forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb978eaaTahinli2 months ago2527 commits

decode.rs23549 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 pub(crate) cdef_bits: std::cell::Cell<u8>,
73 pub(crate) bit_depth: std::cell::Cell<u8>,
74 pub(crate) superres: std::cell::Cell<(u32, u32)>,
75 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
76 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
77 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
78 pub(crate) delta_q_present: std::cell::Cell<bool>,
79 pub(crate) delta_q_res: std::cell::Cell<i32>,
80 pub(crate) current_q_idx: std::cell::Cell<i32>,
81 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
82 pub(crate) delta_lf_present: std::cell::Cell<bool>,
83 pub(crate) delta_lf_res: std::cell::Cell<i32>,
84 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
85 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
86 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
87 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
88 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
89 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
90 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
91 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
92 pub(crate) cur_segment_id: std::cell::Cell<u8>,
93 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
94 pub(crate) tx_select_inter: std::cell::Cell<bool>,
95 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
96 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
97 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
98 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
99 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
100 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
101 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
102 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
103 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
104 pub(crate) inter_last_mc:
105 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
106 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
107 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
108 pub(crate) reach_sb_px: std::cell::Cell<usize>,
109 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
110 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
111 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
112 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
113 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
114 /// so a superblock's records do not regrow the vector from nothing.
115 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
116 /// lane-recoparse: the coefficient grids of the recorded ops above, one
117 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
118 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
119 /// before the op is published, read only by whoever replays that op, and
120 /// handed over WITH the ops at every drain point ([`wave_submit`],
121 /// [`flush_recon`]), so offsets are always relative to the live arena.
122 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
123 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
124 /// path (a submitted job's arena travels to its worker instead).
125 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
126 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
127 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
128 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
129 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
130 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
131 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
132 /// `None` while the queue is in use (wavefront workers) and outside a
133 /// tile. See [`push_op`].
134 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
135 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
136 /// writes are handed to, at more than one reconstruction thread.
137 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
138 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
139 /// thread last handed a superblock to the wavefront.
140 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
141}
142
143impl std::fmt::Debug for FrameCtx {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 f.write_str("FrameCtx")
146 }
147}
148
149impl FrameCtx {
150 /// A fresh context, every field at the default its thread-local
151 /// predecessor was born with.
152 pub(crate) fn new() -> Self {
153 Self {
154 sb128_flag: std::cell::Cell::new(false),
155 cdef_bits: std::cell::Cell::new(0),
156 bit_depth: std::cell::Cell::new(8),
157 superres: std::cell::Cell::new((0, 8)),
158 cdef_transmitted: std::cell::Cell::new(false),
159 cdef_sb_cols: std::cell::Cell::new(0),
160 capture_stages: std::cell::Cell::new(false),
161 stages: std::cell::RefCell::new(None),
162 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
163 delta_q_present: std::cell::Cell::new(false),
164 delta_q_res: std::cell::Cell::new(1),
165 current_q_idx: std::cell::Cell::new(0),
166 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
167 y_dc: 0,
168 u_dc: 0,
169 u_ac: 0,
170 v_dc: 0,
171 v_ac: 0,
172 }),
173 delta_lf_present: std::cell::Cell::new(false),
174 delta_lf_res: std::cell::Cell::new(1),
175 delta_lf_multi: std::cell::Cell::new(false),
176 current_delta_lf: std::cell::Cell::new([0; 4]),
177 seg: std::cell::RefCell::new(SegmentationParams::default()),
178 seg_ids: std::cell::RefCell::new(Vec::new()),
179 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
180 seg_mi_dims: std::cell::Cell::new((0, 0)),
181 above_seg_pred: std::cell::RefCell::new(Vec::new()),
182 left_seg_pred: std::cell::RefCell::new(Vec::new()),
183 cur_segment_id: std::cell::Cell::new(0),
184 seg_tile_origin: std::cell::Cell::new((0, 0)),
185 tx_select_inter: std::cell::Cell::new(false),
186 reduced_tx_set_inter: std::cell::Cell::new(true),
187 enable_filter_intra_inter: std::cell::Cell::new(false),
188 palette_pred: std::cell::RefCell::new(None),
189 intrabc_mi_grid: std::cell::RefCell::new(None),
190 intrabc_dv: std::cell::Cell::new(None),
191 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
192 intrabc_chroma_tx: std::cell::Cell::new(None),
193 intra_in_inter_mode: std::cell::Cell::new(None),
194 inter_strip_chroma: std::cell::Cell::new(None),
195 inter_last_mc: std::cell::Cell::new(None),
196 enable_edge_filter: std::cell::Cell::new(false),
197 last_frame_wide_margin: std::cell::RefCell::new(None),
198 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
199 grain_bit_depth: std::cell::Cell::new(8),
200 recon_ops: std::cell::RefCell::new(Vec::new()),
201 recon_spare: std::cell::RefCell::new(Vec::new()),
202 coeff_arena: std::cell::RefCell::new(Vec::new()),
203 coeff_spare: std::cell::RefCell::new(Vec::new()),
204 pred_arena: std::cell::RefCell::new(Vec::new()),
205 pred_spare: std::cell::RefCell::new(Vec::new()),
206 recon_planes: std::cell::Cell::new(None),
207 wave: std::cell::RefCell::new(None),
208 wave_mark: std::cell::Cell::new(None),
209 }
210 }
211}
212
213/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
214/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
215/// `with` still wins for the scratch pools and gate counters that stay
216/// thread-local.
217pub(crate) trait WithRef {
218 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
219 f(self)
220 }
221}
222impl<T: ?Sized> WithRef for T {}
223
224/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
225///
226/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
227/// and the post-decode filter chain reads exactly these fields: the bit depth
228/// (every kernel's clamp and threshold shift), the segmentation table
229/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
230/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
231/// default -- a field that turns out to be read after all shows up as a hash
232/// mismatch in
233/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
234pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
235 let out = FrameCtx::new();
236 out.bit_depth.set(fctx.bit_depth.get());
237 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
238 out.superres.set(fctx.superres.get());
239 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
240 out.seg.replace(fctx.seg.borrow().clone());
241 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
242 out
243}
244
245use crate::cdf;
246use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
247use crate::encode::{Picture, Reach};
248use crate::intra::predict;
249use crate::mc;
250use crate::msac::SymbolDecoder;
251use crate::mvstack::{
252 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
253 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
254 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
255 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
256 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
257};
258use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
259use crate::transform::{TxType, dequant_and_inverse_typed_wh};
260
261const PARTITION_NONE: usize = 0;
262const PARTITION_HORZ: usize = 1;
263const PARTITION_VERT: usize = 2;
264const PARTITION_SPLIT: usize = 3;
265const PARTITION_HORZ_A: usize = 4;
266const PARTITION_HORZ_B: usize = 5;
267const PARTITION_VERT_A: usize = 6;
268const PARTITION_VERT_B: usize = 7;
269const PARTITION_HORZ_4: usize = 8;
270const PARTITION_VERT_4: usize = 9;
271const SB_MI: u32 = 16;
272const BLOCK_MI: u32 = 8;
273
274// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
275// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
276// superblock's own top-left mi?", the loop-restoration read's unit span, the
277// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
278// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
279// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
280// inside a 128 superblock).
281thread_local! {
282 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
283 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
284 /// prints gigabytes otherwise). Unset = every frame, as before.
285 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
286 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
287}
288
289/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
290/// that frame's DECODE-order index.
291pub fn set_coeff_trace_frame(idx: usize) {
292 COEFF_TRACE_FRAME.with(|c| {
293 if c.get().is_none() {
294 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
295 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
296 // unset: keep tracing every frame, as before this rung existed
297 Err(_) => usize::MAX - 1,
298 };
299 c.set(Some(want));
300 }
301 });
302 COEFF_TRACE_CUR.with(|c| c.set(idx));
303 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
304 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
305 }
306}
307
308pub(crate) fn coeff_trace_on() -> bool {
309 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
310 return false;
311 }
312 match COEFF_TRACE_FRAME.with(|c| c.get()) {
313 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
314 // env var unset: trace every frame.
315 None => true,
316 Some(w) if w >= usize::MAX - 1 => true,
317 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
318 }
319}
320
321
322/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
323pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
324 fctx.sb128_flag.with(|c| c.set(v));
325 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
326}
327
328fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
329 fctx.sb128_flag.with(|c| c.get())
330}
331
332/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
333pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
334 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
335}
336
337// How many real 128-level partition symbols this decoder has read, and how
338// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
339// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
340thread_local! {
341 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
342 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
343 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
344}
345
346/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
347/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
348/// 5.11.4), which this decoder used to read and throw away.
349#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
350pub(crate) fn part128_gathered_symbols() -> usize {
351 PART128_GATHERED_SYMBOLS.with(|c| c.get())
352}
353
354/// Current value of [`PART128_SYMBOLS`].
355#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
356pub(crate) fn part128_symbols() -> usize {
357 PART128_SYMBOLS.with(|c| c.get())
358}
359
360/// Current value of [`PART128_SPLIT_HITS`].
361#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
362pub(crate) fn part128_split_hits() -> usize {
363 PART128_SPLIT_HITS.with(|c| c.get())
364}
365
366/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
367/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
368/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
369/// the 64/32 levels sum 6.
370fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
371 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
372 [32768 - split, 32768, 0]
373}
374
375/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
376const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
377const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
378
379// How many `use_filter_intra` symbols this decoder has read as `1`, across
380// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
381// tests read (before/after, not the absolute value) to prove a stream
382// actually exercised the filter-intra predictor rather than silently
383// skipping it.
384thread_local! {
385 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
386 const { std::cell::Cell::new(0) };
387}
388
389/// Current value of [`FILTER_INTRA_HITS`].
390#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
391pub(crate) fn filter_intra_hits() -> usize {
392 FILTER_INTRA_HITS.with(|c| c.get())
393}
394
395// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
396// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
397// `read_filter_intra_mode_info` call), which no gate exercised before this
398// round -- every inter gate recipe passed `--enable-filter-intra=0`.
399thread_local! {
400 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
401 const { std::cell::Cell::new(0) };
402}
403
404/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
405#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
406pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
407 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
408}
409
410// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
411// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
412// arms refused a nonzero luma delta before this round, and no inter gate
413// enabled `--enable-angle-delta` (aomenc's own default is 1).
414thread_local! {
415 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
416 const { std::cell::Cell::new(0) };
417 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
418 const { std::cell::Cell::new(0) };
419}
420
421/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
422#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
423pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
424 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
425}
426
427/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
428#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
429pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
430 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
431}
432
433// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
434// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
435// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
436// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
437thread_local! {
438 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
439 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
440 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
441}
442
443thread_local! {
444 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
445}
446
447/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
448/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
449#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
450pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
451 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
452}
453
454/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
455/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
456#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
457pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
458 (
459 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
460 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
461 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
462 )
463}
464
465// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
466// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
467// frame-level flag through the recursive block decode -- `0` (the default)
468// makes every call a true no-op, matching every existing gate stream's
469// `cdef_bits == 0` behaviour exactly.
470// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
471// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
472// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
473// blocks every non-8-bit stream from reaching a decode call, so this is `8`
474// on every path that runs today -- threading it now (rather than the literal
475// `8`) is stage 1 of widening past that refusal without re-deriving every
476// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
477// depth (this decoder's own internal choice, matches dav1d/libaom).
478/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
479/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
480pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
481 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
482}
483/// The current stream's bit depth, for callers (e.g. dequant) that need the
484/// raw value rather than the derived clamp bound.
485pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
486 fctx.bit_depth.with(std::cell::Cell::get)
487}
488/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
489/// [`crate::stream`]'s decode loop.
490pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
491 fctx.bit_depth.with(|c| c.set(bit_depth));
492}
493
494 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
495 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
496 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
497 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
498 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
499 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
500 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
501 /// superres arms). Set once per frame from [`crate::stream`]'s decode
502 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
503 /// so a later frame never inherits it.
504
505/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
506/// `denom` 8) for a frame that is not superres-scaled.
507pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
508 fctx.superres.with(|c| c.set((upscaled_width, denom)));
509}
510
511/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
512/// (libaom `av1_superres_scaled`), else `None`.
513pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
514 let (w, d) = fctx.superres.with(std::cell::Cell::get);
515 (w > 0 && d != 8).then_some((w, d))
516}
517// Whether this superblock's single CDEF unit (this decoder has no 128x128
518// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
519// read -- reset to `false` at the top of each superblock in the two tile
520// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
521// Number of superblock columns in the current tile's grid, so
522// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
523// [`CDEF_IDX_GRID`].
524// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
525// which of the header's `1 << cdef.bits` strength pairs applies to that
526// superblock's samples.
527// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
528// has read, across every call on the current thread -- the gate's proof that a
529// `cdef_bits > 0` stream actually reached the new reader rather than every
530// superblock coincidentally being all-skip.
531thread_local! {
532 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
533}
534
535// How many times a warp was suppressed for one PLANE because that plane's own
536// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
537// reconinter.c) -- the gate's proof that a stream really carries the shape,
538// since the square `side`/`chroma_side` can be 8 or more while the plane's
539// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
540thread_local! {
541 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
542}
543
544/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
545#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
546pub(crate) fn warp_plane_suppress_hits() -> usize {
547 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
548}
549
550/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
551/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
552/// block dimensions decide it -- never the square `side`/`chroma_side`, which
553/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
554/// bigger than the real block in one axis.
555pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
556 if w >= 8 && h >= 8 {
557 return true;
558 }
559 hit!(WARP_PLANE_SUPPRESS_HITS);
560 false
561}
562
563/// Current value of [`CDEF_IDX_HITS`].
564#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
565pub(crate) fn cdef_idx_hits() -> usize {
566 CDEF_IDX_HITS.with(|c| c.get())
567}
568
569// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
570// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
571// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
572// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
573// instead of from the coarse 16x16 cell.
574thread_local! {
575 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
576 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
577 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
578}
579
580/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
581#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
582pub(crate) fn intra_in_inter_txctx_hits() -> usize {
583 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
584}
585
586/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
587#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
588pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
589 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
590}
591
592/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
593#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
594pub(crate) fn edge_filter_mi_fix_hits() -> usize {
595 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
596}
597
598// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
599// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
600// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
601// true no-op, matching every existing gate stream's `delta_q_present == 0`
602// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
603// The running quantizer index (spec `CurrentQIndex`, libaom
604// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
605// top of every tile (spec `decode_tile`), carried across superblocks within
606// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
607// dequantization call sites instead of the frame-constant `base_q_idx`.
608// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
609// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
610// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
611// back at every dequantization call site keyed on which plane it is doing.
612// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
613// read, across every call on the current thread -- the gate's proof that a
614// `delta_q_present` stream actually reached the new reader.
615thread_local! {
616 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
617}
618
619/// Current value of [`DELTA_Q_HITS`].
620#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
621pub(crate) fn delta_q_hits() -> usize {
622 DELTA_Q_HITS.with(|c| c.get())
623}
624
625/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
626/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
627/// one), so it is always `0` here.
628fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
629 let d = fctx.quant_deltas.with(|c| c.get());
630 match plane_idx {
631 0 => (d.y_dc, 0),
632 1 => (d.u_dc, d.u_ac),
633 _ => (d.v_dc, d.v_ac),
634 }
635}
636
637/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
638/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
639/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
640/// A no-op when `delta_q_present` is unset, or when this block is not at the
641/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
642/// libaom, collapsed here to a position check since a partition tree's
643/// top-left leaf is the only block that can ever land there), or when that
644/// leaf both *is* the whole superblock and is `skip` (the one case libaom
645/// itself skips the read, state carrying over unchanged).
646fn 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) {
647 if !fctx.delta_q_present.with(|c| c.get()) {
648 return;
649 }
650 let sb_mi = sb_mi_cur(fctx) as usize;
651 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
652 return;
653 }
654 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
655 // computed against the sequence's own superblock size (lane-sb128b r1:
656 // it used to be hardcoded against 64 and disabled under `sb128`, which a
657 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
658 // wrong).
659 if is_whole_sb && skip {
660 return;
661 }
662 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
663 const DELTA_Q_SMALL: i32 = 3;
664 if abs >= DELTA_Q_SMALL {
665 let rem_bits = dec.literal(3) + 1;
666 let thr = (1i32 << rem_bits) + 1;
667 abs = dec.literal(rem_bits) as i32 + thr;
668 }
669 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
670 let reduced = if sign_negative { -abs } else { abs };
671 hit!(DELTA_Q_HITS);
672 let res = fctx.delta_q_res.with(|c| c.get());
673 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
674}
675
676// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
677// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
678// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
679// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
680// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
681// updates index 0 and every reader treats that as the value for all 4
682// indices (spec `read_delta_lf_params`'s own single-cdf branch).
683// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
684// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
685thread_local! {
686 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
687}
688
689/// Current value of [`DELTA_LF_HITS`].
690#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
691pub(crate) fn delta_lf_hits() -> usize {
692 DELTA_LF_HITS.with(|c| c.get())
693}
694
695/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
696/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
697/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
698/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
699/// read once into index 0 otherwise.
700fn 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) {
701 if !fctx.delta_lf_present.with(|c| c.get()) {
702 return;
703 }
704 let sb_mi = sb_mi_cur(fctx) as usize;
705 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
706 return;
707 }
708 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
709 // computed against the sequence's own superblock size (lane-sb128b r1:
710 // it used to be hardcoded against 64 and disabled under `sb128`, which a
711 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
712 // wrong).
713 if is_whole_sb && skip {
714 return;
715 }
716 let multi = fctx.delta_lf_multi.with(|c| c.get());
717 let res = fctx.delta_lf_res.with(|c| c.get());
718 let count = if multi { 4 } else { 1 };
719 let mut cur = fctx.current_delta_lf.with(|c| c.get());
720 for i in 0..count {
721 let mut abs = if multi {
722 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
723 } else {
724 dec.symbol(&mut cdfs.delta_lf) as i32
725 };
726 const DELTA_LF_SMALL: i32 = 3;
727 if abs >= DELTA_LF_SMALL {
728 let rem_bits = dec.literal(3) + 1;
729 let thr = (1i32 << rem_bits) + 1;
730 abs = dec.literal(rem_bits) as i32 + thr;
731 }
732 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
733 let reduced = if sign_negative { -abs } else { abs };
734 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
735 hit!(DELTA_LF_HITS);
736 }
737 fctx.current_delta_lf.with(|c| c.set(cur));
738}
739
740/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
741/// after `skip` is known at every block-decode call site. A no-op at
742/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
743/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
744/// `allow_intrabc`, so neither needs a separate check here. Reads once per
745/// superblock, at the first non-skip block.
746fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
747 let bits = fctx.cdef_bits.with(|c| c.get());
748 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
749 return;
750 }
751 let idx = dec.literal(u32::from(bits)) as u8;
752 fctx.cdef_transmitted.with(|c| c.set(true));
753 hit!(CDEF_IDX_HITS);
754 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
755 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
756 if sb_cols > 0 {
757 fctx.cdef_idx_grid.with(|g| {
758 let mut g = g.borrow_mut();
759 let i = sb_r * sb_cols + sb_c;
760 if i < g.len() {
761 g[i] = idx;
762 }
763 });
764 }
765}
766
767// ---------------------------------------------------------------------------
768// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
769// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
770// the two consumers a real stream exercises: the per-segment quantizer index
771// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
772// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
773// `read_intra_segment_id`/`read_inter_segment_id` and
774// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
775// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
776// is what the oracle every gate here compares against actually does.
777thread_local! {
778 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
779 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
780 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
781 /// this frame has no primary reference (spec `load_previous_segment_ids`).
782 /// `(mi_rows, mi_cols)` for both maps above.
783 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
784 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
785 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
786 /// The block currently being decoded -- read back by [`block_q_idx`].
787 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
788 /// How many real `segment_id` symbols were read, and the set of segment
789 /// ids any block ended up with -- the gate's proof the feature fired.
790 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
791 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
792 /// How many `seg_id_predicted` symbols were read (temporal update).
793 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
794}
795
796/// Installs this frame's segmentation parameters and allocates its map, with
797/// `prev` the primary reference frame's saved map (spec
798/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
799/// slot). Called once per frame, whether or not segmentation is enabled.
800pub(crate) fn set_segmentation(
801 seg: SegmentationParams,
802 mi_rows: usize,
803 mi_cols: usize,
804 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
805) {
806 fctx.seg.with(|s| *s.borrow_mut() = seg);
807 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
808 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
809 fctx.prev_seg_ids.with(|m| {
810 let mut m = m.borrow_mut();
811 m.clear();
812 if let Some(p) = prev {
813 if p.len() == mi_rows * mi_cols {
814 m.extend_from_slice(p);
815 }
816 }
817 });
818 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
819 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
820 fctx.cur_segment_id.with(|c| c.set(0));
821}
822
823/// This frame's decoded segment map, to be stored into whichever reference
824/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
825pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
826 fctx.seg_ids.with(|m| m.borrow().clone())
827}
828
829/// How many `segment_id` symbols have been read (never reset per frame).
830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
831pub(crate) fn segment_id_hits() -> usize {
832 SEG_ID_HITS.with(|c| c.get())
833}
834
835/// How many distinct segment ids any decoded block has carried.
836#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
837pub(crate) fn segment_ids_seen() -> usize {
838 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
839}
840
841/// How many `seg_id_predicted` symbols have been read (temporal update).
842#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
843pub(crate) fn segment_pred_hits() -> usize {
844 SEG_PRED_HITS.with(|c| c.get())
845}
846
847/// Resets the segmentation hit counters (gate setup).
848#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
849pub(crate) fn reset_segment_hits() {
850 SEG_ID_HITS.with(|c| c.set(0));
851 SEG_IDS_SEEN.with(|c| c.set(0));
852 SEG_PRED_HITS.with(|c| c.set(0));
853}
854
855/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
856/// being decoded, with its `FeatureData` value.
857fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
858 fctx.seg.with(|s| {
859 let s = s.borrow();
860 s.feature_active(segment_id, feature)
861 .then(|| i32::from(s.feature_data[segment_id][feature]))
862 })
863}
864
865/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
866/// `av1_get_qindex`) for the block currently being decoded: the running
867/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
868/// Every dequant call site reads the block's quantizer through here.
869fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
870 let base = fctx.current_q_idx.with(|c| c.get());
871 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
872 match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
873 Some(data) => (base + data).clamp(0, 255),
874 None => base,
875 }
876}
877
878/// The segment id recorded for one mi cell of the current frame's map.
879fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
880 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
881 if mi_r >= mi_rows || mi_c >= mi_cols {
882 return 0;
883 }
884 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
885}
886
887/// `set_segment_id`: stamps `id` over every mi cell this block covers.
888fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
889 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
890 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
891 fctx.seg_ids.with(|m| {
892 let mut m = m.borrow_mut();
893 for y in 0..y_mis {
894 for x in 0..x_mis {
895 m[(mi_r + y) * mi_cols + mi_c + x] = id;
896 }
897 }
898 });
899 fctx.cur_segment_id.with(|c| c.set(id));
900 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
901}
902
903/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
904/// `last_frame_seg_map`): the minimum previous-frame segment id over the
905/// block's own mi footprint. `0` when there is no previous map.
906fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
907 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
908 fctx.prev_seg_ids.with(|m| {
909 let m = m.borrow();
910 if m.is_empty() {
911 return 0;
912 }
913 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
914 let mut id = u8::MAX;
915 for y in 0..y_mis {
916 for x in 0..x_mis {
917 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
918 }
919 }
920 if id == u8::MAX { 0 } else { id }
921 })
922}
923
924/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
925fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
926 if reference == 0 {
927 return diff;
928 }
929 if reference >= max - 1 {
930 return max - diff - 1;
931 }
932 let half = if 2 * reference < max {
933 diff <= 2 * reference
934 } else {
935 diff <= 2 * (max - reference - 1)
936 };
937 if half {
938 return if diff & 1 != 0 {
939 reference + ((diff + 1) >> 1)
940 } else {
941 reference - (diff >> 1)
942 };
943 }
944 if 2 * reference < max { diff } else { max - (diff + 1) }
945}
946
947/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
948/// frame's already-decoded above/left/above-left neighbours.
949fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
950 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
951 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
952 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
953 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
954 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
955 let ctx = match prev_ul {
956 None => 0,
957 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
958 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
959 Some(_) => 0,
960 };
961 let pred = match (prev_u, prev_l) {
962 (None, l) => l.unwrap_or(0),
963 (Some(u), None) => u,
964 (Some(u), Some(l)) => {
965 if prev_ul == Some(u) {
966 u
967 } else {
968 l
969 }
970 }
971 };
972 (pred, ctx)
973}
974
975/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
976/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
977/// that prediction. Does NOT write the map -- callers do.
978fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
979 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
980 if skip {
981 return pred as u8;
982 }
983 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
984 hit!(SEG_ID_HITS);
985 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
986 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
987}
988
989/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
990/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
991/// caller decides which by passing `pre_skip`).
992fn intra_segment_id(
993 dec: &mut SymbolDecoder,
994 cdfs: &mut Cdfs,
995 mi_r: usize,
996 mi_c: usize,
997 w_mi: usize,
998 h_mi: usize,
999 skip: bool, fctx: &crate::decode::FrameCtx,
1000) {
1001 if !fctx.seg.with(|s| s.borrow().enabled) {
1002 return;
1003 }
1004 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1005 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1006}
1007
1008/// Whether this frame's intra blocks read their `segment_id` before `skip`
1009/// (`SegIdPreSkip`); `false` also when segmentation is off.
1010fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1011 fctx.seg.with(|s| {
1012 let s = s.borrow();
1013 s.enabled && s.seg_id_pre_skip
1014 })
1015}
1016
1017/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1018/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1019/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1020fn inter_segment_id(
1021 dec: &mut SymbolDecoder,
1022 cdfs: &mut Cdfs,
1023 mi_r: usize,
1024 mi_c: usize,
1025 w_mi: usize,
1026 h_mi: usize,
1027 skip: bool,
1028 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1029) {
1030 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1031 let s = s.borrow();
1032 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1033 });
1034 if !enabled {
1035 return;
1036 }
1037 if !update_map {
1038 // The map is inherited wholesale from the previous frame.
1039 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1040 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1041 return;
1042 }
1043 if pre_skip && !pre_skip_frame {
1044 return;
1045 }
1046 if !pre_skip && skip {
1047 // libaom: a skipped block never codes `seg_id_predicted`, and its
1048 // segment id is the spatial prediction.
1049 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1050 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1051 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1052 return;
1053 }
1054 let id = if temporal_update {
1055 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1056 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1057 hit!(SEG_PRED_HITS);
1058 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1059 if predicted {
1060 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1061 } else {
1062 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1063 }
1064 } else {
1065 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1066 };
1067 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1068}
1069
1070/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1071fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1072 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1073 // so contribute 0) outside the tile -- the availability check here is
1074 // what keeps a previous tile's stamps out of this tile's context.
1075 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1076 let above = if mi_r > row0 {
1077 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1078 } else {
1079 0
1080 };
1081 let left = if mi_c > col0 {
1082 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1083 } else {
1084 0
1085 };
1086 usize::from(above + left)
1087}
1088
1089/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1090fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1091 fctx.above_seg_pred.with(|m| {
1092 let mut m = m.borrow_mut();
1093 for i in 0..w_mi {
1094 if let Some(cell) = m.get_mut(mi_c + i) {
1095 *cell = value;
1096 }
1097 }
1098 });
1099 fctx.left_seg_pred.with(|m| {
1100 let mut m = m.borrow_mut();
1101 for i in 0..h_mi {
1102 if let Some(cell) = m.get_mut(mi_r + i) {
1103 *cell = value;
1104 }
1105 }
1106 });
1107}
1108
1109// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1110// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1111// counter, proving a stream actually put a directional block next to a
1112// smooth-predicted neighbour rather than every block reading the (previously
1113// hardcoded `false`) edge-filter strength bucket unchanged.
1114thread_local! {
1115 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1116 const { std::cell::Cell::new(0) };
1117}
1118
1119/// Current value of [`SMOOTH_LUMA_HITS`].
1120#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1121pub(crate) fn smooth_luma_hits() -> usize {
1122 SMOOTH_LUMA_HITS.with(|c| c.get())
1123}
1124
1125thread_local! {
1126 /// lane-band46 r1: how many split-transform units answered their intra
1127 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1128 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1129 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1130 /// transform unit whose above-right / below-left reference samples would
1131 /// be wrong without that fix.
1132 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1133 const { std::cell::Cell::new(0) };
1134}
1135
1136/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1137#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1138pub(crate) fn split_tu_reach_fix_hits() -> usize {
1139 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1140}
1141
1142/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1143/// answer differs from the standalone-block answer the call sites used before
1144/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1145/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1146/// block's top-left `(px, py)`.
1147#[allow(clippy::too_many_arguments)]
1148fn tu_reach(
1149 bw: usize,
1150 bh: usize,
1151 col_off: usize,
1152 row_off: usize,
1153 tx: usize,
1154 block: Reach,
1155 px: usize,
1156 py: usize,
1157 width: usize,
1158 height: usize, fctx: &crate::decode::FrameCtx,
1159) -> Reach {
1160 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1161 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1162 if fixed != standalone {
1163 hit!(SPLIT_TU_REACH_FIX_HITS);
1164 }
1165 fixed
1166}
1167
1168// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1169// across every call on the current thread -- lane-chroma r3's own before/after
1170// counter, proving a stream actually exercised chroma's smooth/paeth
1171// predictor (the previously-refused round-2 gap) rather than every block
1172// landing on DC/CFL/directional.
1173thread_local! {
1174 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1175 const { std::cell::Cell::new(0) };
1176}
1177
1178/// Current value of [`SMOOTH_UV_HITS`].
1179#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1180pub(crate) fn smooth_uv_hits() -> usize {
1181 SMOOTH_UV_HITS.with(|c| c.get())
1182}
1183
1184// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1185// full superblock walk over, across every call on the current thread --
1186// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1187// multi-tile stream must prove more than one tile actually fired, not just
1188// that the stream carried tile_info.cols > 1.
1189thread_local! {
1190 static TILE_HITS: std::cell::Cell<usize> =
1191 const { std::cell::Cell::new(0) };
1192}
1193/// Current value of [`TILE_HITS`].
1194#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1195pub(crate) fn tile_hits() -> usize {
1196 TILE_HITS.with(|c| c.get())
1197}
1198
1199// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1200// selected for filtering, across every call on the current thread -- the same
1201// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1202// exercised `apply_deblock` rather than every edge landing on level 0.
1203thread_local! {
1204 static DEBLOCK_HITS: std::cell::Cell<usize> =
1205 const { std::cell::Cell::new(0) };
1206}
1207/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1208/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1209/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1210static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1211 std::sync::atomic::AtomicUsize::new(0);
1212
1213/// Current value of [`DEBLOCK_HITS`].
1214#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1215pub(crate) fn deblock_hits() -> usize {
1216 DEBLOCK_HITS.with(|c| c.get())
1217}
1218
1219// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1220// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1221// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1222// stream built with `--enable-onesided-comp=1` really exercised the
1223// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1224thread_local! {
1225 static UNI_COMP_HITS: std::cell::Cell<usize> =
1226 const { std::cell::Cell::new(0) };
1227}
1228
1229/// Current value of [`UNI_COMP_HITS`].
1230#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1231pub(crate) fn uni_comp_hits() -> usize {
1232 UNI_COMP_HITS.with(|c| c.get())
1233}
1234
1235// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1236// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1237// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1238// blend and not only the wedge arm.
1239thread_local! {
1240 static DIFFWTD_HITS: std::cell::Cell<usize> =
1241 const { std::cell::Cell::new(0) };
1242}
1243
1244/// Current value of [`DIFFWTD_HITS`].
1245#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1246pub(crate) fn diffwtd_hits() -> usize {
1247 DIFFWTD_HITS.with(|c| c.get())
1248}
1249
1250// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1251// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1252// this decoder's square inter path reaches), so no `compound_type` symbol is
1253// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1254// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1255thread_local! {
1256 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1257 const { std::cell::Cell::new(0) };
1258}
1259
1260/// Current value of [`DIFFWTD_INFERRED_HITS`].
1261#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1262pub(crate) fn diffwtd_inferred_hits() -> usize {
1263 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1264}
1265
1266// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1267// with `show_frame == 0`, output later by a `show_existing_frame` header
1268// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1269// `stream::decode_stream`, which is where the frame header is consumed; the
1270// gate's proof that the on-value really reached the bitstream rather than
1271// being dropped by the rate control.
1272thread_local! {
1273 static FWD_KF_HITS: std::cell::Cell<usize> =
1274 const { std::cell::Cell::new(0) };
1275}
1276
1277/// Current value of [`FWD_KF_HITS`].
1278#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1279pub(crate) fn fwd_kf_hits() -> usize {
1280 FWD_KF_HITS.with(|c| c.get())
1281}
1282
1283/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1284pub(crate) fn note_fwd_kf() {
1285 hit!(FWD_KF_HITS);
1286}
1287
1288// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1289// the block's own side, across every call on the current thread -- the same
1290// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1291// actually exercised a *split* transform under `TxMode::Select` rather than
1292// every block coincidentally resolving `depth=0` (indistinguishable from
1293// `TxMode::Largest` pixel-wise).
1294thread_local! {
1295 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1296 const { std::cell::Cell::new(0) };
1297}
1298
1299// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1300// transform smaller than their own side (`tx_depth != 0`) while coding a
1301// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1302// only exercises with aomenc's tx-size search left ON (its default), which
1303// every older recipe in this file pins off. Counted at the block, so a stream
1304// where RD happened to give every split-transform block a DC chroma mode
1305// reads as zero rather than silently passing for free.
1306thread_local! {
1307 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1308 const { std::cell::Cell::new(0) };
1309}
1310
1311/// Current value of [`SQ_CHROMA_TX_HITS`].
1312#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1313pub(crate) fn sq_chroma_tx_hits() -> usize {
1314 SQ_CHROMA_TX_HITS.with(|c| c.get())
1315}
1316
1317/// Current value of [`TX_DEPTH_HITS`].
1318#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1319pub(crate) fn tx_depth_hits() -> usize {
1320 TX_DEPTH_HITS.with(|c| c.get())
1321}
1322
1323// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1324// read, and how many of those actually took the split, on the current thread
1325// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1326// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1327// coincidentally coding one whole-block transform.
1328thread_local! {
1329 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1330 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1331 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1332 // strips coded one whole-block rect transform unit, and how many split
1333 // their rect max transform into square sub-transforms.
1334 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1335 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1336 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1337 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1338 // truncated low-32 corner.
1339 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1340 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1341 // inter strip, `[32x8, 8x32]`.
1342 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1343 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1344 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1345 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1346 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1347 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1348 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1349 // frame -- 16x8 and 8x16 inter leaves.
1350 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1351 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1352 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1353 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1354 // `decode_inter_block` already carries forty parameters and both are
1355 // frame-constant.
1356 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1357 // frame-constant like the two above and stashed the same way -- an intra
1358 // block inside an inter frame reads `use_filter_intra` under it.
1359}
1360
1361/// Current value of [`TXFM_SPLIT_READS`].
1362#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1363pub(crate) fn txfm_split_reads() -> usize {
1364 TXFM_SPLIT_READS.with(|c| c.get())
1365}
1366
1367/// Current value of [`TXFM_SPLIT_HITS`].
1368#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1369pub(crate) fn txfm_split_hits() -> usize {
1370 TXFM_SPLIT_HITS.with(|c| c.get())
1371}
1372
1373/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1374#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1375pub(crate) fn inter_leaf16_horz_hits() -> usize {
1376 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1377}
1378
1379/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1380#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1381pub(crate) fn inter_leaf16_vert_hits() -> usize {
1382 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1383}
1384
1385/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1386pub(crate) fn rect_inter_tu_hits() -> usize {
1387 RECT_INTER_TU_HITS.with(|c| c.get())
1388}
1389
1390/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1391pub(crate) fn rect_inter_txsplit_hits() -> usize {
1392 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1393}
1394
1395/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1396pub(crate) fn rect64_inter_tu_hits() -> usize {
1397 RECT64_INTER_TU_HITS.with(|c| c.get())
1398}
1399
1400/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1401/// whole-block luma units of a 32x32-level 1:4 inter strip.
1402pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1403 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1404}
1405
1406/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1407/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1408pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1409 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1410}
1411
1412/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1413/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1414pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1415 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1416}
1417
1418/// Records one rectangular var-tx leaf.
1419fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1420 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1421 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1422 }
1423 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1424 cell.with(|c| {
1425 let mut h = c.get();
1426 h[usize::from(th > tw)] += 1;
1427 c.set(h);
1428 });
1429}
1430
1431/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1432/// [`ENABLE_FILTER_INTRA_INTER`].
1433pub(crate) fn set_inter_tx_mode(
1434 tx_select: bool,
1435 reduced_tx_set: bool,
1436 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1437) {
1438 fctx.tx_select_inter.with(|c| c.set(tx_select));
1439 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1440 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1441}
1442
1443// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1444// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1445// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1446// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1447// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1448// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1449// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1450// path above).
1451thread_local! {
1452 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1453 const { std::cell::Cell::new(0) };
1454}
1455
1456/// Current value of [`VERT_B_INTRA_HITS`].
1457#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1458pub(crate) fn vert_b_intra_hits() -> usize {
1459 VERT_B_INTRA_HITS.with(|c| c.get())
1460}
1461
1462// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1463// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1464// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1465// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1466// every arm separately so a run where aomenc's RD only picked one cannot
1467// pass as proof of four.
1468thread_local! {
1469 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1470}
1471
1472// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1473thread_local! {
1474 /// 4x4 transform units decoded inside an 8x8 square of a
1475 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1476 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1477 /// a real `--enable-tx-size-search=1` stream reaches it.
1478 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1479}
1480
1481#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1482pub(crate) fn vert_ab_tx4_hits() -> usize {
1483 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1484}
1485
1486#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1487pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1488 AB16_HITS.with(std::cell::Cell::get)
1489}
1490
1491fn bump_ab16(arm: usize) {
1492 hit_do! {
1493 AB16_HITS.with(|c| {
1494 let mut v = c.get();
1495 v[arm] += 1;
1496 c.set(v);
1497 });
1498 }
1499}
1500
1501// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1502// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1503// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1504// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1505// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1506// superblock's z-order recursion, not raster mi position).
1507thread_local! {
1508 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1509 const { std::cell::Cell::new(0) };
1510}
1511
1512/// Current value of [`HORZ_VERT_INTRA_HITS`].
1513#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1514pub(crate) fn horz_vert_intra_hits() -> usize {
1515 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1516}
1517
1518// How many blocks were decoded as a frame-edge rect strip -- the single
1519// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1520// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1521// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1522// paths share the counter.
1523thread_local! {
1524 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1525 const { std::cell::Cell::new(0) };
1526}
1527
1528/// Current value of [`EDGE_RECT_STRIP_HITS`].
1529#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1530pub(crate) fn edge_rect_strip_hits() -> usize {
1531 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1532}
1533
1534// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1535// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1536// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1537// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1538// are height mod 16 == 8, so every inter frame crosses these nodes.
1539thread_local! {
1540 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1541 const { std::cell::Cell::new([0; 6]) };
1542}
1543
1544/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1545pub(crate) fn bump_inter_edge_strip(idx: usize) {
1546 hit_do! {
1547 INTER_EDGE_STRIP_HITS.with(|c| {
1548 let mut v = c.get();
1549 v[idx] += 1;
1550 c.set(v);
1551 });
1552 }
1553}
1554
1555// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1556// forced split -- libaom `decode_partition` (decodeframe.c):
1557// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1558// straddle case that reads NO symbol at all. Indexed by level:
1559// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1560thread_local! {
1561 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1562 const { std::cell::Cell::new([0; 4]) };
1563}
1564
1565fn bump_edge_both_cut(level: usize) {
1566 hit_do! {
1567 EDGE_BOTH_CUT_HITS.with(|c| {
1568 let mut v = c.get();
1569 v[level] += 1;
1570 c.set(v);
1571 });
1572 }
1573}
1574
1575/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1576pub fn inter_edge_strip_hits() -> [usize; 6] {
1577 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1578}
1579
1580/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1581/// into the next one (class `counter-from-refused-stream`).
1582pub fn reset_inter_edge_strip_hits() {
1583 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1584}
1585
1586/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1587#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1588pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1589 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1590}
1591
1592/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1593#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1594pub(crate) fn reset_edge_both_cut_hits() {
1595 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1596}
1597
1598// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1599// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1600// the case every rect path here refused by name before, and the first
1601// refusal the user's ReelB extract (600s in) stops at.
1602thread_local! {
1603 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1604 const { std::cell::Cell::new(0) };
1605}
1606
1607/// Current value of [`RECT_SPLIT_TX_HITS`].
1608#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1609pub(crate) fn rect_split_tx_hits() -> usize {
1610 RECT_SPLIT_TX_HITS.with(|c| c.get())
1611}
1612
1613// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1614// side 64) AND split past the first depth, i.e. tiled more than one unit in
1615// each axis -- the only shape with a transform unit that has neighbours on
1616// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1617// no gate fired before lane-rectsplit r2 (the shared counter above also
1618// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1619thread_local! {
1620 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1621 const { std::cell::Cell::new(0) };
1622}
1623
1624/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1625#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1626pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1627 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1628}
1629
1630// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1631// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1632// chroma half takes that had no coefficient tables before (index order:
1633// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1634// proves the pair it happens to hit cannot catch a transposed scan/context
1635// table (class scan-weights-cross-axis).
1636thread_local! {
1637 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1638 const { std::cell::Cell::new([0; 4]) };
1639}
1640
1641/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1642#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1643pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1644 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1645}
1646
1647// How many HORZ/VERT intra strips actually predicted with filter intra
1648// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1649// ("this decoder predicts square-only") until `predict_filter_intra` took
1650// `bw`x`bh`.
1651thread_local! {
1652 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1653 const { std::cell::Cell::new(0) };
1654}
1655
1656/// Current value of [`FILTER_INTRA_RECT_HITS`].
1657#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1658pub(crate) fn filter_intra_rect_hits() -> usize {
1659 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1660}
1661
1662// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1663// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1664// was never read at all before that round, so a gate needs to prove the flag
1665// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1666// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1667// carry different probabilities (18101 vs 20229), so a transposed pair is
1668// only caught by a gate that sees the flag fire on BOTH shapes (class
1669// scan-weights-cross-axis).
1670thread_local! {
1671 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1672 const { std::cell::Cell::new(0) };
1673 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1674 const { std::cell::Cell::new(0) };
1675}
1676
1677/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1678#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1679pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1680 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1681}
1682
1683/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1685pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1686 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1687}
1688
1689// How many rectangular transform units actually coded coefficients through
1690// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1691// exercised the rect coefficient reader at all rather than passing on
1692// all-skip blocks.
1693thread_local! {
1694 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1695 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1696}
1697
1698/// Current value of [`RECT_COEFF_TU_HITS`].
1699#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1700pub(crate) fn rect_coeff_tu_hits() -> usize {
1701 RECT_COEFF_TU_HITS.with(|c| c.get())
1702}
1703
1704/// Rectangular transform units whose resolved `tx_type` is a 1D class
1705/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1706/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1707/// for the square reader's own 1D types.
1708#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1709pub(crate) fn rect_class1_hits() -> usize {
1710 RECT_CLASS1_HITS.with(|c| c.get())
1711}
1712
1713// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1714// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1715// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1716// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1717// prove nothing about the new shapes.
1718thread_local! {
1719 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1720 const { std::cell::Cell::new(0) };
1721}
1722
1723/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1725pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1726 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1727}
1728
1729// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1730// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1731// counter would be satisfied by a 16x8 strip and prove nothing here.
1732thread_local! {
1733 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1734 const { std::cell::Cell::new(0) };
1735}
1736
1737/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1738#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1739pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1740 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1741}
1742
1743// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1744// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1745// call on the current thread -- the same before/after counter pattern as
1746// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1747// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1748// landing on `DCT_DCT`.
1749thread_local! {
1750 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1751 const { std::cell::Cell::new(0) };
1752}
1753
1754// How many `uv_mode` reads resolved to a directional chroma mode (neither
1755// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1756// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1757// actually exercised chroma's own directional predictor.
1758thread_local! {
1759 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1760 const { std::cell::Cell::new(0) };
1761}
1762
1763/// Current value of [`DIRECTIONAL_UV_HITS`].
1764#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1765pub(crate) fn directional_uv_hits() -> usize {
1766 DIRECTIONAL_UV_HITS.with(|c| c.get())
1767}
1768
1769// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1770// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1771// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1772// proving a stream actually exercised a nonzero angle delta.
1773thread_local! {
1774 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1775 const { std::cell::Cell::new(0) };
1776}
1777
1778// How many [`read_single_ref`] reads resolved to a reference other than
1779// `LAST_FRAME`, across every call on the current thread -- the same before/after
1780// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1781// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1782// only other supported one so far) rather than every block coincidentally
1783// resolving `LAST_FRAME`.
1784thread_local! {
1785 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1786 const { std::cell::Cell::new(0) };
1787}
1788
1789/// Current value of [`NON_LAST_REF_HITS`].
1790#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1791pub(crate) fn non_last_ref_hits() -> usize {
1792 NON_LAST_REF_HITS.with(|c| c.get())
1793}
1794
1795// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1796// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1797// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1798// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1799// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1800// `GOLDEN_FRAME` draw it did not ask for.
1801thread_local! {
1802 static LAST2_HITS: std::cell::Cell<usize> =
1803 const { std::cell::Cell::new(0) };
1804}
1805thread_local! {
1806 static LAST3_HITS: std::cell::Cell<usize> =
1807 const { std::cell::Cell::new(0) };
1808}
1809thread_local! {
1810 static GOLDEN_HITS: std::cell::Cell<usize> =
1811 const { std::cell::Cell::new(0) };
1812}
1813thread_local! {
1814 static BWDREF_HITS: std::cell::Cell<usize> =
1815 const { std::cell::Cell::new(0) };
1816}
1817thread_local! {
1818 static ALTREF2_HITS: std::cell::Cell<usize> =
1819 const { std::cell::Cell::new(0) };
1820}
1821thread_local! {
1822 static ALTREF_HITS: std::cell::Cell<usize> =
1823 const { std::cell::Cell::new(0) };
1824}
1825
1826// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1827// -- proves a `reference_select` stream actually reached a block that picked
1828// compound, not just that the header bit was set. Every such block is
1829// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1830// so this only ever counts attempted reads, never a completed decode.
1831thread_local! {
1832 static COMP_MODE_HITS: std::cell::Cell<usize> =
1833 const { std::cell::Cell::new(0) };
1834}
1835
1836/// Current value of [`COMP_MODE_HITS`].
1837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1838pub(crate) fn comp_mode_hits() -> usize {
1839 COMP_MODE_HITS.with(|c| c.get())
1840}
1841
1842// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1843// use for, across every call on the current thread -- the same before/after
1844// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1845// exercised palette reconstruction rather than only reading and refusing the
1846// `palette_y_mode` symbol.
1847thread_local! {
1848 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1849}
1850
1851/// Current value of [`PALETTE_HITS`].
1852#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1853pub(crate) fn palette_hits() -> usize {
1854 PALETTE_HITS.with(|c| c.get())
1855}
1856
1857// lane-tiles r12: of those, how many sat at their own TILE's left column --
1858// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1859// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1860// palette gate that never hits one proves nothing about the tile guard.
1861thread_local! {
1862 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1863}
1864
1865/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1866#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1867pub(crate) fn palette_tile_left_hits() -> usize {
1868 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1869}
1870
1871// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1872// palette use -- proves a stream actually reconstructed UV palette pixels,
1873// not just read and refused the `palette_uv_mode` symbol.
1874thread_local! {
1875 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1876}
1877
1878/// Current value of [`PALETTE_UV_HITS`].
1879#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1880pub(crate) fn palette_uv_hits() -> usize {
1881 PALETTE_UV_HITS.with(|c| c.get())
1882}
1883
1884// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1885// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1886// (not just the square path's) actually fired.
1887thread_local! {
1888 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1889}
1890
1891/// Current value of [`PALETTE_RECT_HITS`].
1892#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1893pub(crate) fn palette_rect_hits() -> usize {
1894 PALETTE_RECT_HITS.with(|c| c.get())
1895}
1896
1897// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1898// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1899// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1900// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1901// RD, almost always refused-on-use because the block doesn't end up USING a
1902// palette -- see r5's report). This is the site the removed refusal
1903// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1904// fired here whether or not the block picked a palette, so this is the
1905// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1906// never observes.
1907thread_local! {
1908 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1909}
1910
1911/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1912#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1913pub(crate) fn rect_screen_content_hits() -> usize {
1914 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1915}
1916
1917// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1918// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1919// windowing actually ran, not just that the whole-block path stayed exact.
1920// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1921// first actually incremented in r7, when the refusal it guarded was lifted.
1922thread_local! {
1923 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1924}
1925
1926thread_local! {
1927 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1928 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1929 /// (16x8/8x16), the two shapes the lifted refusals named.
1930 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1931}
1932
1933/// Current value of [`RECT4_PALETTE_HITS`].
1934#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1935pub(crate) fn rect4_palette_hits() -> usize {
1936 RECT4_PALETTE_HITS.with(|c| c.get())
1937}
1938
1939/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1940#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1941pub(crate) fn palette_split_tx_hits() -> usize {
1942 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1943}
1944
1945thread_local! {
1946 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1947 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1948 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1949 /// `--min-partition-size=8` puts them on this leaf path.
1950 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1951}
1952
1953/// Current value of [`PALETTE_LEAF8_HITS`].
1954#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1955pub(crate) fn palette_leaf8_hits() -> usize {
1956 PALETTE_LEAF8_HITS.with(|c| c.get())
1957}
1958
1959/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
1960#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1961pub(crate) fn reset_palette_leaf8_hits() {
1962 PALETTE_LEAF8_HITS.with(|c| c.set(0));
1963}
1964
1965thread_local! {
1966 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
1967 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
1968 /// block that also carries a real, corner-cropped luma transform.
1969 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1970}
1971
1972/// Current value of [`PALETTE_SB_STRIP_HITS`].
1973#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1974pub(crate) fn palette_sb_strip_hits() -> usize {
1975 PALETTE_SB_STRIP_HITS.with(|c| c.get())
1976}
1977
1978/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
1979#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1980pub(crate) fn reset_palette_sb_strip_hits() {
1981 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
1982}
1983
1984// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
1985// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
1986// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
1987// capability rather than the key frame's, which every screen stream also
1988// carries.
1989thread_local! {
1990 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1991 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1992}
1993
1994// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
1995// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
1996// shared counter too, so only this one proves a gate really reached the leaf
1997// where the refusal used to sit.
1998thread_local! {
1999 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2000 const { std::cell::Cell::new((0, 0)) };
2001}
2002
2003/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2004pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2005 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2006}
2007
2008/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2009pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2010 (
2011 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2012 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2013 )
2014}
2015
2016// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2017// and which are therefore predicted one transform unit at a time (a skipped
2018// block codes no coefficients, so nothing else in the stream witnesses this
2019// path -- only the pixels do).
2020thread_local! {
2021 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2022}
2023
2024/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2025pub fn skip_split_tx_hits() -> usize {
2026 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2027}
2028
2029/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2030pub fn reset_skip_split_tx_hits() {
2031 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2032}
2033
2034// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2035// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2036// the gate's proof that the lifted path actually ran, per size.
2037thread_local! {
2038 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2039 const { std::cell::Cell::new([0; 4]) };
2040}
2041
2042/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2043#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2044pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2045 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2046}
2047
2048 /// A just-decoded palette-Y block's own predicted pixels
2049 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2050 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2051 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2052 /// per-block override through `read_plane`'s two dozen call sites is the
2053 /// alternative this avoids). Always empty again once that call consumes
2054 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2055 /// sees stale state.
2056
2057
2058/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2059/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2060/// site whose reconstruct never runs would be picked up by the NEXT block's
2061/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2062/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2063#[track_caller]
2064fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2065 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2066 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2067 eprintln!(
2068 "PALSET len={} stale={stale} at {}",
2069 buf.len(),
2070 std::panic::Location::caller()
2071 );
2072 }
2073 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2074}
2075
2076#[track_caller]
2077fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2078 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2079 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2080 eprintln!(
2081 "PALTAKE len={:?} at {}",
2082 got.as_ref().map(Vec::len),
2083 std::panic::Location::caller()
2084 );
2085 }
2086 got
2087}
2088
2089/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2090/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2091/// pixels, because at parse time this block's own luma is still queued.
2092#[derive(Clone, Copy, Debug)]
2093pub(crate) struct CflSrc {
2094 px: usize,
2095 py: usize,
2096 bw: usize,
2097 bh: usize,
2098 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2099 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2100 rect: bool,
2101}
2102
2103fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2104 CflSrc { px, py, bw: side, bh: side, rect: false }
2105}
2106
2107fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2108 CflSrc { px, py, bw, bh, rect: true }
2109}
2110
2111/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2112/// instead of executed. Each variant is the resolved argument tuple of the
2113/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2114/// order performs exactly the same writes in exactly the same order --
2115/// entropy parsing no longer touches the frame's own planes (except the two
2116/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2117/// the replay on a superblock-row wavefront worker.
2118/// The dequantization + inverse transform of one transform unit, kept as its
2119/// INPUTS so that a recorded write carries the work instead of its result
2120/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2121/// recon worker, not on the parsing thread. `stride == 0` means the dense
2122/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2123/// `reconstruct_mc_rect` reads both of its buffers at.
2124#[derive(Clone, Copy)]
2125pub(crate) struct TxParams {
2126 pub(crate) w: usize,
2127 pub(crate) h: usize,
2128 pub(crate) bit_depth: u8,
2129 pub(crate) q_idx: i32,
2130 pub(crate) dc_delta: i32,
2131 pub(crate) ac_delta: i32,
2132 pub(crate) tx_type: TxType,
2133 pub(crate) stride: usize,
2134}
2135
2136impl TxParams {
2137 /// The one copy of the produce-the-residual code: the inline path calls it
2138 /// on the parse thread, the wavefront worker calls it on its own, so both
2139 /// are the same function on the same inputs and byte-identical.
2140 fn run(self, grid: &[i32]) -> Vec<i32> {
2141 let residual = dequant_and_inverse_typed_wh(
2142 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2143 self.tx_type,
2144 );
2145 // An all-zero grid transforms to the empty marker, and a strided copy
2146 // of zeros is still zeros: the marker passes straight through.
2147 if residual.is_empty() {
2148 return residual;
2149 }
2150 if self.stride == 0 {
2151 return residual;
2152 }
2153 let mut strided = vec![0i32; self.stride * self.stride];
2154 for row in 0..self.h {
2155 strided[row * self.stride..][..self.w]
2156 .copy_from_slice(&residual[row * self.w..][..self.w]);
2157 }
2158 strided
2159 }
2160}
2161
2162/// A recorded write's residual: already transformed, or the coefficients and
2163/// [`TxParams`] the worker transforms itself.
2164pub(crate) enum Residual {
2165 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2166 /// `len` is the all-zero marker [`dense_residual`] expands.
2167 Done(u32, u32),
2168 /// The coefficients live in the pushing tile's arena
2169 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2170 /// len)` in it.
2171 Coeffs(TxParams, u32, u32),
2172}
2173
2174impl Residual {
2175 /// The record for a transform unit whose coefficient grid is all zero:
2176 /// the empty marker, so neither the grid nor the residual is cloned and
2177 /// the worker never runs the transform (60% of the 4K segment's units).
2178 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2179 if is_zero_grid(grid) {
2180 return Self::Done(0, 0);
2181 }
2182 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2183 }
2184
2185 /// A residual the parse thread already transformed, kept in the arena
2186 /// instead of its own `Vec`.
2187 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2188 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2189 // which is exactly the all-zero marker -- one pointer compare instead
2190 // of copying up to 64 KB of zeros into the arena per block.
2191 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2192 return Self::Done(0, 0);
2193 }
2194 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2195 }
2196
2197 /// The residual to reconstruct with; `scratch` is where a transform run
2198 /// on this thread lands, so the caller owns that buffer.
2199 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2200 match self {
2201 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2202 Self::Coeffs(p, off, len) => {
2203 *scratch = p.run(&arena[off as usize..][..len as usize]);
2204 scratch
2205 }
2206 }
2207 }
2208}
2209
2210/// Appends to the tile's coefficient arena, returning the offset the record
2211/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2212fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2213 fctx.coeff_arena.with(|a| {
2214 let mut a = a.borrow_mut();
2215 let off = a.len();
2216 a.extend_from_slice(v);
2217 off as u32
2218 })
2219}
2220
2221/// [`push_coeffs`] for a recorded prediction.
2222fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2223 fctx.pred_arena.with(|a| {
2224 let mut a = a.borrow_mut();
2225 let off = a.len();
2226 a.extend_from_slice(v);
2227 off as u32
2228 })
2229}
2230
2231/// An all-zero residual, for the transform units that code no coefficient:
2232/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2233/// and the reconstruction loops below read this instead of a per-unit
2234/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2235/// (a 128-wide inter block's prediction stride).
2236pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2237
2238/// lane-blockscratch: one plane's coefficient levels as the block-tail
2239/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2240/// strip with no chroma, luma under a var-tx split whose units already wrote
2241/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2242/// zeroing up to 64 KB of its own per block.
2243#[derive(Clone)]
2244enum Grid {
2245 Zero(usize),
2246 Own(Vec<i32>),
2247}
2248
2249/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2250/// unit that writes into it. Only a block wider or taller than 64 px codes its
2251/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2252/// collectors per block and then drop them untouched.
2253fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2254 if v.is_empty() {
2255 *v = vec![0i32; n];
2256 }
2257 v
2258}
2259
2260impl std::ops::Deref for Grid {
2261 type Target = [i32];
2262 fn deref(&self) -> &[i32] {
2263 match self {
2264 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2265 Grid::Own(v) => v,
2266 }
2267 }
2268}
2269
2270/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2271/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2272/// transform units that code no coefficient without the scan (lane-coefgrid).
2273pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2274 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2275}
2276
2277/// `residual`, or `n` zeros when it is the empty all-zero marker.
2278fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2279 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2280}
2281
2282/// Where a recorded motion-compensated write reads its prediction from.
2283///
2284/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2285/// the parse thread's single biggest reconstruction cost, so at
2286/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2287/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2288/// runs it into its own three-plane slot, and every transform unit of that
2289/// block then reads its window out of that slot ([`Pred::Cur`]).
2290#[derive(Clone, Copy)]
2291pub(crate) enum Pred<'a> {
2292 /// A prediction the parse thread already built, at its own stride
2293 /// (`stride == 0` means "the reader's own `stride` argument").
2294 Inline(&'a [u16], usize),
2295 /// The current block's deferred prediction: plane, its stride, and this
2296 /// unit's offset into it.
2297 Cur { plane: usize, stride: usize, off: usize },
2298}
2299
2300impl<'a> Pred<'a> {
2301 /// The same prediction read at an explicit stride.
2302 fn view(self, stride: usize) -> Self {
2303 match self {
2304 Self::Inline(b, _) => Self::Inline(b, stride),
2305 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2306 }
2307 }
2308 /// The materialised buffer and the stride to read it at (`stride` is the
2309 /// reader's own when this prediction was built dense); `None` for a
2310 /// deferred prediction, which only a recorded op can carry.
2311 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2312 match self {
2313 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2314 Self::Cur { .. } => None,
2315 }
2316 }
2317 /// This prediction's window starting `n` samples in.
2318 fn offset(self, n: usize) -> Self {
2319 match self {
2320 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2321 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2322 }
2323 }
2324}
2325
2326/// [`Pred`], resolved into what a recorded op carries.
2327pub(crate) enum PredSrc {
2328 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2329 Owned(u32, u32),
2330 /// A window of the block prediction: its plane, its offset, and the
2331 /// stride it is read at -- which is the block's, not necessarily the
2332 /// op's (a transform unit's residual stays dense, so the worker takes
2333 /// its window out of the block prediction itself).
2334 Cur { plane: usize, off: usize, src: usize },
2335}
2336
2337/// One block's whole-block prediction build, deferred to a recon worker.
2338///
2339/// The closure borrows the tile's reference pictures and its own frame-level
2340/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2341/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2342/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2343pub(crate) struct PredBuild(
2344 Box<
2345 dyn FnOnce(
2346 &mut PlaneBuf<'static>,
2347 &mut PlaneBuf<'static>,
2348 &mut PlaneBuf<'static>,
2349 &crate::decode::FrameCtx,
2350 // lane-blockmem: the previous block's three prediction buffers,
2351 // refilled in place -- the build used to return three fresh
2352 // `Vec`s per block and drop these.
2353 &mut [Vec<u16>; 3],
2354 ),
2355 >,
2356);
2357
2358// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2359// pictures and frame tables, and the closure runs on exactly one worker.
2360#[allow(unsafe_code)]
2361unsafe impl Send for PredBuild {}
2362
2363/// `true` when this tile's writes are recorded for the wavefront instead of
2364/// performed at the push site, i.e. when a prediction may be deferred.
2365fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2366 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2367}
2368
2369/// The previous block's prediction buffer, cleared and zero-filled to `n`
2370/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2371/// without the per-block allocation and free.
2372fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2373 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2374 // than resized element by element -- which is every block on the inline
2375 // path, where there is no previous buffer to reuse.
2376 if v.capacity() < n {
2377 return vec![0u16; n];
2378 }
2379 v.clear();
2380 v.resize(n, 0);
2381 v
2382}
2383
2384/// Records one block's prediction build for the worker that reconstructs it.
2385#[allow(unsafe_code)]
2386fn push_pred<'a>(
2387 fctx: &crate::decode::FrameCtx,
2388 f: impl FnOnce(
2389 &mut PlaneBuf<'static>,
2390 &mut PlaneBuf<'static>,
2391 &mut PlaneBuf<'static>,
2392 &crate::decode::FrameCtx,
2393 &mut [Vec<u16>; 3],
2394 ) + 'a,
2395) {
2396 type Dyn<'x> = dyn FnOnce(
2397 &mut PlaneBuf<'static>,
2398 &mut PlaneBuf<'static>,
2399 &mut PlaneBuf<'static>,
2400 &crate::decode::FrameCtx,
2401 &mut [Vec<u16>; 3],
2402 ) + 'x;
2403 let boxed: Box<Dyn<'a>> = Box::new(f);
2404 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2405 // before the borrows the closure holds go out of scope.
2406 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2407 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2408}
2409
2410/// One superblock's recorded writes plus the two arenas they index -- the
2411/// unit a wavefront worker takes off the queue (lane-recoparse).
2412pub(crate) struct ReconJob {
2413 ops: Vec<ReconOp>,
2414 coeffs: Vec<i32>,
2415 preds: Vec<u16>,
2416}
2417
2418pub(crate) enum ReconOp {
2419 /// lane-wave4: build this block's prediction into the worker's slot.
2420 Pred(PredBuild),
2421 Intra {
2422 plane: usize,
2423 x: usize,
2424 y: usize,
2425 bw: usize,
2426 bh: usize,
2427 /// `true` when the parse site called `reconstruct_rect` (whose
2428 /// `edges_rect` differs from `edges` even at `bw == bh`).
2429 rect: bool,
2430 mode: usize,
2431 angle_delta: i32,
2432 reach: Reach,
2433 residual: Residual,
2434 cfl: Option<(i32, CflSrc)>,
2435 filter_intra: Option<usize>,
2436 smooth_neighbor: bool,
2437 /// The palette/intrabc prediction override, taken off
2438 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2439 /// from that slot by the replay.
2440 pred: Option<Vec<u16>>,
2441 },
2442 Mc {
2443 plane: usize,
2444 x: usize,
2445 y: usize,
2446 stride: usize,
2447 w: usize,
2448 h: usize,
2449 prediction: PredSrc,
2450 residual: Residual,
2451 },
2452}
2453
2454/// The three planes of the tile currently being decoded, as raw pointers.
2455///
2456/// corner-cut: at one reconstruction thread a recorded write must cost
2457/// nothing -- deferring it to the end of the superblock is +1.2%
2458/// instructions and +4.5% wall on 4K, because the residual is written at
2459/// parse and read back cache-cold at replay. So the recorded op is performed
2460/// at the push site instead, through the pointers the tile decoder registers
2461/// once ([`ReconInline`]), which is the same thread, the same order and the
2462/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2463/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2464/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2465/// threading the three planes down every `read_plane`/`read_inter_plane`
2466/// call site (~40) so the push site owns the borrow it writes through.
2467#[derive(Clone, Copy)]
2468pub(crate) struct ReconPlanes(
2469 *mut PlaneBuf<'static>,
2470 *mut PlaneBuf<'static>,
2471 *mut PlaneBuf<'static>,
2472);
2473
2474// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2475// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2476// value travelling is `None`; the pointers never leave the tile decoder's
2477// own thread.
2478#[allow(unsafe_code)]
2479unsafe impl Send for ReconPlanes {}
2480// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2481// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2482// contract, one superblock per band instead of one row band.
2483#[allow(unsafe_code)]
2484unsafe impl Sync for ReconPlanes {}
2485
2486/// Registers the tile's planes for inline reconstruction and unregisters them
2487/// on every exit from the tile decoder, including the `?` ones -- a stale
2488/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2489/// tile.
2490pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2491
2492#[allow(unsafe_code)]
2493impl<'a> ReconInline<'a> {
2494 /// Installs the guard for this tile when reconstruction is inline
2495 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2496 /// to the queue instead, for the wavefront workers to replay.
2497 fn install(
2498 fctx: &'a crate::decode::FrameCtx,
2499 y: &mut PlaneBuf<'static>,
2500 u: &mut PlaneBuf<'static>,
2501 v: &mut PlaneBuf<'static>,
2502 ) -> Option<Self> {
2503 if crate::par::recon_threads() != 1 {
2504 return None;
2505 }
2506 // SAFETY: the planes are locals of the tile decoder and outlive the
2507 // guard, which is dropped on every exit from it (including `?`); see
2508 // [`ReconPlanes`] for the aliasing trade-off.
2509 let planes = ReconPlanes(
2510 std::ptr::from_mut(y),
2511 std::ptr::from_mut(u),
2512 std::ptr::from_mut(v),
2513 );
2514 fctx.recon_planes.with(|c| c.set(Some(planes)));
2515 Some(Self(fctx))
2516 }
2517}
2518
2519impl Drop for ReconInline<'_> {
2520 fn drop(&mut self) {
2521 self.0.recon_planes.with(|c| c.set(None));
2522 }
2523}
2524
2525#[allow(unsafe_code)]
2526fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2527 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2528 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2529 // the parse site would have performed itself before lane-wave1.
2530 // The inline path never records coefficients (the transform runs at
2531 // the push site), so the arena is not read here.
2532 unsafe {
2533 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2534 };
2535 return;
2536 }
2537 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2538}
2539
2540/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2541/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2542///
2543/// The parser keeps parsing and never touches the planes; each superblock's
2544/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2545/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2546/// four of their 64x64 visits, since a 128 block writes across quadrants).
2547/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2548/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2549/// every pixel an intra predictor can read (its edges reach one block right
2550/// along the row above and one block down the column to the left, both
2551/// inside those two neighbours) and every CfL AC read (this block's own
2552/// luma, written by this same job). Jobs are handed out in raster order, so
2553/// the oldest outstanding one always has its dependencies met: no deadlock.
2554///
2555/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2556/// `thread_local!` and miss every worker, which is why the default is 1.
2557pub(crate) struct WaveState {
2558 q: std::sync::Mutex<WaveQueue>,
2559 cv: std::sync::Condvar,
2560 planes: ReconPlanes,
2561 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2562 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2563 bit_depth: u8,
2564 enable_edge_filter: bool,
2565 last_col: usize,
2566}
2567
2568struct WaveQueue {
2569 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2570 /// row's front job can ever be runnable -- a job waits on its own left
2571 /// neighbour -- so a worker takes the lowest row whose front job's
2572 /// dependencies are met. Popping the raster-oldest job instead (what
2573 /// this replaced) put every worker on the SAME row, where the wavefront
2574 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2575 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
2576 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2577 /// walking it.
2578 queued: usize,
2579 /// Per superblock row, the last column reconstructed (-1 = none yet).
2580 done: Vec<isize>,
2581 /// Per superblock row, the last column PARSED (submitted, whether or not
2582 /// it recorded any write) and the last column actually pushed as a job
2583 /// (-1 = none). A row is fully reconstructed once it has been parsed to
2584 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2585 /// reads that to release the row's filters (see [`wave_rows_complete`]).
2586 last_sub: Vec<isize>,
2587 last_push: Vec<isize>,
2588 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2589 active: usize,
2590 closed: bool,
2591 /// lane-sballoc: the three per-superblock buffers a finished job hands
2592 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
2593 /// first-touch page faults) instead of the `Vec::with_capacity` it used
2594 /// to make per superblock -- 3 allocations and 3 frees per superblock,
2595 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
2596 /// inside the queue's own mutex, which both sides already take.
2597 free: Vec<JobBufs>,
2598 free_cap: usize,
2599}
2600
2601/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
2602type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
2603
2604impl WaveQueue {
2605 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2606 /// or `None` (with the blocking condition counted when instrumented).
2607 fn take_runnable(
2608 &mut self,
2609 last_col: usize,
2610 stats: bool,
2611 ) -> Option<(usize, usize, ReconJob)> {
2612 let mut blocked: Option<bool> = None;
2613 for r in 0..self.rows.len() {
2614 let Some(front) = self.rows[r].front() else {
2615 continue;
2616 };
2617 let c = front.0;
2618 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2619 let left = c == 0 || self.done[r] >= c as isize - 1;
2620 if above && left {
2621 let (c, job) = self.rows[r].pop_front().expect("front checked above");
2622 self.queued -= 1;
2623 return Some((r, c, job));
2624 }
2625 if blocked.is_none() {
2626 blocked = Some(above);
2627 }
2628 }
2629 if stats {
2630 match blocked {
2631 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2632 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2633 None => 0,
2634 };
2635 }
2636 None
2637 }
2638}
2639
2640/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2641/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2642/// empty queue), how far ahead the parse thread is, and how often the two
2643/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2644/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2645/// whole run.
2646const WS_SLOTS: usize = 16;
2647use std::sync::atomic::AtomicU64;
2648use std::sync::atomic::Ordering::Relaxed;
2649static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2650static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2651static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2652static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2653static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2654static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2655/// Parse-thread time between two submits, i.e. everything parse still does
2656/// itself (symbol decode plus the predictions not deferred).
2657static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2658/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2659/// (the intrabc/interintra reads) and at the tile's end.
2660static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2661static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2662static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2663static WS_TILES: AtomicU64 = AtomicU64::new(0);
2664
2665fn wave_stats() -> bool {
2666 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2667 match ON.load(Relaxed) {
2668 0 => {
2669 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2670 .map(|v| v.trim() == "1")
2671 .unwrap_or(false);
2672 ON.store(1 + u8::from(on), Relaxed);
2673 on
2674 }
2675 n => n == 2,
2676 }
2677}
2678
2679fn wave_stats_dump() {
2680 let ms = |n: u64| n as f64 / 1e6;
2681 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2682 for i in 0..WS_SLOTS {
2683 let jobs = WS_JOBS[i].load(Relaxed);
2684 if jobs == 0 {
2685 continue;
2686 }
2687 s += &format!(
2688 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2689 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2690 ms(WS_BUSY[i].load(Relaxed)),
2691 ms(WS_WAIT[i].load(Relaxed)),
2692 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2693 );
2694 }
2695 s += &format!(
2696 " | pipe={}/{}",
2697 PIPE_FRAMES.load(Relaxed),
2698 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2699 );
2700 s += &format!(
2701 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2702 ms(WS_PARSE.load(Relaxed)),
2703 ms(WS_BARRIER.load(Relaxed)),
2704 WS_BARRIERS.load(Relaxed),
2705 ms(WS_DRAIN.load(Relaxed)),
2706 WS_BLOCK_ABOVE.load(Relaxed),
2707 WS_BLOCK_LEFT.load(Relaxed),
2708 );
2709 eprintln!("{s}");
2710}
2711
2712#[allow(unsafe_code)]
2713fn wave_worker(st: &WaveState, idx: usize) {
2714 let fctx = FrameCtx::new();
2715 fctx.bit_depth.set(st.bit_depth);
2716 fctx.enable_edge_filter.set(st.enable_edge_filter);
2717 let stats = wave_stats();
2718 let slot = idx.min(WS_SLOTS - 1);
2719 loop {
2720 let t0 = std::time::Instant::now();
2721 let mut q = st.q.lock().unwrap();
2722 let (r, c, job) = loop {
2723 if let Some(job) = q.take_runnable(st.last_col, stats) {
2724 break job;
2725 }
2726 if q.closed && q.queued == 0 {
2727 return;
2728 }
2729 q = st.cv.wait(q).unwrap();
2730 };
2731 q.active += 1;
2732 drop(q);
2733 if stats {
2734 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2735 WS_JOBS[slot].fetch_add(1, Relaxed);
2736 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
2737 }
2738 let t1 = std::time::Instant::now();
2739 let ReconPlanes(y, u, v) = st.planes;
2740 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2741 // every superblock that could have written or be reading them is
2742 // complete by the wavefront rule above.
2743 let mut cur: [Vec<u16>; 3] = Default::default();
2744 let ReconJob { mut ops, mut coeffs, mut preds } = job;
2745 unsafe {
2746 for op in ops.drain(..) {
2747 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
2748 }
2749 }
2750 if stats {
2751 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2752 }
2753 coeffs.clear();
2754 preds.clear();
2755 let mut q = st.q.lock().unwrap();
2756 // lane-sballoc: hand the three buffers back for the next submit.
2757 if q.free.len() < q.free_cap {
2758 q.free.push((ops, coeffs, preds));
2759 }
2760 q.done[r] = c as isize;
2761 q.active -= 1;
2762 st.cv.notify_all();
2763 }
2764}
2765
2766/// Installs the wavefront for one tile and joins its workers on every exit
2767/// from the tile decoder, including the `?` ones -- the jobs hold raw
2768/// pointers into the tile's planes, so no worker may outlive them.
2769/// (lane-pool1: the workers come from this thread's persistent pool, so a
2770/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
2771/// with fresh scratch.)
2772pub(crate) struct WaveGuard<'a>(
2773 &'a crate::decode::FrameCtx,
2774 Option<crate::par::Batch<'static>>,
2775);
2776
2777#[allow(unsafe_code)]
2778impl<'a> WaveGuard<'a> {
2779 fn install(
2780 fctx: &'a crate::decode::FrameCtx,
2781 y: &mut PlaneBuf<'static>,
2782 u: &mut PlaneBuf<'static>,
2783 v: &mut PlaneBuf<'static>,
2784 rows: usize,
2785 cols: usize,
2786 ) -> Option<Self> {
2787 let threads = crate::par::recon_threads();
2788 if threads == 1 || rows == 0 || cols == 0 {
2789 return None;
2790 }
2791 let st = std::sync::Arc::new(WaveState {
2792 q: std::sync::Mutex::new(WaveQueue {
2793 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2794 queued: 0,
2795 done: vec![-1; rows],
2796 last_sub: vec![-1; rows],
2797 last_push: vec![-1; rows],
2798 active: 0,
2799 closed: false,
2800 free: Vec::new(),
2801 free_cap: threads + 2,
2802 }),
2803 cv: std::sync::Condvar::new(),
2804 // SAFETY: the planes are locals of the tile decoder and outlive
2805 // this guard, which joins every worker in `drop`.
2806 planes: ReconPlanes(
2807 std::ptr::from_mut(y),
2808 std::ptr::from_mut(u),
2809 std::ptr::from_mut(v),
2810 ),
2811 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
2812 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
2813 last_col: cols - 1,
2814 });
2815 let batch = crate::par::Batch::new("ec-av1-recon");
2816 for idx in 0..threads {
2817 let st = std::sync::Arc::clone(&st);
2818 batch.submit(move || wave_worker(&st, idx));
2819 }
2820 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2821 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
2822 Some(Self(fctx, Some(batch)))
2823 }
2824}
2825
2826impl Drop for WaveGuard<'_> {
2827 fn drop(&mut self) {
2828 let st = self.0.wave.with(|w| w.borrow_mut().take());
2829 if let Some(st) = st {
2830 st.q.lock().unwrap().closed = true;
2831 st.cv.notify_all();
2832 }
2833 let t0 = std::time::Instant::now();
2834 // Dropping the batch waits every worker out, as the joins did.
2835 drop(self.1.take());
2836 if wave_stats() {
2837 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2838 WS_TILES.fetch_add(1, Relaxed);
2839 wave_stats_dump();
2840 }
2841 }
2842}
2843
2844/// An empty buffer for the next superblock: the recycled one when it is at
2845/// least as big as the superblock just parsed, else a fresh sized one
2846/// (lane-sballoc; `v` is always empty).
2847fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
2848 if v.capacity() < cap {
2849 v.reserve_exact(cap - v.len());
2850 }
2851 v
2852}
2853
2854/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
2855/// when there is no wavefront (one reconstruction thread), in which case the
2856/// caller replays them itself.
2857fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2858 let st = fctx.wave.with(|w| w.borrow().clone());
2859 let Some(st) = st else { return false };
2860 // lane-blockmem: the op list is replaced sized for the next superblock,
2861 // exactly as the two arenas below are -- taking it left a zero-capacity
2862 // `Vec` that regrew (and memmoved every recorded op) from nothing on
2863 // every superblock.
2864 // lane-sballoc: the replacement comes from the finished jobs' free list
2865 // when there is one (warm capacity, already faulted in); only the first
2866 // superblocks of a tile allocate.
2867 let mut q = st.q.lock().unwrap();
2868 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
2869 let ops = fctx.recon_ops.with(|c| {
2870 let mut c = c.borrow_mut();
2871 let cap = c.len();
2872 std::mem::replace(&mut *c, reuse(sops, cap))
2873 });
2874 // The job owns its coefficients: the arena is replaced by an empty one
2875 // sized for the next superblock, so parse never regrows from nothing and
2876 // the worker frees this buffer once, instead of once per unit.
2877 let coeffs = fctx.coeff_arena.with(|c| {
2878 let mut c = c.borrow_mut();
2879 let cap = c.len();
2880 std::mem::replace(&mut *c, reuse(scoeffs, cap))
2881 });
2882 let preds = fctx.pred_arena.with(|c| {
2883 let mut c = c.borrow_mut();
2884 let cap = c.len();
2885 std::mem::replace(&mut *c, reuse(spreds, cap))
2886 });
2887 {
2888 if (c as isize) > q.last_sub[r] {
2889 q.last_sub[r] = c as isize;
2890 }
2891 if !ops.is_empty() {
2892 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
2893 q.queued += 1;
2894 q.last_push[r] = c as isize;
2895 }
2896 drop(q);
2897 st.cv.notify_all();
2898 }
2899 if wave_stats() {
2900 let now = std::time::Instant::now();
2901 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
2902 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
2903 }
2904 }
2905 true
2906}
2907
2908/// Waits until every submitted job is reconstructed, so the parser may read
2909/// the planes itself (the intrabc source fetch and the interintra intra
2910/// predictor -- see [`flush_recon`]).
2911fn wave_barrier(fctx: &crate::decode::FrameCtx) {
2912 let st = fctx.wave.with(|w| w.borrow().clone());
2913 let Some(st) = st else { return };
2914 let stats = wave_stats();
2915 let t0 = std::time::Instant::now();
2916 let mut q = st.q.lock().unwrap();
2917 while q.queued > 0 || q.active > 0 {
2918 q = st.cv.wait(q).unwrap();
2919 }
2920 drop(q);
2921 if stats {
2922 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2923 WS_BARRIERS.fetch_add(1, Relaxed);
2924 }
2925}
2926
2927/// Performs an intra write at its push site when the tile registered its
2928/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
2929/// caller must record it for the wavefront workers instead.
2930#[allow(unsafe_code)]
2931#[allow(clippy::too_many_arguments)]
2932fn inline_intra(
2933 plane: usize,
2934 x: usize,
2935 oy: usize,
2936 bw: usize,
2937 bh: usize,
2938 rect: bool,
2939 mode: usize,
2940 angle_delta: i32,
2941 reach: Reach,
2942 residual: &[i32],
2943 cfl: Option<(i32, CflSrc)>,
2944 filter_intra: Option<usize>,
2945 smooth_neighbor: bool,
2946 fctx: &crate::decode::FrameCtx,
2947) -> bool {
2948 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
2949 return false;
2950 };
2951 let pred = take_palette_pred(fctx);
2952 // SAFETY: see [`ReconPlanes`].
2953 unsafe {
2954 exec_intra(
2955 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
2956 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
2957 );
2958 }
2959 true
2960}
2961
2962/// [`inline_intra`] for a motion-compensated write.
2963#[allow(unsafe_code)]
2964#[allow(clippy::too_many_arguments)]
2965fn inline_mc(
2966 plane: usize,
2967 x: usize,
2968 oy: usize,
2969 stride: usize,
2970 w: usize,
2971 h: usize,
2972 prediction: &[u16],
2973 residual: &[i32],
2974 fctx: &crate::decode::FrameCtx,
2975) -> bool {
2976 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
2977 return false;
2978 };
2979 // SAFETY: see [`ReconPlanes`].
2980 unsafe {
2981 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
2982 }
2983 true
2984}
2985
2986/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
2987#[allow(clippy::too_many_arguments)]
2988fn push_intra(
2989 plane: usize,
2990 x: usize,
2991 y: usize,
2992 side: usize,
2993 mode: usize,
2994 angle_delta: i32,
2995 reach: Reach,
2996 residual: &[i32],
2997 cfl: Option<(i32, CflSrc)>,
2998 filter_intra: Option<usize>,
2999 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3000) {
3001 if inline_intra(
3002 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3003 smooth_neighbor, fctx,
3004 ) {
3005 return;
3006 }
3007 let pred = take_palette_pred(fctx);
3008 push_op(fctx, ReconOp::Intra {
3009 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3010 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3011 });
3012}
3013
3014/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3015#[allow(clippy::too_many_arguments)]
3016fn push_intra_rect(
3017 plane: usize,
3018 x: usize,
3019 y: usize,
3020 bw: usize,
3021 bh: usize,
3022 mode: usize,
3023 angle_delta: i32,
3024 reach: Reach,
3025 residual: &[i32],
3026 cfl: Option<(i32, CflSrc)>,
3027 filter_intra: Option<usize>,
3028 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3029) {
3030 if inline_intra(
3031 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3032 smooth_neighbor, fctx,
3033 ) {
3034 return;
3035 }
3036 let pred = take_palette_pred(fctx);
3037 push_op(fctx, ReconOp::Intra {
3038 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3039 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3040 });
3041}
3042
3043/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3044fn push_mc(
3045 plane: usize,
3046 x: usize,
3047 y: usize,
3048 side: usize,
3049 prediction: Pred<'_>,
3050 residual: &[i32], fctx: &crate::decode::FrameCtx,
3051) {
3052 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3053}
3054
3055/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3056#[allow(clippy::too_many_arguments)]
3057fn push_mc_rect(
3058 plane: usize,
3059 x: usize,
3060 y: usize,
3061 stride: usize,
3062 w: usize,
3063 h: usize,
3064 prediction: Pred<'_>,
3065 residual: &[i32], fctx: &crate::decode::FrameCtx,
3066) {
3067 let (src, stride) = match prediction.inline(stride) {
3068 Some(v) => v,
3069 None => {
3070 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3071 push_op(fctx, ReconOp::Mc {
3072 plane, x, y, stride: ss, w, h,
3073 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3074 residual: Residual::done(residual, fctx),
3075 });
3076 return;
3077 }
3078 };
3079 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3080 return;
3081 }
3082 push_op(fctx, ReconOp::Mc {
3083 plane, x, y, stride, w, h,
3084 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3085 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3086 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3087 residual: Residual::done(residual, fctx),
3088 });
3089}
3090
3091/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3092/// thread the transform runs here, exactly as before; on the wavefront it
3093/// travels with the op and runs on the worker (lane-wave3).
3094#[allow(clippy::too_many_arguments)]
3095fn push_intra_tx(
3096 plane: usize,
3097 x: usize,
3098 y: usize,
3099 bw: usize,
3100 bh: usize,
3101 rect: bool,
3102 mode: usize,
3103 angle_delta: i32,
3104 reach: Reach,
3105 tx: TxParams,
3106 grid: &[i32],
3107 cfl: Option<(i32, CflSrc)>,
3108 filter_intra: Option<usize>,
3109 smooth_neighbor: bool,
3110 fctx: &crate::decode::FrameCtx,
3111) {
3112 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3113 inline_intra(
3114 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3115 smooth_neighbor, fctx,
3116 );
3117 return;
3118 }
3119 let pred = take_palette_pred(fctx);
3120 push_op(fctx, ReconOp::Intra {
3121 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3122 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3123 });
3124}
3125
3126/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3127#[allow(clippy::too_many_arguments)]
3128fn push_mc_rect_tx(
3129 plane: usize,
3130 x: usize,
3131 y: usize,
3132 stride: usize,
3133 w: usize,
3134 h: usize,
3135 prediction: Pred<'_>,
3136 tx: TxParams,
3137 grid: &[i32],
3138 fctx: &crate::decode::FrameCtx,
3139) {
3140 // lane-wave4: a deferred prediction is not there to be windowed -- the
3141 // op carries its offset into the block's prediction instead, and the
3142 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3143 // both buffers at one stride).
3144 let (prediction, stride) = match prediction.inline(stride) {
3145 Some(v) => v,
3146 None => {
3147 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3148 let mut tx = tx;
3149 tx.stride = 0;
3150 push_op(fctx, ReconOp::Mc {
3151 plane, x, y, stride: w, w, h,
3152 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3153 residual: Residual::coeffs(tx, grid, fctx),
3154 });
3155 return;
3156 }
3157 };
3158 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3159 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3160 // stride, so a prediction handed over at the block's stride (a var-tx
3161 // unit's window, lane-wave4) has to be densified for a dense residual
3162 // -- which is exactly what the recorded path below does.
3163 let residual = tx.run(grid);
3164 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3165 let window;
3166 let prediction = if stride == res_stride {
3167 prediction
3168 } else {
3169 debug_assert_eq!(res_stride, w);
3170 let mut win = Vec::with_capacity(w * h);
3171 for row in 0..h {
3172 win.extend_from_slice(&prediction[row * stride..][..w]);
3173 }
3174 window = win;
3175 &window[..]
3176 };
3177 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3178 return;
3179 }
3180 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3181 // two buffers at `stride`, so the record carries that window densely
3182 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3183 // copied 64*64 samples on the PARSING thread before. The residual is then
3184 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3185 // in the same places at stride `w`.
3186 let off = fctx.pred_arena.with(|a| {
3187 let mut a = a.borrow_mut();
3188 let off = a.len();
3189 for row in 0..h {
3190 a.extend_from_slice(&prediction[row * stride..][..w]);
3191 }
3192 off as u32
3193 });
3194 let mut tx = tx;
3195 tx.stride = 0;
3196 push_op(fctx, ReconOp::Mc {
3197 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3198 residual: Residual::coeffs(tx, grid, fctx),
3199 });
3200}
3201
3202/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3203/// and empties the queue (lane-wave1 step (i)).
3204///
3205/// Called at the top of each superblock visit and at the end of each tile, so
3206/// a whole superblock's parsing runs with no plane access at all; the two
3207/// parse-time pixel READS that survive -- the intrabc source fetch and the
3208/// interintra intra predictor -- flush ahead of themselves instead, which
3209/// keeps them byte-exact and names exactly what step (ii) still has to move.
3210fn flush_recon(
3211 fctx: &crate::decode::FrameCtx,
3212 y: &mut PlaneBuf<'static>,
3213 u: &mut PlaneBuf<'static>,
3214 v: &mut PlaneBuf<'static>,
3215) {
3216 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3217 // writes in place, not just this superblock's queue.
3218 wave_barrier(fctx);
3219 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3220 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3221 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3222 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3223 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3224 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3225 let mut cur: [Vec<u16>; 3] = Default::default();
3226 for op in ops.drain(..) {
3227 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3228 }
3229 coeffs.clear();
3230 preds.clear();
3231 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3232 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3233 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3234}
3235
3236/// Performs one recorded write: the body [`flush_recon`] replays, and the
3237/// body [`push_op`] runs immediately when reconstruction is inline.
3238fn exec_op(
3239 op: ReconOp,
3240 y: &mut PlaneBuf<'static>,
3241 u: &mut PlaneBuf<'static>,
3242 v: &mut PlaneBuf<'static>,
3243 cur: &mut [Vec<u16>; 3],
3244 coeffs: &[i32],
3245 preds: &[u16],
3246 fctx: &crate::decode::FrameCtx,
3247) {
3248 let mut scratch = Vec::new();
3249 match op {
3250 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3251 ReconOp::Intra {
3252 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3253 filter_intra, smooth_neighbor, pred,
3254 } => exec_intra(
3255 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3256 residual.resolve(coeffs, &mut scratch),
3257 cfl, filter_intra, smooth_neighbor, pred, fctx,
3258 ),
3259 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3260 let residual = residual.resolve(coeffs, &mut scratch);
3261 match prediction {
3262 PredSrc::Owned(off, len) => {
3263 let p = &preds[off as usize..][..len as usize];
3264 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3265 }
3266 PredSrc::Cur { plane: sp, off, src } => {
3267 let block = std::mem::take(&mut cur[sp]);
3268 if src == stride {
3269 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3270 } else {
3271 // A transform unit's residual is dense, so its window
3272 // of the block prediction is taken out dense too --
3273 // the copy the parsing thread used to make, made here.
3274 let mut window = Vec::with_capacity(w * h);
3275 for row in 0..h {
3276 window.extend_from_slice(&block[off + row * src..][..w]);
3277 }
3278 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3279 }
3280 cur[sp] = block;
3281 }
3282 }
3283 }
3284 }
3285}
3286
3287/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3288/// path ([`push_op`]'s registered planes) reaches it without ever building
3289/// the record -- which is what keeps one reconstruction thread at the cost of
3290/// the pre-lane-wave1 decoder.
3291#[allow(clippy::too_many_arguments)]
3292fn exec_intra(
3293 y: &mut PlaneBuf<'static>,
3294 u: &mut PlaneBuf<'static>,
3295 v: &mut PlaneBuf<'static>,
3296 plane: usize,
3297 x: usize,
3298 oy: usize,
3299 bw: usize,
3300 bh: usize,
3301 rect: bool,
3302 mode: usize,
3303 angle_delta: i32,
3304 reach: Reach,
3305 residual: &[i32],
3306 cfl: Option<(i32, CflSrc)>,
3307 filter_intra: Option<usize>,
3308 smooth_neighbor: bool,
3309 pred: Option<Vec<u16>>,
3310 fctx: &crate::decode::FrameCtx,
3311) {
3312 // The CfL AC signal is read HERE, off the luma that has already been
3313 // written for this block -- at parse time it would have been the previous
3314 // frame's samples.
3315 let ac = cfl.map(|(alpha, src)| {
3316 let sig = if src.rect {
3317 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3318 } else {
3319 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3320 };
3321 (alpha, sig)
3322 });
3323 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3324 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3325 if rect {
3326 target.reconstruct_rect(
3327 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3328 smooth_neighbor, pred, fctx,
3329 );
3330 } else {
3331 target.reconstruct(
3332 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3333 smooth_neighbor, pred, fctx,
3334 );
3335 }
3336}
3337
3338/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3339#[allow(clippy::too_many_arguments)]
3340fn exec_mc(
3341 y: &mut PlaneBuf<'static>,
3342 u: &mut PlaneBuf<'static>,
3343 v: &mut PlaneBuf<'static>,
3344 plane: usize,
3345 x: usize,
3346 oy: usize,
3347 stride: usize,
3348 w: usize,
3349 h: usize,
3350 prediction: &[u16],
3351 residual: &[i32],
3352 fctx: &crate::decode::FrameCtx,
3353) {
3354 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3355 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3356}
3357
3358thread_local! {
3359 /// The current frame's `mi` grid, kept only while a frame header set
3360 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3361 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3362 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3363 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3364 /// does not allow intrabc (so nothing is paid for it).
3365 ///
3366 /// corner-cut: only [`decode_block`] (the square path) records into it,
3367 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3368 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3369 /// be wrong there; upgrade = record from the rect/leaf paths too.
3370 /// The block vector [`read_intra_mode`] just decoded, handed to
3371 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3372 /// which the alternative -- a tenth tuple member through every caller --
3373 /// already avoids). Always `.take()`n by the block that reads it.
3374 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
3375 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3376}
3377 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3378 // an intrabc block's chroma reads can inherit it (see
3379 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3380 // through that one arming site.
3381 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3382 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3383 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3384 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3385 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3386 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3387 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3388 // -- getting it wrong desyncs the chroma coefficients, it is not a
3389 // reconstruction-only detail.
3390
3391/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3392/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3393/// needs no separate plumbing to reach the rect-strip mode reader.
3394fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3395 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3396}
3397
3398thread_local! {
3399 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3400 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3401 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3402 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3403}
3404
3405/// Current value of [`RECT_INTRABC_READS`].
3406pub(crate) fn rect_intrabc_reads() -> usize {
3407 RECT_INTRABC_READS.with(|c| c.get())
3408}
3409
3410/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3411#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3412pub(crate) fn reset_rect_intrabc_reads() {
3413 RECT_INTRABC_READS.with(|c| c.set(0));
3414}
3415
3416thread_local! {
3417 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3418 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3419 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3420}
3421
3422/// Current value of [`LEAF8_INTRABC_HITS`].
3423pub(crate) fn leaf8_intrabc_hits() -> usize {
3424 LEAF8_INTRABC_HITS.with(|c| c.get())
3425}
3426
3427/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3428#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3429pub(crate) fn reset_leaf8_intrabc_hits() {
3430 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3431}
3432
3433/// Current value of [`INTRABC_HITS`].
3434#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3435pub(crate) fn intrabc_hits() -> usize {
3436 INTRABC_HITS.with(|c| c.get())
3437}
3438
3439/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3440#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3441pub(crate) fn reset_intrabc_hits() {
3442 INTRABC_HITS.with(|c| c.set(0));
3443}
3444
3445thread_local! {
3446 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3447 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3448 /// that replaced the refusal "an intrabc block under TxMode::Select".
3449 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3450}
3451
3452/// Current value of [`INTRABC_VARTX_HITS`].
3453#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3454pub(crate) fn intrabc_vartx_hits() -> usize {
3455 INTRABC_VARTX_HITS.with(|c| c.get())
3456}
3457
3458/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3459#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3460pub(crate) fn reset_intrabc_vartx_hits() {
3461 INTRABC_VARTX_HITS.with(|c| c.set(0));
3462}
3463
3464/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3465/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3466/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3467/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3468fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
3469 fctx.intrabc_mi_grid.with(|g| {
3470 let mut g = g.borrow_mut();
3471 let Some((grid, _, _)) = g.as_mut() else {
3472 return;
3473 };
3474 let info = crate::mvstack::MiInfo {
3475 is_inter: dv.is_some(),
3476 ref_frame: 0,
3477 ref_frame1: NO_REF1,
3478 mv: mv16(dv.unwrap_or((0, 0))),
3479 mv1: (0, 0),
3480 is_new_mv: dv.is_some(),
3481 is_global_mv0: false,
3482 is_global_mv1: false,
3483 size: n4 as u8,
3484 size_h: n4 as u8,
3485 };
3486 for r in mi_r..mi_r + n4 {
3487 for c in mi_c..mi_c + n4 {
3488 grid.set(r, c, info);
3489 }
3490 }
3491 });
3492}
3493
3494// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3495// proves a real `skip_mode_present` stream actually reached a block that
3496// picked it, not just that the frame header bit was set.
3497thread_local! {
3498 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3499 const { std::cell::Cell::new(0) };
3500}
3501
3502/// Current value of [`SKIP_MODE_HITS`].
3503#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3504pub(crate) fn skip_mode_hits() -> usize {
3505 SKIP_MODE_HITS.with(|c| c.get())
3506}
3507
3508// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3509// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3510// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3511// reached [`obmc_blend`], not just the header bit.
3512thread_local! {
3513 static OBMC_HITS: std::cell::Cell<usize> =
3514 const { std::cell::Cell::new(0) };
3515}
3516
3517// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3518// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3519// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3520// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3521// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3522// decoder used to read with the wrong alphabet, so a gate that asserts this
3523// counter advanced proves the fixed path fired (class
3524// `gate-blind-to-feature`).
3525thread_local! {
3526 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3527}
3528
3529/// Current value of [`FIMV_ALPHABET_HITS`].
3530pub fn fimv_alphabet_hits() -> usize {
3531 FIMV_ALPHABET_HITS.with(|c| c.get())
3532}
3533
3534// lane-fimv r1: how many frame headers this decoder has decoded with
3535// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3536// prove the encoder really produced the header state under test rather than
3537// assume it.
3538thread_local! {
3539 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3540}
3541
3542/// Current value of [`FIMV_FRAME_HITS`].
3543pub fn fimv_frame_hits() -> usize {
3544 FIMV_FRAME_HITS.with(|c| c.get())
3545}
3546
3547/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3548/// `force_integer_mv` bit is set.
3549pub fn note_force_integer_mv_frame() {
3550 hit!(FIMV_FRAME_HITS);
3551}
3552
3553/// Current value of [`OBMC_HITS`].
3554#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3555pub(crate) fn obmc_hits() -> usize {
3556 OBMC_HITS.with(|c| c.get())
3557}
3558
3559// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3560// off the neighbour band -- the positive half of the proof for "an OBMC
3561// neighbour whose switchable interp filter was never recorded". A
3562// fixed-filter frame returns before this point (its neighbours legitimately
3563// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3564// `interp_filter` symbols were published by `record_inter_rect_mi`.
3565thread_local! {
3566 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3567}
3568
3569/// Current value of [`OBMC_FILTER_BAND_READS`].
3570#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3571pub(crate) fn obmc_filter_band_reads() -> usize {
3572 OBMC_FILTER_BAND_READS.with(|c| c.get())
3573}
3574
3575// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3576// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3577// reference would pass just as well and prove nothing, so the gate
3578// hard-asserts each combination this round lifts actually occurred:
3579// a compound block with a scaled tap, a warp block whose warp libaom
3580// suppresses because the reference is scaled, an OBMC block, an interintra
3581// block, and an 8x8 leaf.
3582thread_local! {
3583 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3584 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3585 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3586 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3587 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3588 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3589 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3590}
3591
3592/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
3593/// scaled and one unscaled tap.
3594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3595pub(crate) fn mixed_scale_compound_hits() -> usize {
3596 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
3597}
3598
3599/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
3600/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
3601/// instead because their reference is scaled (libaom `motion_mode_allowed`,
3602/// `blockd.h:1484`).
3603#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3604pub(crate) fn scaled_warp_suppressed_hits() -> usize {
3605 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
3606}
3607
3608/// Current value of [`SCALED_COMPOUND_HITS`].
3609#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3610pub(crate) fn scaled_compound_hits() -> usize {
3611 SCALED_COMPOUND_HITS.with(|c| c.get())
3612}
3613
3614/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
3615pub fn scaled_warp_fallback_hits() -> usize {
3616 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
3617}
3618
3619/// Current value of [`SCALED_OBMC_HITS`].
3620#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3621pub(crate) fn scaled_obmc_hits() -> usize {
3622 SCALED_OBMC_HITS.with(|c| c.get())
3623}
3624
3625/// Current value of [`SCALED_INTERINTRA_HITS`].
3626#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3627pub(crate) fn scaled_interintra_hits() -> usize {
3628 SCALED_INTERINTRA_HITS.with(|c| c.get())
3629}
3630
3631/// Current value of [`SCALED_BLOCK8_HITS`].
3632#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3633pub(crate) fn scaled_block8_hits() -> usize {
3634 SCALED_BLOCK8_HITS.with(|c| c.get())
3635}
3636
3637// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
3638// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
3639// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
3640// 8x8-leaf OBMC block apart from a 16x16+ one.
3641thread_local! {
3642 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3643}
3644
3645// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
3646// pair whose two directions differ (`enable_dual_filter` only -- with dual
3647// filter off both directions take the single symbol, so this can never fire).
3648// A gate asserting it proves the stream really carries dual-filter blocks.
3649thread_local! {
3650 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3651}
3652
3653// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
3654// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
3655// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
3656// no-filter sentinel that made a neighbouring OBMC block panic).
3657thread_local! {
3658 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3659}
3660
3661/// Current value of [`DUAL_FILTER_DIFF_HITS`].
3662#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3663pub(crate) fn dual_filter_diff_hits() -> usize {
3664 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
3665}
3666
3667/// Current value of [`COMPOUND8_FILTER_HITS`].
3668#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3669pub(crate) fn compound8_filter_hits() -> usize {
3670 COMPOUND8_FILTER_HITS.with(|c| c.get())
3671}
3672
3673// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
3674// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
3675// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
3676// -- the gate's proof that a fixture really exercises the alphabet this
3677// round changed, even though the block itself still refuses (warp
3678// estimation/filter not ported).
3679thread_local! {
3680 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
3681 const { std::cell::Cell::new(0) };
3682}
3683
3684/// Current value of [`WARP_SELECTED_HITS`].
3685#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3686pub(crate) fn warp_selected_hits() -> usize {
3687 WARP_SELECTED_HITS.with(|c| c.get())
3688}
3689
3690// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
3691// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
3692// into the compound intermediate) rather than translationally -- the
3693// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
3694// really reached [`crate::warp::warp_affine_compound`].
3695thread_local! {
3696 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
3697 const { std::cell::Cell::new(0) };
3698}
3699
3700/// Current value of [`COMPOUND_WARP_HITS`].
3701#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3702pub(crate) fn compound_warp_hits() -> usize {
3703 COMPOUND_WARP_HITS.with(|c| c.get())
3704}
3705
3706// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
3707// arm ([`decode_inter_block8`]) -- that arm predicted both taps
3708// translationally until r3, so a gate needs to tell a warped 8x8 compound
3709// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
3710thread_local! {
3711 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
3712 const { std::cell::Cell::new(0) };
3713}
3714
3715/// Current value of [`COMPOUND_WARP_HITS_8`].
3716#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3717pub(crate) fn compound_warp_hits_8() -> usize {
3718 COMPOUND_WARP_HITS_8.with(|c| c.get())
3719}
3720
3721// lane-gmaffine r1: how many blocks built their prediction from a
3722// SIX-parameter (`AFFINE`) global-motion model through
3723// `crate::warp::global_warp_params` -- the gate's proof that a stream really
3724// carried an AFFINE `global_motion_params` AND that a block was predicted
3725// with it, not merely that the header parsed one.
3726thread_local! {
3727 static AFFINE_GM_HITS: std::cell::Cell<usize> =
3728 const { std::cell::Cell::new(0) };
3729}
3730
3731/// Current value of [`AFFINE_GM_HITS`].
3732#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3733pub(crate) fn affine_gm_hits() -> usize {
3734 AFFINE_GM_HITS.with(|c| c.get())
3735}
3736
3737// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
3738// differently at the block's WIDTH than at libaom's
3739// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
3740// pick the wrong motion_mode alphabet.
3741thread_local! {
3742 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3743}
3744
3745/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
3746pub fn tr_reach_longer_side_hits() -> usize {
3747 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
3748}
3749
3750// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
3751// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
3752// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
3753// reads its interp-filter symbol. Counts the blocks where that guard flips
3754// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
3755// and a 4-px side, which we used to suppress the interp read on (a pre-mode
3756// entropy desync one symbol wide).
3757thread_local! {
3758 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3759}
3760
3761/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
3762pub fn gm_nontrans_small_side_hits() -> usize {
3763 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
3764}
3765
3766// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
3767// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
3768// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
3769// only once `find_projection` returned a usable model, unlike
3770// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
3771// proof that the leaf path itself fired, not the 16x16+ one.
3772thread_local! {
3773 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3774 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3775}
3776
3777/// Current value of [`GLOBALMV_HITS_8`].
3778#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3779pub(crate) fn globalmv_hits_8() -> usize {
3780 GLOBALMV_HITS_8.with(|c| c.get())
3781}
3782
3783/// Current value of [`WARP_HITS_8`].
3784#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3785pub(crate) fn warp_hits_8() -> usize {
3786 WARP_HITS_8.with(|c| c.get())
3787}
3788
3789// How many blocks decoded `interintra == 1` with the non-wedge blended
3790// prediction applied (lane-interintra r1) -- the gate's proof that a
3791// stream actually exercised interintra.
3792thread_local! {
3793 static INTERINTRA_HITS: std::cell::Cell<usize> =
3794 const { std::cell::Cell::new(0) };
3795}
3796
3797/// Current value of [`INTERINTRA_HITS`].
3798#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3799pub(crate) fn interintra_hits() -> usize {
3800 INTERINTRA_HITS.with(|c| c.get())
3801}
3802
3803// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
3804// -- the shape `interintra_blend` used to build a square `side x side` intra
3805// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
3806// pre-existing interintra gate passed with that bug, so the rect arm needs
3807// its own counter to stop being vacuous.
3808thread_local! {
3809 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3810}
3811
3812/// Current value of [`INTERINTRA_RECT_HITS`].
3813pub fn interintra_rect_hits() -> usize {
3814 INTERINTRA_RECT_HITS.with(|c| c.get())
3815}
3816
3817// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
3818// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
3819// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
3820// gate fixture actually exercises this alphabet, even though the block
3821// still refuses (the mask blend itself is unported).
3822thread_local! {
3823 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3824 const { std::cell::Cell::new(0) };
3825}
3826
3827/// Current value of [`MASKED_COMPOUND_HITS`].
3828#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3829pub(crate) fn masked_compound_hits() -> usize {
3830 MASKED_COMPOUND_HITS.with(|c| c.get())
3831}
3832
3833// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
3834// masked-compound block whose true footprint is rectangular, i.e. the case
3835// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
3836// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
3837// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
3838thread_local! {
3839 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3840 const { std::cell::Cell::new(0) };
3841}
3842
3843/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
3844#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3845pub(crate) fn rect_masked_compound_hits() -> usize {
3846 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
3847}
3848
3849// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
3850// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
3851// actually exercised the wedge blend, not just the DIFFWTD half of
3852// `MASKED_COMPOUND_HITS`.
3853thread_local! {
3854 static WEDGE_HITS: std::cell::Cell<usize> =
3855 const { std::cell::Cell::new(0) };
3856}
3857
3858/// Current value of [`WEDGE_HITS`].
3859#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3860pub(crate) fn wedge_hits() -> usize {
3861 WEDGE_HITS.with(|c| c.get())
3862}
3863
3864// How many blocks decoded a real wedge-INTERINTRA block
3865// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
3866// a gate fixture exercised the wedge blend (fixed sign 0), not just the
3867// smooth arm counted by `INTERINTRA_HITS`.
3868thread_local! {
3869 static WII_HITS: std::cell::Cell<usize> =
3870 const { std::cell::Cell::new(0) };
3871}
3872
3873/// Current value of [`WII_HITS`].
3874#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3875pub(crate) fn wii_hits() -> usize {
3876 WII_HITS.with(|c| c.get())
3877}
3878
3879// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
3880// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
3881// wide <= 32 && high <= 32). The witness that a gate stream really carries a
3882// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
3883// frame carrying one.
3884thread_local! {
3885 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3886}
3887
3888/// Current value of [`NOCFL_UV_MODE_HITS`].
3889#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3890pub(crate) fn nocfl_uv_mode_hits() -> usize {
3891 NOCFL_UV_MODE_HITS.with(|c| c.get())
3892}
3893
3894/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
3895/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
3896pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
3897 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
3898
3899fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
3900 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
3901}
3902
3903// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
3904// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
3905// the rect wedge masks lifted this round actually fired, not just the square
3906// ones already counted by `WEDGE_HITS`/`WII_HITS`.
3907thread_local! {
3908 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3909 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3910}
3911
3912/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3913pub(crate) fn rect_wedge_hits() -> [usize; 6] {
3914 RECT_WEDGE_HITS.with(|c| c.get())
3915}
3916
3917/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3918pub(crate) fn rect_wii_hits() -> [usize; 6] {
3919 RECT_WII_HITS.with(|c| c.get())
3920}
3921
3922// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
3923// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
3924// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
3925// aomdec, neighbour list included).
3926thread_local! {
3927 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3928}
3929
3930/// Current value of [`OBMC_RECT_LEAF_HITS`].
3931pub(crate) fn obmc_rect_leaf_hits() -> usize {
3932 OBMC_RECT_LEAF_HITS.with(|c| c.get())
3933}
3934
3935// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
3936// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
3937// to be read from the pair's FIRST mi, which is a different block and, when
3938// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
3939// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
3940thread_local! {
3941 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3942}
3943
3944/// Current value of [`OBMC_PAIR_FILTER_HITS`].
3945pub(crate) fn obmc_pair_filter_hits() -> usize {
3946 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
3947}
3948
3949// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
3950// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
3951// own side, so a block overhanging the bottom/right still predicts the full
3952// neighbour strip (the destination write is what clips). We used to shrink the
3953// prediction to the visible part, which at 4 chroma rows/cols also swaps the
3954// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
3955thread_local! {
3956 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3957}
3958
3959/// Current value of [`OBMC_EDGE_SPAN_HITS`].
3960#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3961pub(crate) fn obmc_edge_span_hits() -> usize {
3962 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
3963}
3964
3965/// Current value of [`OBMC_HITS_8`].
3966#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3967pub(crate) fn obmc_hits_8() -> usize {
3968 OBMC_HITS_8.with(|c| c.get())
3969}
3970
3971// lane-rectgate r1: how many 32x32 quadrants actually decoded a
3972// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
3973// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
3974// `VERT_B` all still fall into the generic "a partition type this encoder
3975// never writes" refusal below) -- the gate's proof that a free-partition
3976// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
3977// coincidentally never selecting one.
3978thread_local! {
3979 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
3980 const { std::cell::Cell::new(0) };
3981}
3982
3983/// Current value of [`EXTENDED_PARTITION_HITS`].
3984#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3985pub(crate) fn extended_partition_hits() -> usize {
3986 EXTENDED_PARTITION_HITS.with(|c| c.get())
3987}
3988
3989// lane-partitions r1: how many 32x32 quadrants decoded a real
3990// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
3991// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
3992// gate's proof this round's arms actually fired.
3993thread_local! {
3994 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
3995 const { std::cell::Cell::new(0) };
3996}
3997
3998/// Current value of [`RECT_PARTITION_HITS`].
3999#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4000pub(crate) fn rect_partition_hits() -> usize {
4001 RECT_PARTITION_HITS.with(|c| c.get())
4002}
4003
4004// lane-inter8 r1: how many superblocks an inter tile coded as a single
4005// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4006// static content, previously a named refusal).
4007thread_local! {
4008 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4009 /// path decoded as one whole block (its gate's own witness).
4010 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4011 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4012 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4013 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4014}
4015
4016/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4017pub(crate) fn inter_sb128_horz_hits() -> usize {
4018 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4019}
4020
4021/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4022pub(crate) fn inter_sb128_vert_hits() -> usize {
4023 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4024}
4025
4026/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4027pub fn inter_sb128_none_hits() -> usize {
4028 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4029}
4030
4031thread_local! {
4032 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4033 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4034 /// units) -- the gate's witness that the lifted refusal's case fired.
4035 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4036}
4037
4038/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4039pub fn intra_128_in_inter_hits() -> usize {
4040 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4041}
4042
4043thread_local! {
4044 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4045 const { std::cell::Cell::new(0) };
4046}
4047
4048/// Current value of [`INTER_SB_NONE_HITS`].
4049#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4050pub(crate) fn inter_sb_none_hits() -> usize {
4051 INTER_SB_NONE_HITS.with(|c| c.get())
4052}
4053
4054// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4055// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4056// path has always run that loop, so only this counter proves the newly-lifted
4057// alphabet value fired.
4058thread_local! {
4059 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4060 const { std::cell::Cell::new(0) };
4061}
4062
4063/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4064#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4065pub(crate) fn inter_sub16_split_hits() -> usize {
4066 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4067}
4068
4069// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4070// while at least one reference picture was SCALED (superres) -- the counter
4071// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4072thread_local! {
4073 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4074 const { std::cell::Cell::new(0) };
4075}
4076
4077/// Current value of [`SCALED_LEAF8_HITS`].
4078pub fn scaled_leaf8_hits() -> usize {
4079 SCALED_LEAF8_HITS.with(|c| c.get())
4080}
4081
4082// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4083// rect pair) were predicted from a SCALED reference -- the counter behind the
4084// lifted "sub-8x8 inter block under a scaled reference" refusal.
4085thread_local! {
4086 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4087 const { std::cell::Cell::new(0) };
4088}
4089
4090/// Current value of [`SCALED_SUB8_HITS`].
4091pub fn scaled_sub8_hits() -> usize {
4092 SCALED_SUB8_HITS.with(|c| c.get())
4093}
4094
4095// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4096// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4097// rect coefficient reader itself fired, not just the strip-level partition
4098// symbol [`RECT_PARTITION_HITS`] already counts.
4099thread_local! {
4100 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4101 const { std::cell::Cell::new(0) };
4102}
4103
4104/// Current value of [`RECT_COEFF_HITS`].
4105#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4106pub(crate) fn rect_coeff_hits() -> usize {
4107 RECT_COEFF_HITS.with(|c| c.get())
4108}
4109
4110// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4111// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4112// charter's real-aomenc gate hard-asserts.
4113thread_local! {
4114 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4115 const { std::cell::Cell::new(0) };
4116}
4117
4118/// Current value of [`RECT_LEAF_COEFF_HITS`].
4119#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4120pub(crate) fn rect_leaf_coeff_hits() -> usize {
4121 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4122}
4123
4124// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4125// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4126// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4127// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4128// needs rectangular intra prediction" before this round.
4129thread_local! {
4130 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4131 const { std::cell::Cell::new([0; 3]) };
4132}
4133
4134/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4135/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4136#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4137pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4138 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4139}
4140
4141// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4142// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4143// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4144// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4145// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4146// a single counter cannot tell an axis swap from a working arm
4147// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4148thread_local! {
4149 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4150 const { std::cell::Cell::new([0; 2]) };
4151}
4152
4153/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4154/// (0 = 64x32, 1 = 32x64).
4155pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4156 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4157}
4158
4159// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4160// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4161// is never incremented) -- the gate's proof that the lifted path ran per depth.
4162thread_local! {
4163 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4164 const { std::cell::Cell::new([0; 3]) };
4165}
4166
4167// lane-t900 r21: rect intra strips inside an inter frame that read the
4168// screen-content palette syntax (`allow_screen_content_tools` set and the
4169// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4170// refusal used to guard, so this counter is what keeps its witness gate
4171// non-vacuous.
4172thread_local! {
4173 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4174}
4175
4176/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4177#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4178pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4179 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4180}
4181
4182/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4183#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4184pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4185 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4186}
4187
4188/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4189#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4190pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4191 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4192}
4193
4194// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
4195// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
4196// the blocks the key frame's deblock-grid approximation used to mis-read.
4197thread_local! {
4198 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
4199 const { std::cell::Cell::new(0) };
4200}
4201
4202/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
4203#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4204pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
4205 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
4206}
4207
4208// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4209// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4210// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4211// rect strip on the inter block path" before this round.
4212thread_local! {
4213 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4214 const { std::cell::Cell::new([0; 4]) };
4215}
4216
4217/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4218/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4219pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4220 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4221}
4222
4223// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4224// through one of the key-frame rect readers ([`decode_block_rect4`],
4225// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4226// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4227// already read by [`decode_inter_block`] and (b) the luma mode comes off
4228// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4229// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4230
4231// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4232// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4233// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4234// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4235thread_local! {
4236 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4237 const { std::cell::Cell::new(0) };
4238}
4239
4240/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4241#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4242pub(crate) fn mode_mi_override_hits() -> usize {
4243 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4244}
4245
4246// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4247// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4248// mode from the previous tile, where libaom's `up_available`/`left_available`
4249// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4250// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4251// per superblock row in `start_row`, so the luma fallback cannot leak the way
4252// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4253// the invariant that makes the coarse fallback safe.
4254thread_local! {
4255 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4256 const { std::cell::Cell::new(0) };
4257}
4258
4259/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4260#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4261pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4262 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4263}
4264
4265// lane-cfl r1: how many times a chroma intra-edge filter-type read
4266// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4267// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4268// r1 defect would have filtered a chroma edge with the wrong strength.
4269thread_local! {
4270 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4271 const { std::cell::Cell::new(0) };
4272}
4273
4274/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4275#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4276pub(crate) fn uv_mode_mi_override_hits() -> usize {
4277 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4278}
4279
4280// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4281// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4282// answered differently -- the sub-8x8 pair case where the pair's own first
4283// half had already overwritten the column slot the chroma-ref half reads.
4284thread_local! {
4285 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4286 const { std::cell::Cell::new(0) };
4287}
4288
4289/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4290pub fn uv_mode_grid_override_hits() -> usize {
4291 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4292}
4293
4294// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4295// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4296// from an earlier block in that pixel row/column while the mi-exact map --
4297// which an inter block only started writing this round -- correctly says the
4298// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4299// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4300thread_local! {
4301 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4302 const { std::cell::Cell::new(0) };
4303}
4304
4305/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4306#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4307pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4308 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4309}
4310
4311// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4312// suppressed at a TILE edge that is not a frame edge -- the above/left
4313// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4314// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4315// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4316// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4317// above would decide this tile's chroma edge filter strength.
4318thread_local! {
4319 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4320 const { std::cell::Cell::new(0) };
4321}
4322
4323/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4324#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4325pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4326 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4327}
4328
4329// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4330// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4331// shapes the r1 chroma defect showed up on.
4332thread_local! {
4333 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4334 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4335}
4336
4337/// Current value of [`CFL_BLOCK_HITS`].
4338#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4339pub(crate) fn cfl_block_hits() -> usize {
4340 CFL_BLOCK_HITS.with(|c| c.get())
4341}
4342
4343/// Current value of [`UV_ANGLE_DELTA_HITS`].
4344#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4345pub(crate) fn uv_angle_delta_hits() -> usize {
4346 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4347}
4348
4349// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4350// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4351// gate's proof this round's arms actually reached a real block, not just
4352// that `partition_w64` read one of those two symbol values.
4353thread_local! {
4354 static SB_RECT_HITS: std::cell::Cell<usize> =
4355 const { std::cell::Cell::new(0) };
4356}
4357
4358// Current value of [`SB_RECT_HITS`].
4359// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4360// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4361// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4362// non-SPLIT edge arm actually decoded (before this round the bit was read and
4363// thrown away, so that arm was unreachable).
4364thread_local! {
4365 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4366}
4367
4368/// Current value of [`EDGE_PART_HITS`].
4369#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4370pub(crate) fn edge_part_hits() -> [usize; 4] {
4371 EDGE_PART_HITS.with(|c| c.get())
4372}
4373
4374/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4375#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4376pub(crate) fn reset_edge_part_hits() {
4377 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4378}
4379
4380fn bump_edge_part(slot: usize) {
4381 hit_do! {
4382 EDGE_PART_HITS.with(|c| {
4383 let mut h = c.get();
4384 h[slot] += 1;
4385 c.set(h);
4386 });
4387 }
4388}
4389
4390#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4391pub(crate) fn sb_rect_hits() -> usize {
4392 SB_RECT_HITS.with(|c| c.get())
4393}
4394
4395// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4396// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4397// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4398// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4399// paths (intra and inter) feed the same counter.
4400//
4401// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4402// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4403// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4404// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4405// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4406// every SB of the last row), so the 32-level slots stay 0 on that content and
4407// only these prove the arm fired.
4408thread_local! {
4409 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4410 const { std::cell::Cell::new([0; 8]) };
4411}
4412
4413/// Current value of [`EDGE32_HITS`].
4414#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4415pub(crate) fn edge32_hits() -> [usize; 8] {
4416 EDGE32_HITS.with(|c| c.get())
4417}
4418
4419/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4420/// reads are `if`-conditions, so the counter has to ride the expression.
4421fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4422 bump_edge32(base + bit.min(1));
4423 bit
4424}
4425
4426fn bump_edge32(slot: usize) {
4427 hit_do! {
4428 EDGE32_HITS.with(|c| {
4429 let mut h = c.get();
4430 h[slot] += 1;
4431 c.set(h)
4432 });
4433 }
4434}
4435
4436// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4437// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4438// strip) fired. Real aomenc picks these at 64 even with
4439// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4440// the counter the gate hard-asserts.
4441thread_local! {
4442 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4443 const { std::cell::Cell::new([0; 4]) };
4444}
4445
4446/// Current value of [`SB_AB_HITS`], summed over the four arms.
4447#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4448pub(crate) fn sb_ab_hits() -> usize {
4449 SB_AB_HITS.with(|c| c.get().iter().sum())
4450}
4451
4452/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4453/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4454/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4455/// proof of all four.
4456#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4457pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4458 SB_AB_HITS.with(std::cell::Cell::get)
4459}
4460
4461// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4462// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4463// strips). Two counters, not one, because a gate that only proved "some 1:4
4464// strip fired" would pass on a stream that never coded the other axis, and
4465// every scan/context table this round added comes in a transposed pair.
4466thread_local! {
4467 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4468 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4469}
4470
4471/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4472#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4473pub(crate) fn sb_rect4_horz_hits() -> usize {
4474 SB_RECT4_HORZ_HITS.with(|c| c.get())
4475}
4476
4477/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4478#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4479pub(crate) fn sb_rect4_vert_hits() -> usize {
4480 SB_RECT4_VERT_HITS.with(|c| c.get())
4481}
4482
4483// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4484// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4485// strips), the arms the ReelB mid-film extract stops at.
4486thread_local! {
4487 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4488 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4489 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4490 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4491 /// `PARTITION_VERT_4`.
4492 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4493 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4494 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4495 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4496 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4497 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4498 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4499 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4500}
4501
4502// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4503// a gate that only counted strips would pass on an all-skip stream, which
4504// exercises none of the new scan/context tables.
4505thread_local! {
4506 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4507}
4508
4509// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4510// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4511// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4512// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4513// counts the same for a 16x8/8x16 strip below 16x16.
4514thread_local! {
4515 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4516 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4517 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4518}
4519
4520/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4521#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4522pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4523 (
4524 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4525 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4526 )
4527}
4528
4529/// Current value of `SUB16_SPLIT_HITS`.
4530#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4531pub(crate) fn sub16_split_hits() -> usize {
4532 SUB16_SPLIT_HITS.with(|c| c.get())
4533}
4534
4535// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4536// luma transform is SPLIT and which therefore leave through that fn's early
4537// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4538thread_local! {
4539 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4540}
4541
4542/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4543#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4544pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4545 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4546}
4547
4548/// Current value of `RECT4_COEFF_HITS`.
4549pub(crate) fn rect4_coeff_hits() -> usize {
4550 RECT4_COEFF_HITS.with(|c| c.get())
4551}
4552
4553// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4554// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4555// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4556// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4557// asserts the arms it proves separately so a run whose RD only picked one
4558// cannot pass as proof of the others.
4559thread_local! {
4560 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4561}
4562
4563/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4564/// inter frame).
4565pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4566 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4567}
4568
4569// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4570// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4571// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4572// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4573// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4574// arm separately so a run whose RD only picked one cannot pass as proof of
4575// four.
4576thread_local! {
4577 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4578}
4579
4580/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4581/// inter frame).
4582pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4583 AB16_INTER_HITS.with(std::cell::Cell::get)
4584}
4585
4586// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
4587// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
4588// counts the odd strips that close a 4:2:0 chroma pair
4589// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
4590// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
4591// the PREVIOUS strip's own mv/ref/filters -- libaom
4592// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
4593// through `is_sub8x8_inter` (same file, :54).
4594thread_local! {
4595 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4596 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4597 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4598 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4599}
4600
4601// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
4602// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
4603// pair's single 8x4 (4x8) chroma unit for BOTH strips.
4604thread_local! {
4605 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4606 const { std::cell::Cell::new([0; 3]) };
4607}
4608
4609/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
4610/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
4611pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
4612 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
4613 (v[0], v[1], v[2])
4614}
4615
4616/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
4617/// strips, chroma pairs closed, chroma pairs built from two different
4618/// strips' motion vectors)`.
4619pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
4620 (
4621 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
4622 INTER16_VERT4_HITS.with(std::cell::Cell::get),
4623 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
4624 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
4625 )
4626}
4627
4628/// One 16x4 / 4x16 inter strip's chroma situation, handed to
4629/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
4630/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
4631/// that all mean "an ordinary block, chroma of its own".
4632#[derive(Clone, Copy)]
4633pub(crate) struct InterStripChroma {
4634 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
4635 /// read and reconstruct NO chroma at all.
4636 has_chroma: bool,
4637 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
4638 horz: bool,
4639 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
4640 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
4641 /// i.e. the origin of the 8x4 (4x8) chroma transform.
4642 pair_mi: (usize, usize),
4643 /// The previous (even) strip's single-reference MC parameters, `None`
4644 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
4645 /// and the whole chroma block is predicted from THIS strip's mv.
4646 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
4647}
4648
4649 /// The single-reference MC parameters of the inter block that decoded
4650 /// last -- read by the next 1:4 strip to build its pair's chroma.
4651
4652fn bump_ab16_inter(arm: usize) {
4653 hit_do! {
4654 AB16_INTER_HITS.with(|c| {
4655 let mut v = c.get();
4656 v[arm] += 1;
4657 c.set(v);
4658 });
4659 }
4660}
4661
4662// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
4663// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
4664// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
4665thread_local! {
4666 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4667 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4668 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4669 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4670 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4671 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
4672 /// base mi differs from what the strip's own (odd) mi would have said --
4673 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
4674 /// key frame miss by 1. Zero here means a gate never exercised the fix.
4675 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4676 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
4677 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
4678 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4679}
4680
4681/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
4682/// that reconstructed as flat DC before lane-kf1200 r2).
4683pub fn skip_cfl_hits() -> usize {
4684 SKIP_CFL_HITS.with(|c| c.get())
4685}
4686
4687/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
4688/// from the pair's base mi than the strip's own mi would have given.
4689pub fn rect4_16_uv_pair_filt_hits() -> usize {
4690 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
4691}
4692
4693// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
4694// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
4695// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
4696// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
4697// intra-edge filter type must come from the chroma-reference position).
4698thread_local! {
4699 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4700 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4701}
4702
4703/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
4704pub fn reelc_chroma_counters() -> (usize, usize) {
4705 (
4706 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
4707 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
4708 )
4709}
4710
4711/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
4712/// strips, chroma-reference strips, strips with a coded residual, strips
4713/// whose luma transform is split)`.
4714pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
4715 (
4716 RECT4_16_HORZ_HITS.with(|c| c.get()),
4717 RECT4_16_VERT_HITS.with(|c| c.get()),
4718 RECT4_16_CHROMA_HITS.with(|c| c.get()),
4719 RECT4_16_COEFF_HITS.with(|c| c.get()),
4720 RECT4_16_SPLIT_HITS.with(|c| c.get()),
4721 )
4722}
4723
4724/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
4725pub(crate) fn rect4_32_horz_hits() -> usize {
4726 RECT4_32_HORZ_HITS.with(|c| c.get())
4727}
4728
4729/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
4730pub(crate) fn rect4_32_vert_hits() -> usize {
4731 RECT4_32_VERT_HITS.with(|c| c.get())
4732}
4733
4734/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
4735pub(crate) fn rect4_32_horz_inter_hits() -> usize {
4736 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
4737}
4738
4739/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
4740pub(crate) fn rect4_32_vert_inter_hits() -> usize {
4741 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
4742}
4743
4744/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
4745pub(crate) fn inter_sb_horz_hits() -> usize {
4746 INTER_SB_HORZ_HITS.with(|c| c.get())
4747}
4748
4749/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
4750pub(crate) fn inter_sb_vert_hits() -> usize {
4751 INTER_SB_VERT_HITS.with(|c| c.get())
4752}
4753
4754/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
4755pub(crate) fn inter_sb_horz4_hits() -> usize {
4756 INTER_SB_HORZ4_HITS.with(|c| c.get())
4757}
4758
4759/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
4760pub(crate) fn inter_sb_vert4_hits() -> usize {
4761 INTER_SB_VERT4_HITS.with(|c| c.get())
4762}
4763
4764// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
4765// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
4766// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
4767// just inert-compiled. Zero forever on a passing gate means that gate's
4768// stream never carries `delta_q_present=1` through a rect64 block.
4769thread_local! {
4770 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
4771 const { std::cell::Cell::new(0) };
4772}
4773
4774/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
4775#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4776pub(crate) fn rect64_qidx_drift_hits() -> usize {
4777 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
4778}
4779
4780// lane-partab r1: how many 32x32 quadrants decoded an AB partition
4781// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
4782// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
4783// free-partition gate's proof this round's arms actually fired.
4784thread_local! {
4785 static PARTAB_HITS: std::cell::Cell<usize> =
4786 const { std::cell::Cell::new(0) };
4787}
4788
4789/// Current value of [`PARTAB_HITS`].
4790#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4791pub(crate) fn partab_hits() -> usize {
4792 PARTAB_HITS.with(|c| c.get())
4793}
4794
4795// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
4796// one counter per arm rather than one shared total -- the gate hard-asserts
4797// each of these individually nonzero so a recipe that only ever fires
4798// HORZ_A can't silently stand in for the whole set.
4799thread_local! {
4800 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
4801 const { std::cell::Cell::new(0) };
4802 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
4803 const { std::cell::Cell::new(0) };
4804 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
4805 const { std::cell::Cell::new(0) };
4806 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
4807 const { std::cell::Cell::new(0) };
4808}
4809
4810/// Current value of [`INTRA_HORZ_A_HITS`].
4811#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4812pub(crate) fn intra_horz_a_hits() -> usize {
4813 INTRA_HORZ_A_HITS.with(|c| c.get())
4814}
4815/// Current value of [`INTRA_HORZ_B_HITS`].
4816#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4817pub(crate) fn intra_horz_b_hits() -> usize {
4818 INTRA_HORZ_B_HITS.with(|c| c.get())
4819}
4820/// Current value of [`INTRA_VERT_A_HITS`].
4821#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4822pub(crate) fn intra_vert_a_hits() -> usize {
4823 INTRA_VERT_A_HITS.with(|c| c.get())
4824}
4825/// Current value of [`INTRA_VERT_B_HITS`].
4826#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4827pub(crate) fn intra_vert_b_hits() -> usize {
4828 INTRA_VERT_B_HITS.with(|c| c.get())
4829}
4830
4831// How many [`read_inter_compound_mode`] reads actually happened
4832// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
4833// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
4834// mvstack build), not just that `comp_mode` fired. Still refused right
4835// after (no MV assignment or MC wired), so this only counts attempted
4836// reads.
4837thread_local! {
4838 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
4839 const { std::cell::Cell::new(0) };
4840}
4841
4842/// Current value of [`COMPOUND_MODE_HITS`].
4843#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4844pub(crate) fn compound_mode_hits() -> usize {
4845 COMPOUND_MODE_HITS.with(|c| c.get())
4846}
4847
4848/// How many query blocks folded in at least one temporal MV candidate
4849/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
4850/// temporal-MV gate's own firing counter (lane-av1tmvp).
4851///
4852/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
4853/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
4854/// this file (`decode_inter_block`) still passes `tpl: None` -- this
4855/// counter compiles and the projection math it counts is unit-tested
4856/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
4857/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
4858/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
4859/// against any real stream today. See the module doc on
4860/// `crate::motion_field` and this crate's ledger for the remaining wiring.
4861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4862pub(crate) fn tmv_hits() -> usize {
4863 crate::mvstack::tmv_hits()
4864}
4865
4866/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
4867/// produced on this thread, the 10-bit inter gate's firing proof.
4868#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4869pub(crate) fn inter_pred_hits() -> usize {
4870 crate::mc::inter_pred_hits()
4871}
4872
4873/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
4874/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
4875/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
4876/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
4877/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
4878/// needs to turn a query block's own resolved `ref_frame` into
4879/// `TplArgs::cur_offset_0` (spec 7.9.3).
4880pub(crate) struct TplFrameArgs<'a> {
4881 pub field: &'a crate::motion_field::TplField,
4882 pub order_hint_bits: u32,
4883 pub order_hint: u32,
4884 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
4885 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
4886 /// frame's own `ref_frame_idx` names for each single reference.
4887 pub ref_order_hints: [u32; 7],
4888}
4889
4890/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
4891/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
4892/// decoded `grid`: every 4x4 unit an inter block covers reads the same
4893/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
4894/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
4895/// exact — every block this crate ever codes is at least 8x8, so no 8x8
4896/// cell straddles two different blocks' values.
4897#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
4898pub(crate) fn build_motion_field(
4899 grid: &MiGrid,
4900 mi_cols: usize,
4901 mi_rows: usize,
4902 order_hint: u32,
4903 order_hint_bits: u32,
4904 ref_order_hints: [u32; 7],
4905 fctx: &FrameCtx,
4906) -> crate::motion_field::MotionField {
4907 let mut field =
4908 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
4909 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
4910 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
4911 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
4912 // referencing one stores only its OTHER side's mv. With
4913 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
4914 // nothing is skipped.
4915 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
4916 // only on the reference frame, so it is 7 table lookups per frame instead
4917 // of two per inter unit.
4918 let other_side: [bool; 8] = std::array::from_fn(|rf| {
4919 let i = rf.wrapping_sub(LAST_FRAME as usize);
4920 order_hint_bits != 0
4921 && i < 7
4922 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
4923 || ref_order_hints[i] == order_hint)
4924 });
4925 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
4926 // capped at 12 bits per component; a longer one is not stored at all.
4927 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
4928 let (cols, rows, cells) = field.cells_mut();
4929 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
4930 // never touch each other (an 8x8 cell lives in one cell row, and mi row
4931 // `row` writes cell row `row / 2`).
4932 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
4933 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
4934 let out = &mut out[(row / 2 - r0) * cols..][..cols];
4935 for col in 0..mi_cols {
4936 let Some(info) = grid.get_frame(row, col) else {
4937 continue;
4938 };
4939 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
4940 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
4941 // so an intra block -- or an inter block whose every slot is on the
4942 // other side / over the limit -- wipes what an earlier block wrote
4943 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
4944 // share a cell).
4945 if !info.is_inter {
4946 out[col / 2] = None;
4947 continue;
4948 }
4949 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
4950 // qualifying one wins -- a compound block stores its second
4951 // reference's mv, never its first (unless the second is on the
4952 // other side or over the limit). Storing slot 0 unconditionally
4953 // put the wrong (mv, ref_frame_offset) pair in every compound
4954 // block's cell, which a later frame's temporal candidate then
4955 // projected with the wrong reference distance.
4956 let mut saved: Option<crate::motion_field::SavedMv> = None;
4957 for (rf, mv) in [
4958 (info.ref_frame, Some(mv32(info.mv))),
4959 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
4960 ] {
4961 let (Some(mv), true) = (mv, rf > 0) else {
4962 continue;
4963 };
4964 if other_side[rf as usize] {
4965 continue;
4966 }
4967 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
4968 continue;
4969 }
4970 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
4971 }
4972 out[col / 2] = saved;
4973 }
4974 }
4975 };
4976 // lane-mf: the whole-frame pass split over the filter pool in cell-row
4977 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
4978 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
4979 let bands = crate::par::bands(rows, crate::par::filter_threads());
4980 if bands.len() <= 1 {
4981 fill(0, rows, cells);
4982 } else {
4983 let shared = crate::par::Shared::new(cells);
4984 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
4985 // SAFETY: cell rows `r0..r1` are this band's alone.
4986 let cells = unsafe { shared.get() };
4987 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
4988 });
4989 }
4990 if crate::envflags::env_flag!("EC_TRACE_TPL") {
4991 eprintln!("EC_TPL_SAVED oh={order_hint}");
4992 for (r, row) in field.occupancy().iter().enumerate() {
4993 eprintln!("EC_TPL_SAVED r{r} {row}");
4994 }
4995 }
4996 field
4997}
4998
4999/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5000/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5001#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5002pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5003 let c = match ref_frame {
5004 LAST2_FRAME => &LAST2_HITS,
5005 LAST3_FRAME => &LAST3_HITS,
5006 GOLDEN_FRAME => &GOLDEN_HITS,
5007 BWDREF_FRAME => &BWDREF_HITS,
5008 ALTREF2_FRAME => &ALTREF2_HITS,
5009 ALTREF_FRAME => &ALTREF_HITS,
5010 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5011 };
5012 c.with(|v| v.get())
5013}
5014
5015 /// The sequence header's `enable_intra_edge_filter`, set once per
5016 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5017 /// own read of it, kept off the call stack (see that function's own doc
5018 /// comment for why) rather than threaded through every `read_plane`/
5019 /// `decode_block`/`decode_leaf8` call between here and there.
5020
5021/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5022///
5023/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5024/// never did -- so an inter frame's intra blocks read whatever value the last
5025/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5026/// harmless (its own key frame sets it first), but a caller that decodes an
5027/// inter frame directly, or a test harness running several streams on one
5028/// thread, inherits a foreign sequence's bit: decode stops being a pure
5029/// function of the bitstream. `decode_stream` now calls this once per stream
5030/// from the sequence header, which covers every frame including inter ones.
5031pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5032 fctx.enable_edge_filter.with(|f| f.set(value));
5033}
5034
5035/// Current value of [`ANGLE_DELTA_HITS`].
5036#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5037pub(crate) fn angle_delta_hits() -> usize {
5038 ANGLE_DELTA_HITS.with(|c| c.get())
5039}
5040
5041/// Current value of [`TX_CLASS1_HITS`].
5042#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5043pub(crate) fn tx_class1_hits() -> usize {
5044 TX_CLASS1_HITS.with(|c| c.get())
5045}
5046
5047// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5048// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5049// bottom) this thread's decode actually reconstructed -- the same
5050// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5051// genuinely exercised the sub-8x8 leaf path rather than every attempt
5052// coincidentally landing on `PARTITION_NONE`.
5053thread_local! {
5054 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5055 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5056 /// sub-blocks (lane-intersub8).
5057 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5058 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5059 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5060 /// `[1] = VERT` (two BLOCK_4X8).
5061 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5062 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5063 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5064 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5065 /// MIXED groups whose chroma reference is INTER while its sibling is
5066 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5067 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5068 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5069 /// so only this cell separates the split arm from the HORZ/VERT one).
5070 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5071}
5072
5073/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5074/// mixed groups, split 4x4 leaves)`.
5075pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5076 SUB8_INTRA_RECT_HITS.with(|c| {
5077 let h = c.get();
5078 (h[0], h[1], h[2], h[3], h[4])
5079 })
5080}
5081
5082/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5083pub fn sub8_inter_rect_hits() -> (usize, usize) {
5084 SUB8_INTER_RECT_HITS.with(|c| {
5085 let h = c.get();
5086 (h[0], h[1])
5087 })
5088}
5089
5090// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5091// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5092// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5093// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5094// (b) was 0 for every stream before this round -- the leaf path never touched
5095// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5096// filtered where libaom skips it. A gate asserts both are non-zero.
5097thread_local! {
5098 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5099 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5100 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5101 // crosses the cropped frame edge -- the only units for which "clamp at
5102 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5103 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5104 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5105 // whose width or height is not a multiple of 8 is the only shape that
5106 // produces one; the straddling-band gate arms assert it grew.
5107 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5108 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5109 // (see `Neighbours::skip_written`).
5110 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5111 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5112 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5113 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5114 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5115 // 8-tall strip pair where only one half is skip must still be FILTERED.
5116 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5117 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5118}
5119
5120/// Current value of `RECT_SKIP_BAND_HITS`.
5121pub fn rect_skip_band_hits() -> usize {
5122 RECT_SKIP_BAND_HITS.with(|c| c.get())
5123}
5124
5125/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5126pub fn cdef_mixed_skip_units() -> usize {
5127 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5128}
5129
5130/// Current value of `CDEF_SKIPPED_UNITS`.
5131#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5132pub(crate) fn cdef_skipped_units() -> usize {
5133 CDEF_SKIPPED_UNITS.with(|c| c.get())
5134}
5135
5136/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5137/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5138pub fn cdef_unwritten_skip_units() -> usize {
5139 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5140}
5141
5142/// Current value of `INTER8_SKIP_BAND_HITS`.
5143#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5144pub(crate) fn inter8_skip_band_hits() -> usize {
5145 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5146}
5147
5148/// Current value of `CDEF_STRADDLE_UNITS`.
5149#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5150pub(crate) fn cdef_straddle_units() -> usize {
5151 CDEF_STRADDLE_UNITS.with(|c| c.get())
5152}
5153
5154/// Current value of [`SUB8_SPLIT_HITS`].
5155#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5156pub(crate) fn sub8_split_hits() -> usize {
5157 SUB8_SPLIT_HITS.with(|c| c.get())
5158}
5159
5160/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5161pub fn sub8_inter_split_hits() -> usize {
5162 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5163}
5164
5165// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5166// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5167// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5168// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5169// first sub-block's type is never the one). Reading it off sub-block 0
5170// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5171// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5172// see this rule through this counter.
5173thread_local! {
5174 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5175}
5176
5177/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5178pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5179 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5180}
5181
5182fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5183 if coeffs && first_sub != chroma_ref {
5184 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5185 }
5186}
5187
5188// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5189// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5190// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5191// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5192// asserts on these two rather than a plain leaf count.
5193thread_local! {
5194 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5195 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5196 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5197 /// two 4x4 transform units, predicted one after the other. A separate
5198 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5199 /// the gate can prove THIS path fired.
5200 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5201 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5202 /// own width (above-right) or height (below-left) -- the samples
5203 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5204 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5205 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5206 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5207 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5208 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5209}
5210
5211/// Current value of [`RECT8_SPLIT_TX_HITS`].
5212#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5213pub(crate) fn rect8_split_tx_hits() -> usize {
5214 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5215}
5216
5217/// Current value of [`RECT_STRIP_PRED_HITS`].
5218#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5219pub(crate) fn rect_strip_pred_hits() -> usize {
5220 RECT_STRIP_PRED_HITS.with(|c| c.get())
5221}
5222
5223/// Current value of [`RECT_STRIP_REACH_HITS`].
5224#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5225pub(crate) fn rect_strip_reach_hits() -> usize {
5226 RECT_STRIP_REACH_HITS.with(|c| c.get())
5227}
5228
5229/// Current value of [`TX4X8_CODED_HITS`].
5230#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5231pub(crate) fn tx4x8_coded_hits() -> usize {
5232 TX4X8_CODED_HITS.with(|c| c.get())
5233}
5234
5235/// Current value of [`TX8X4_CODED_HITS`].
5236#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5237pub(crate) fn tx8x4_coded_hits() -> usize {
5238 TX8X4_CODED_HITS.with(|c| c.get())
5239}
5240
5241// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5242// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5243// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5244// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5245// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5246// (`eob_pt_{16,64,128,256}_chroma_class1`).
5247thread_local! {
5248 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5249 const { std::cell::Cell::new(0) };
5250}
5251
5252/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5253#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5254pub(crate) fn chroma_eob_class1_hits() -> usize {
5255 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5256}
5257
5258/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5259/// `tx_type` put this block's `eob_pt` on the class-1 row.
5260fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5261 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5262 hit!(CHROMA_EOB_CLASS1_HITS);
5263 }
5264}
5265
5266const SUB_MI: u32 = 4;
5267const MI: usize = 4;
5268const SB: usize = 64;
5269/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5270/// (tile start, superblock-row start).
5271///
5272/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5273/// `av1_get_partition_plane_context` reads its own zero-initialised
5274/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5275/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5276/// (64), which reads identically at every level up to 64x64 but sets the bit
5277/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5278/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5279/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5280const NO_NEIGHBOUR_SIDE: usize = 128;
5281const BLOCK: usize = 32;
5282const SUB: usize = 16;
5283const TX32: usize = 32;
5284const TX16: usize = 16;
5285const TX8: usize = 8;
5286const TX4: usize = 4;
5287const DC_PRED: usize = 0;
5288/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5289/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5290/// constant.
5291const V_PRED: usize = 1;
5292const H_PRED: usize = 2;
5293/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
5294/// `Fimode_To_Intradir`, libaom `blockd.h`).
5295const D157_PRED: usize = 6;
5296/// The last directional mode, `D67_PRED`.
5297const D67_PRED: usize = 8;
5298/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
5299/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
5300/// codes anything else, so this decoder never reads anything else either.
5301const ANGLE_DELTA_ZERO: usize = 3;
5302const NUM_BASE_LEVELS: i32 = 2;
5303const COEFF_BASE_RANGE: i32 = 12;
5304const BR_STEP: i32 = 3;
5305const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
5306
5307/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
5308/// whose probability mass a superblock or block half outside the frame
5309/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
5310/// duplicated here (that module is another lane's territory this round) and
5311/// kept in step with it by the byte-exact round-trip tests below rather than
5312/// by sharing code.
5313const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
5314const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
5315
5316fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
5317 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5318 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
5319 }
5320}
5321
5322fn element_prob(cdf: &[u16], element: usize) -> u16 {
5323 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5324}
5325
5326/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5327/// with: the mass of `elements` becomes the probability of the one partition
5328/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5329/// (the encoder's non-adapting counterpart to this read).
5330fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5331 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5332 [32768 - split, 32768, 0]
5333}
5334
5335fn unsupported(what: impl Into<String>) -> Error {
5336 Error::unsupported("AV1 tile", what.into())
5337}
5338
5339/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5340/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5341/// same rule.
5342pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5343 match base_q_idx {
5344 0..=20 => 0,
5345 21..=60 => 1,
5346 61..=120 => 2,
5347 _ => 3,
5348 }
5349}
5350
5351/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5352/// [`crate::tile`]'s writer generates its scan tables with.
5353fn default_scan(side: usize) -> &'static [u16] {
5354 // One table per transform side (4/8/16/32), built once: this used to be a
5355 // fresh heap allocation plus the whole anti-diagonal walk on every
5356 // transform block read.
5357 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5358 [
5359 default_scan_gen(4),
5360 default_scan_gen(8),
5361 default_scan_gen(16),
5362 default_scan_gen(32),
5363 ]
5364 });
5365 assert!(
5366 matches!(side, 4 | 8 | 16 | 32),
5367 "no default scan for a {side}-point transform"
5368 );
5369 &SCANS[side.trailing_zeros() as usize - 2]
5370}
5371
5372fn default_scan_gen(side: usize) -> Vec<u16> {
5373 let mut scan = Vec::with_capacity(side * side);
5374 for d in 0..(2 * side - 1) {
5375 let lo = d.saturating_sub(side - 1);
5376 let hi = d.min(side - 1);
5377 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5378 if d % 2 == 0 {
5379 scan.extend(diagonal.rev());
5380 } else {
5381 scan.extend(diagonal);
5382 }
5383 }
5384 scan
5385}
5386
5387/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5388/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5389/// in, instead of the default zigzag. libaom's own tables are keyed by a
5390/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5391/// physically column-major level buffer, but they decompose to the exact
5392/// same (row, col) walk as a flat row-major traversal of *our* row-major
5393/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5394/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5395/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5396/// transposed (column 0 down every row, then column 1, ...).
5397fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5398 class_scan_table_wh(side, side, class)
5399}
5400
5401/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5402/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5403/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5404/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5405/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5406/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5407fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5408 match class {
5409 TxClass::Vert => (0..(w * h) as u16).collect(),
5410 TxClass::Horiz => (0..w)
5411 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5412 .collect(),
5413 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5414 }
5415}
5416
5417fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5418 match scan_idx {
5419 0 => 0,
5420 i if i <= area / 8 => 1,
5421 i if i <= area / 4 => 2,
5422 _ => 3,
5423 }
5424}
5425
5426/// One cell of [`read_coeffs`]'s level buffer.
5427///
5428/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
5429/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
5430/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
5431/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
5432/// zero cells instead of needing the `row >= side || col >= side` edge test
5433/// this used to run five times per coefficient. Nothing writes a padding
5434/// cell, so the values are the same zeros the test returned.
5435#[inline]
5436fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5437 grid[row * stride + col] as i32
5438}
5439
5440/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5441/// `txb_common.h`): everything but the two lone-axis-identity types this
5442/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5443#[derive(Clone, Copy, PartialEq, Eq)]
5444enum TxClass {
5445 TwoD,
5446 Horiz,
5447 Vert,
5448}
5449
5450impl TxClass {
5451 fn of(tx_type: TxType) -> Self {
5452 match tx_type {
5453 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5454 // key on axis alone -- FLIPADST is still ADST for this purpose.
5455 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5456 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5457 _ => Self::TwoD,
5458 }
5459 }
5460}
5461
5462/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5463/// table (indexed by the position along the transform's *coded* axis --
5464/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5465/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5466/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5467fn nz_map_ctx_offset_1d(i: usize) -> usize {
5468 match i {
5469 0 => 26,
5470 1 => 31,
5471 _ => 36,
5472 }
5473}
5474
5475fn base_ctx(
5476 grid: &[u8],
5477 stride: usize,
5478 row: usize,
5479 col: usize,
5480 class: TxClass,
5481 rect_shape: Option<(usize, usize)>,
5482) -> usize {
5483 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5484 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5485 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5486 // position through the full 1D neighbour sum and offset table. Skipping
5487 // that for every class desynced the last (DC) coefficient of a
5488 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5489 // 0, which then read one extra `BR` symbol at the max and forced a
5490 // spurious third Golomb call).
5491 if class == TxClass::TwoD && row == 0 && col == 0 {
5492 return 0;
5493 }
5494 let offsets: [(usize, usize); 5] = match class {
5495 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5496 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5497 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5498 };
5499 let mag: i32 = offsets
5500 .iter()
5501 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
5502 .sum();
5503 let ctx = ((mag + 1) >> 1).min(4) as usize;
5504 match class {
5505 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5506 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5507 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5508 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5509 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5510 // strip, which own a genuinely different table from the square one
5511 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5512 // square table vs the real ctx 13 the rect table gives).
5513 TxClass::TwoD => {
5514 // lane-rectsplit r4: apply libaom's GENERATING RULE
5515 // (`txb_common.h:199-209`) directly instead of indexing the
5516 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5517 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5518 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5519 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5520 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5521 // transcriptions are `[col][row]` and this read had them as
5522 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5523 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5524 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5525 // pins the rule against the tables over their whole 5x5 domain.
5526 if let Some((w, h)) = rect_shape {
5527 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5528 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
5529 }
5530 if w < h && row < 2 {
5531 return ctx + 11;
5532 }
5533 if w > h && col < 2 {
5534 return ctx + 16;
5535 }
5536 }
5537 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5538 }
5539 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5540 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5541 }
5542}
5543
5544/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
5545/// offsets into the padded level frame (lane-coefread): the tap pattern is a
5546/// function of the tx class alone, which is fixed for a whole transform unit,
5547/// so resolving it once per unit takes the class match and the `(dr, dc)`
5548/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
5549/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
5550/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
5551/// original `(dr, dc)` form.
5552fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
5553 match class {
5554 TxClass::TwoD => (
5555 [stride, 1, stride + 1, 2 * stride, 2],
5556 [stride, 1, stride + 1],
5557 ),
5558 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
5559 TxClass::Vert => (
5560 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
5561 [stride, 1, 2 * stride],
5562 ),
5563 }
5564}
5565
5566/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
5567/// neighbours) + 1) >> 1`, clamped to 4.
5568#[inline(always)]
5569fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
5570 let mut mag = 0u32;
5571 for &t in taps {
5572 mag += u32::from(grid[idx + t]).min(3);
5573 }
5574 (((mag + 1) >> 1) as usize).min(4)
5575}
5576
5577/// [`br_ctx`]'s neighbour sum, off flat taps.
5578#[inline(always)]
5579fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
5580 let mut mag = 0u32;
5581 for &t in taps {
5582 mag += u32::from(grid[idx + t]);
5583 }
5584 (((mag + 1) >> 1) as usize).min(6)
5585}
5586
5587/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
5588/// origin-offset tail the two coefficient readers state inline; kept as the
5589/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
5590/// flat one against.
5591#[cfg(test)]
5592fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
5593 let extra = match class {
5594 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
5595 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
5596 TxClass::Vert => neighbour(grid, stride, row + 2, col),
5597 };
5598 let mag = neighbour(grid, stride, row + 1, col)
5599 + neighbour(grid, stride, row, col + 1)
5600 + extra;
5601 let mag = (((mag + 1) >> 1).min(6)) as usize;
5602 if row == 0 && col == 0 {
5603 return mag;
5604 }
5605 let near_origin = match class {
5606 TxClass::TwoD => row < 2 && col < 2,
5607 TxClass::Horiz => col == 0,
5608 TxClass::Vert => row == 0,
5609 };
5610 if near_origin { mag + 7 } else { mag + 14 }
5611}
5612
5613/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
5614/// transposed from libaom's column-major buffer into this decoder's row-major
5615/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
5616/// against the real table). Not the square zigzag formula generalized to
5617/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
5618const SCAN_32X16: [u16; 512] = [
5619 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
5620 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
5621 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
5622 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
5623 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
5624 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
5625 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
5626 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
5627 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
5628 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
5629 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
5630 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
5631 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
5632 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
5633 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
5634 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
5635 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
5636 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
5637 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
5638 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
5639 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
5640 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
5641 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
5642 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
5643 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
5644 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
5645 509, 478, 447, 510, 479, 511,
5646];
5647
5648/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
5649/// [`SCAN_32X16`]'s doc comment).
5650const SCAN_16X32: [u16; 512] = [
5651 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,
5652 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
5653 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
5654 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
5655 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
5656 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
5657 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
5658 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
5659 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
5660 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
5661 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
5662 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
5663 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
5664 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
5665 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
5666 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
5667 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
5668 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
5669 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
5670 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
5671 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
5672 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
5673 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
5674 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
5675 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
5676 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
5677];
5678
5679/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
5680/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
5681/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
5682/// the same source).
5683const SCAN_4X8: [u16; 32] = [
5684 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,
5685 23, 26, 29, 27, 30, 31,
5686];
5687
5688/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
5689const SCAN_8X4: [u16; 32] = [
5690 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,
5691 29, 22, 15, 30, 23, 31,
5692];
5693
5694/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
5695/// [`SCAN_32X16`]'s doc comment).
5696const SCAN_16X8: [u16; 128] = [
5697 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,
5698 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
5699 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
5700 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
5701 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
5702 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
5703];
5704
5705/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
5706/// [`SCAN_32X16`]'s doc comment).
5707const SCAN_8X16: [u16; 128] = [
5708 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,
5709 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5710 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5711 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5712 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
5713 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
5714];
5715
5716/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
5717/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
5718/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
5719/// scans column-major (`p = col * height + row`), so a naive copy of
5720/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
5721/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
5722/// are byte-identical to this decoder's [`SCAN_8X16`].
5723const SCAN_32X8: [u16; 256] = [
5724 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
5725 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
5726 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
5727 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
5728 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
5729 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
5730 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
5731 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
5732 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
5733 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
5734 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
5735 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
5736 222, 191, 254, 223, 255,
5737];
5738/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
5739/// 16x64 `PARTITION_VERT_4` strip).
5740const SCAN_8X32: [u16; 256] = [
5741 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,
5742 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5743 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5744 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5745 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
5746 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
5747 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
5748 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
5749 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
5750 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
5751 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
5752 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
5753 239, 246, 253, 247, 254, 255,
5754];
5755/// `Default_Scan_16x4`, this decoder's own row-major transcription of
5756/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
5757/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
5758/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
5759/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
5760/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
5761/// were emitted -- a naive copy installs the transpose (class
5762/// reference-layout-not-spec).
5763const SCAN_16X4: [u16; 64] = [
5764 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,
5765 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
5766 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
5767];
5768/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
5769/// 8x32 `PARTITION_VERT_4` strip).
5770const SCAN_4X16: [u16; 64] = [
5771 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,
5772 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
5773 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
5774];
5775
5776/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
5777/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
5778/// padding already holds.
5779#[inline]
5780fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5781 grid[row * stride + col] as i32
5782}
5783
5784/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
5785/// the rect generalization is libaom's own comment in
5786/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
5787/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
5788/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
5789/// [`decode_block_rect`] codes (see that function's own doc comment).
5790fn base_ctx_rect(
5791 grid: &[u8],
5792 stride: usize,
5793 w: usize,
5794 h: usize,
5795 row: usize,
5796 col: usize,
5797 class: TxClass,
5798) -> usize {
5799 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
5800 // the 2D class short-circuits the DC position.
5801 if class == TxClass::TwoD && row == 0 && col == 0 {
5802 return 0;
5803 }
5804 let offsets: [(usize, usize); 5] = match class {
5805 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5806 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5807 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5808 };
5809 let mag: i32 = offsets
5810 .iter()
5811 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
5812 .sum();
5813 let ctx = ((mag + 1) >> 1).min(4) as usize;
5814 match class {
5815 TxClass::TwoD => {
5816 if w < h && row < 2 {
5817 return ctx + 11;
5818 }
5819 if w > h && col < 2 {
5820 return ctx + 16;
5821 }
5822 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5823 }
5824 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
5825 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
5826 // position along one axis only).
5827 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5828 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5829 }
5830}
5831
5832/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
5833/// neighbour-offset math itself is shape-independent, only the boundary
5834/// clamp needs the real bound in each axis.
5835/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
5836/// its body was character-for-character [`br_ctx`]'s, which
5837/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
5838#[cfg(test)]
5839fn br_ctx_rect(
5840 grid: &[u8],
5841 stride: usize,
5842 row: usize,
5843 col: usize,
5844 class: TxClass,
5845) -> usize {
5846 let extra = match class {
5847 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
5848 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
5849 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
5850 };
5851 let mag = neighbour_rect(grid, stride, row + 1, col)
5852 + neighbour_rect(grid, stride, row, col + 1)
5853 + extra;
5854 let mag = (((mag + 1) >> 1).min(6)) as usize;
5855 if row == 0 && col == 0 {
5856 return mag;
5857 }
5858 let near_origin = match class {
5859 TxClass::TwoD => row < 2 && col < 2,
5860 TxClass::Horiz => col == 0,
5861 TxClass::Vert => row == 0,
5862 };
5863 if near_origin { mag + 7 } else { mag + 14 }
5864}
5865
5866fn dc_vote(dc: Option<bool>) -> i32 {
5867 match dc {
5868 None => 0,
5869 Some(true) => -1,
5870 Some(false) => 1,
5871 }
5872}
5873
5874fn dc_sign_ctx(vote: i32) -> usize {
5875 match vote.signum() {
5876 0 => 0,
5877 -1 => 1,
5878 _ => 2,
5879 }
5880}
5881
5882/// The `tx_type` a CDF symbol names, given the width of the row it was read
5883/// from.
5884///
5885/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
5886/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
5887/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
5888/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
5889/// members are a prefix of the five.
5890///
5891/// One function rather than a `match` at each reader, so
5892/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
5893/// tests the mapping the readers actually use.
5894pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
5895 match cdf_len {
5896 17 => TxType::from_symbol_all16(t),
5897 13 => TxType::from_symbol_set2_12(t),
5898 8 => TxType::from_symbol_set1(t),
5899 _ => TxType::from_symbol(t),
5900 }
5901}
5902
5903/// The remainder of a level the base and base-range syntax could not reach
5904/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
5905/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
5906pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
5907 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
5908 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
5909 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
5910 // for every tail any encoder writes -- our own writer tops out at 19 zeros
5911 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
5912 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
5913 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
5914 // RED: seed 67 stops here today, and with the cap raised it decodes to a
5915 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
5916 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
5917 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
5918 // together with that defect's fix, not before.
5919 let mut length = 1u32;
5920 while dec.literal(1) == 0 {
5921 length += 1;
5922 if length > 20 {
5923 return Err(unsupported("a Golomb tail longer than this decoder reads"));
5924 }
5925 }
5926 let mut x = 1u32;
5927 for _ in 1..length {
5928 x = (x << 1) | dec.literal(1);
5929 }
5930 Ok(x - 1)
5931}
5932
5933/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
5934/// [`crate::tile`]'s `write_eob`.
5935fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
5936 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
5937 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
5938
5939 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
5940 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
5941 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
5942 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
5943 // `eob_multi_ctx`). Missing that split desynced the very first
5944 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
5945 // against a real aomdec trace).
5946 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
5947 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
5948 (_, Some(class1)) => class1,
5949 };
5950 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
5951 let (range, value) = dec.debug_state();
5952 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
5953 }
5954 let group = dec.symbol(eob_pt) + 1;
5955 if trace {
5956 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
5957 }
5958 let bits = OFFSET_BITS[group];
5959 let mut offset = 0u32;
5960 if bits > 0 {
5961 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
5962 if trace {
5963 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
5964 }
5965 offset = top << (bits - 1);
5966 if bits > 1 {
5967 offset |= dec.literal(bits - 1);
5968 }
5969 }
5970 GROUP_START[group] + offset as usize
5971}
5972
5973/// One transform block's levels, the inverse of [`crate::tile`]'s
5974/// `write_coeffs`, returned as a `side * side` grid in raster order, along
5975/// with the transform type that grid was coded under (`DCT_DCT` when the
5976/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
5977/// 64-point transforms, which never code anything else).
5978///
5979/// # Errors
5980/// Returns an error if the `tx_type` symbol decodes to a value outside its
5981/// CDF's own set (a corrupt or unsupported bitstream) — every value the
5982/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
5983/// produce dispatches to a real inverse transform.
5984/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
5985/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
5986/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
5987/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
5988/// the plane's own predicted mode instead. Every entry this table can
5989/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
5990/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
5991/// table ever names), so unlike the CDF-coded luma path there is no
5992/// ext-tx-set membership check to fall back from here.
5993pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
5994 use crate::intra::{
5995 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
5996 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
5997 };
5998 match mode {
5999 DC_PRED | D45_PRED => TxType::DctDct,
6000 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6001 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6002 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6003 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6004 }
6005}
6006
6007/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6008/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6009/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6010fn is_smooth_mode(mode: usize) -> bool {
6011 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6012}
6013
6014/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6015/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6016/// nine of them inside the base/sign loops pinned nine sets of values in the
6017/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6018/// traffic). Out of line, the loop keeps its values in registers and the
6019/// trace output is character-for-character what it was.
6020#[cold]
6021#[inline(never)]
6022fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6023 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6024}
6025
6026#[cold]
6027#[inline(never)]
6028fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6029 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6030}
6031
6032#[cold]
6033#[inline(never)]
6034fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6035 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6036}
6037
6038#[cold]
6039#[inline(never)]
6040fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6041 let (rng, _) = dec.debug_state();
6042 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6043}
6044
6045#[cold]
6046#[inline(never)]
6047fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6048 let (rng, _) = dec.debug_state();
6049 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6050}
6051
6052#[cold]
6053#[inline(never)]
6054fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6055 let (rng, _) = dec.debug_state();
6056 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6057}
6058
6059#[cold]
6060#[inline(never)]
6061fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6062 let (rng, _) = dec.debug_state();
6063 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6064}
6065
6066#[cold]
6067#[inline(never)]
6068fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6069 let (rng, _) = dec.debug_state();
6070 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6071}
6072
6073fn read_coeffs(
6074 dec: &mut SymbolDecoder,
6075 coding: &mut TxbTables,
6076 scan: &[u16],
6077 skip_ctx: usize,
6078 sign_ctx: usize,
6079 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6080 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6081 // nothing at all; `DctDct` for every luma call and every chroma call at
6082 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6083 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6084 default_tx_type: TxType,
6085 // `Some((w, h))` with `w != h` when this read is a superblock-level
6086 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6087 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6088 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6089 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6090 // caller's block genuinely is `side` x `side`.
6091 rect_shape: Option<(usize, usize)>,
6092) -> Result<(Grid, TxType)> {
6093 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6094 let side = coding.side;
6095 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6096 let (range, value) = dec.debug_state();
6097 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6098 }
6099 let dbg_txbskip = if coeff_trace_on() {
6100 coding.txb_skip[skip_ctx]
6101 } else {
6102 [0; 3]
6103 };
6104 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6105 if coeff_trace_on() {
6106 let (rng, _) = dec.debug_state();
6107 eprintln!(
6108 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6109 coding.side,
6110 all_zero as i32
6111 );
6112 }
6113 if crate::envflags::env_flag!("EC_AV1_TELL") {
6114 eprintln!(
6115 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6116 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6117 );
6118 }
6119 if trace {
6120 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6121 }
6122 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6123 let (range, value) = dec.debug_state();
6124 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6125 }
6126 if all_zero {
6127 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6128 // shared zero grid instead of allocating and zeroing its own.
6129 return Ok((Grid::Zero(side * side), TxType::DctDct));
6130 }
6131 let mut grid = vec![0i32; side * side];
6132 let mut tx_type = default_tx_type;
6133 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6134 // The CDF row's own width names its set (lane-cdffwd2: extended
6135 // past the original two-way intra split once wider `reduced_tx_set
6136 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6137 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6138 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6139 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6140 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6141 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6142 let len = tx_type_cdf.len();
6143 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6144 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6145 }
6146 let t = dec.symbol(tx_type_cdf);
6147 if coeff_trace_on() {
6148 let (rng, _) = dec.debug_state();
6149 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6150 }
6151 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6152 let (range, value) = dec.debug_state();
6153 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6154 }
6155 if trace {
6156 eprintln!("TRACE tx_type value={t} len={len}");
6157 }
6158 tx_type = tx_type_from_symbol(len, t)
6159 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6160 }
6161
6162 let class = TxClass::of(tx_type);
6163 if class != TxClass::TwoD {
6164 hit!(TX_CLASS1_HITS);
6165 hit!(RECT_CLASS1_HITS);
6166 }
6167 let eob = read_eob(dec, coding, class);
6168 if trace {
6169 eprintln!("TRACE eob value={eob}");
6170 }
6171 let ec_trace_coeff = coeff_trace_on();
6172 if ec_trace_coeff {
6173 let (rng, _) = dec.debug_state();
6174 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6175 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6176 }
6177 let class_scan;
6178 let scan: &[u16] = if class == TxClass::TwoD {
6179 scan
6180 } else {
6181 class_scan = class_scan_table(side, class);
6182 &class_scan
6183 };
6184 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6185 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6186 // shift and a mask say the same thing, and the level buffer fits a fixed
6187 // 32x32 frame of stack instead of a heap allocation per transform block.
6188 debug_assert!(side.is_power_of_two() && side <= 32);
6189 let sh = side.trailing_zeros();
6190 let col_mask = side - 1;
6191 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6192 // `stride = side + 4` columns and four spare rows, so the widest read
6193 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6194 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6195 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6196 let stride = side + 4;
6197 let mut levels_buf = [0u8; 36 * 36];
6198 let levels = &mut levels_buf[..stride * stride];
6199 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6200 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6201 // padded frame just to skip the zeros. The base pass already knows both,
6202 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6203 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6204 // pass walks that list in reverse (the base pass runs in reverse scan
6205 // order, so reversing it is forward scan order: the same coefficients, in
6206 // the same order, with the same `c` the trace prints).
6207 let mut nz_buf = [0u16; 1024];
6208 let mut nz_n = 0usize;
6209 let (base_taps, br_taps) = flat_taps(stride, class);
6210 for scan_idx in (0..eob).rev() {
6211 let pos = scan[scan_idx] as usize;
6212 let (row, col) = (pos >> sh, pos & col_mask);
6213 let idx = row * stride + col;
6214 let level = if scan_idx == eob - 1 {
6215 let ctx = eob_coeff_ctx(scan_idx, side * side);
6216 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6217 if trace {
6218 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6219 }
6220 v
6221 } else {
6222 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6223 if row == 0 && col == 0 {
6224 0
6225 } else {
6226 base_mag(levels, idx, &base_taps)
6227 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6228 }
6229 } else {
6230 base_ctx(levels, stride, row, col, class, rect_shape)
6231 };
6232 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6233 if ec_trace_coeff {
6234 // `pos` in libaom's column-major `coeff_idx` convention, so
6235 // the ladder lines up with instrumented `aomdec`.
6236 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6237 }
6238 if trace {
6239 trace_base(scan_idx, pos, row, col, ctx, v);
6240 }
6241 v
6242 };
6243 let level = if level > NUM_BASE_LEVELS {
6244 let ctx = {
6245 let mag = br_mag(levels, idx, &br_taps);
6246 if row == 0 && col == 0 {
6247 mag
6248 } else {
6249 let near_origin = match class {
6250 TxClass::TwoD => row < 2 && col < 2,
6251 TxClass::Horiz => col == 0,
6252 TxClass::Vert => row == 0,
6253 };
6254 if near_origin { mag + 7 } else { mag + 14 }
6255 }
6256 };
6257 let mut level = level;
6258 let mut sent = 0;
6259 loop {
6260 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6261 if ec_trace_coeff {
6262 // lane-leaf8tx r3: the `br` rung was missing from THIS
6263 // path's trace, so the cross-decoder range ladder was
6264 // blind to every base-range symbol and mis-reported the
6265 // first divergence (class [[gate-blind-to-feature]]).
6266 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6267 }
6268 if trace {
6269 trace_br(scan_idx, pos, row, col, ctx, k);
6270 }
6271 level += k;
6272 sent += BR_STEP;
6273 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6274 break;
6275 }
6276 }
6277 level
6278 } else {
6279 level
6280 };
6281 if ec_trace_coeff && scan_idx == eob - 1 {
6282 coeff_step_base_eob_level(dec, level);
6283 }
6284 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
6285 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
6286 // added in the sign pass below, straight into `grid`), so the context
6287 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
6288 // byte gather (lane-coefbuf).
6289 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6290 levels[idx] = level as u8;
6291 if level != 0 {
6292 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6293 nz_n += 1;
6294 }
6295 }
6296 if ec_trace_coeff {
6297 let (rng, _) = dec.debug_state();
6298 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6299 }
6300
6301 for &packed in nz_buf[..nz_n].iter().rev() {
6302 let c = (packed >> 4) as usize;
6303 let pos = scan[c] as usize;
6304 let level = (packed & 15) as i32;
6305 let negative = if pos == 0 {
6306 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
6307 if trace {
6308 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
6309 }
6310 v
6311 } else {
6312 dec.literal(1) == 1
6313 };
6314 if ec_trace_coeff {
6315 coeff_step_sign(dec, c, negative);
6316 }
6317 let level = if level > MAX_BR_LEVEL {
6318 let g = read_golomb(dec)?;
6319 if trace {
6320 eprintln!("TRACE golomb pos={pos} value={g}");
6321 }
6322 level + g as i32
6323 } else {
6324 level
6325 };
6326 if ec_trace_coeff {
6327 coeff_step_post_golomb(dec, c, level);
6328 }
6329 grid[pos] = if negative { -level } else { level };
6330 }
6331 Ok((Grid::Own(grid), tx_type))
6332}
6333
6334/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
6335/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
6336/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
6337/// can ever produce, since every `tx_type` this decoder's rect sets can read
6338/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
6339/// rather than guess-decode if a non-2D class ever shows up here, since
6340/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
6341/// form for those.
6342
6343fn read_coeffs_rect(
6344 dec: &mut SymbolDecoder,
6345 coding: &mut TxbTables,
6346 scan: &[u16],
6347 w: usize,
6348 h: usize,
6349 skip_ctx: usize,
6350 sign_ctx: usize,
6351 default_tx_type: TxType,
6352) -> Result<(Grid, TxType)> {
6353 let rect_trace = coeff_trace_on();
6354 let entry_rng = dec.debug_state().0;
6355 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6356 if rect_trace {
6357 eprintln!(
6358 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
6359 all_zero as i32,
6360 dec.debug_state().0
6361 );
6362 }
6363 if all_zero {
6364 return Ok((Grid::Zero(w * h), TxType::DctDct));
6365 }
6366 let mut grid = vec![0i32; w * h];
6367 hit!(RECT_COEFF_TU_HITS);
6368 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
6369 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
6370 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
6371 // context offsets -- both of which now have rect forms
6372 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
6373 // The rect sets that carry no symbol at all still pass `None` here.
6374 let mut tx_type = default_tx_type;
6375 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6376 let len = tx_type_cdf.len();
6377 let t = dec.symbol(tx_type_cdf);
6378 tx_type = tx_type_from_symbol(len, t)
6379 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6380 if rect_trace {
6381 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
6382 }
6383 }
6384 let class = TxClass::of(tx_type);
6385 if class != TxClass::TwoD {
6386 hit!(TX_CLASS1_HITS);
6387 }
6388 let eob = read_eob(dec, coding, class);
6389 if rect_trace {
6390 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
6391 }
6392 let class_scan;
6393 let scan: &[u16] = if class == TxClass::TwoD {
6394 scan
6395 } else {
6396 class_scan = class_scan_table_wh(w, h, class);
6397 &class_scan
6398 };
6399 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
6400 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
6401 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
6402 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
6403 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
6404 // mask rather than a hardware divide.
6405 let stride = w + 4;
6406 let n = stride * (h + 4);
6407 debug_assert!(w.is_power_of_two() && n <= 36 * 36);
6408 let (mut b96, mut b256, mut b768);
6409 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
6410 let levels: &mut [u8] = if n <= 96 {
6411 b96 = [0u8; 96];
6412 &mut b96[..n]
6413 } else if n <= 256 {
6414 b256 = [0u8; 256];
6415 &mut b256[..n]
6416 } else {
6417 b768 = [0u8; 768];
6418 &mut b768[..n]
6419 };
6420 let wsh = w.trailing_zeros();
6421 let wmask = w - 1;
6422 // lane-coefread: the non-zero list [`read_coeffs`] documents.
6423 let mut nz_buf = [0u16; 1024];
6424 let mut nz_n = 0usize;
6425 let (base_taps, br_taps) = flat_taps(stride, class);
6426 let (wlt, wgt) = (w < h, w > h);
6427 for scan_idx in (0..eob).rev() {
6428 let pos = scan[scan_idx] as usize;
6429 let (row, col) = (pos >> wsh, pos & wmask);
6430 let idx = row * stride + col;
6431 // libaom's column-major `coeff_idx`, for ladder comparison.
6432 let _apos = col * h + row;
6433 let level = if scan_idx == eob - 1 {
6434 let ctx = eob_coeff_ctx(scan_idx, w * h);
6435 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6436 if rect_trace {
6437 eprintln!(
6438 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6439 dec.debug_state().0
6440 );
6441 }
6442 v
6443 } else {
6444 let ctx = if class == TxClass::TwoD {
6445 if row == 0 && col == 0 {
6446 0
6447 } else {
6448 let m = base_mag(levels, idx, &base_taps);
6449 if wlt && row < 2 {
6450 m + 11
6451 } else if wgt && col < 2 {
6452 m + 16
6453 } else {
6454 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6455 }
6456 }
6457 } else {
6458 base_ctx_rect(levels, stride, w, h, row, col, class)
6459 };
6460 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6461 if rect_trace {
6462 eprintln!(
6463 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6464 dec.debug_state().0
6465 );
6466 }
6467 v
6468 };
6469 let level = if level > NUM_BASE_LEVELS {
6470 let ctx = {
6471 let mag = br_mag(levels, idx, &br_taps);
6472 if row == 0 && col == 0 {
6473 mag
6474 } else {
6475 let near_origin = match class {
6476 TxClass::TwoD => row < 2 && col < 2,
6477 TxClass::Horiz => col == 0,
6478 TxClass::Vert => row == 0,
6479 };
6480 if near_origin { mag + 7 } else { mag + 14 }
6481 }
6482 };
6483 let mut level = level;
6484 let mut sent = 0;
6485 loop {
6486 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6487 if rect_trace {
6488 eprintln!(
6489 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
6490 dec.debug_state().0
6491 );
6492 }
6493 level += k;
6494 sent += BR_STEP;
6495 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6496 break;
6497 }
6498 }
6499 level
6500 } else {
6501 level
6502 };
6503 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6504 levels[idx] = level as u8;
6505 if level != 0 {
6506 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6507 nz_n += 1;
6508 }
6509 if rect_trace {
6510 let (rng, _) = dec.debug_state();
6511 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
6512 }
6513 }
6514 if rect_trace {
6515 let (rng, _) = dec.debug_state();
6516 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6517 }
6518 for &packed in nz_buf[..nz_n].iter().rev() {
6519 let pos = scan[(packed >> 4) as usize] as usize;
6520 let level = (packed & 15) as i32;
6521 let negative = if pos == 0 {
6522 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
6523 } else {
6524 dec.literal(1) == 1
6525 };
6526 if rect_trace {
6527 let (rng, _) = dec.debug_state();
6528 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
6529 }
6530 let level = if level > MAX_BR_LEVEL {
6531 let g = read_golomb(dec)?;
6532 level + g as i32
6533 } else {
6534 level
6535 };
6536 grid[pos] = if negative { -level } else { level };
6537 }
6538 Ok((Grid::Own(grid), tx_type))
6539}
6540
6541/// What one coded block leaves behind for the blocks that read it as a
6542/// neighbour: whether it coded anything at all, and the sign of its DC —
6543/// [`crate::tile`]'s own private `Neighbour`.
6544#[derive(Clone, Copy, Default)]
6545struct Neighbour {
6546 /// The transform unit's cumulative coefficient level (spec `cul_level`,
6547 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
6548 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
6549 /// boolean (`level != 0`) is enough for every context this decoder read
6550 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
6551 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
6552 /// needs the actual magnitude tier of its above/left neighbours, not
6553 /// just whether they coded anything.
6554 level: u8,
6555 dc: Option<bool>,
6556}
6557
6558/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
6559/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
6560/// grid is dropped, never a panic. One `memset` per grid row instead of a
6561/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
6562/// is contiguous, so this writes exactly the cells the cell loop did,
6563/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
6564/// next row.
6565#[inline]
6566fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
6567 let end = (start + n).min(dst.len());
6568 if start < end {
6569 dst[start..end].fill(v);
6570 }
6571}
6572
6573fn neighbour_state(grid: &[i32]) -> Neighbour {
6574 // lane-coefgrid: the shared zero grid sums to zero by construction; this
6575 // sum has no early exit, so the 60% of units that code nothing used to
6576 // walk their whole grid here.
6577 if is_zero_grid(grid) {
6578 return Neighbour::default();
6579 }
6580 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
6581 Neighbour {
6582 level: cul.min(7) as u8,
6583 dc: (grid[0] != 0).then_some(grid[0] < 0),
6584 }
6585}
6586
6587/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6588/// transform unit smaller than the block it sits in): `top`/`left` are the
6589/// above/left neighbours' magnitude tiers, each already clamped to 4.
6590pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6591 [1, 2, 2, 2, 3],
6592 [2, 4, 4, 4, 5],
6593 [2, 4, 4, 4, 5],
6594 [2, 4, 4, 4, 5],
6595 [3, 5, 5, 5, 6],
6596];
6597
6598/// The `skip` flag, its written-instrument bit, and the covering coded
6599/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
6600/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
6601/// nothing else, so a block's row is one fill instead of four, and the
6602/// deblocker's `pu_edge` reads origin and dims off one cache line.
6603#[derive(Clone, Copy)]
6604struct BlkCell {
6605 skip: bool,
6606 written: bool,
6607 org: [u16; 2],
6608 dim: [u8; 2],
6609}
6610
6611/// The neighbour state a block's contexts are read from — a duplicate of
6612/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
6613/// territory this round), kept at the same two granularities the real writer
6614/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
6615/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
6616/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
6617/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
6618/// chroma transform straddling the true, odd-sized frame edge see its
6619/// neighbour's state clamped at its own subsampled edge rather than luma's.
6620#[derive(Clone)]
6621struct Neighbours {
6622 above: Vec<[Neighbour; 3]>,
6623 left: Vec<[Neighbour; 3]>,
6624 above_mode: Vec<usize>,
6625 left_mode: Vec<usize>,
6626 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
6627 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
6628 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
6629 /// luma one -- the same block can (and often does) code a different
6630 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
6631 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
6632 /// within-block neighbour finer than this grid) is luma-only -- a known,
6633 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
6634 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
6635 above_uv_mode: Vec<usize>,
6636 left_uv_mode: Vec<usize>,
6637 above_side: Vec<usize>,
6638 left_side: Vec<usize>,
6639 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
6640 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
6641 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
6642 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
6643 /// array cannot tell the second leaf's partition symbol that the first
6644 /// one was coded at 8x8.
6645 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
6646 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
6647 above_side_mi: Vec<u8>,
6648 left_side_mi: Vec<u8>,
6649 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
6650 /// / row, with the mi position it was written at
6651 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
6652 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
6653 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
6654 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
6655 /// leaf whose neighbour is another split group needs that group's leaf 3
6656 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
6657 /// and read only by [`decode_leaf_split4`]; the position guard makes it
6658 /// fall back to the coarse slot whenever the real neighbour was a block
6659 /// of 8x8 or larger (whose one mode is correct for every row it spans).
6660 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
6661 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
6662 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
6663 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
6664 /// frame is 65536 px = 16384 mi).
6665 sub8_mode_col: Vec<(u16, u8)>,
6666 sub8_mode_row: Vec<(u16, u8)>,
6667 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
6668 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
6669 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
6670 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
6671 /// the leaf above writes the same row slot the block to the left owns.
6672 uv_mode_col: Vec<(u16, u8)>,
6673 uv_mode_row: Vec<(u16, u8)>,
6674 /// Every mi cell's own `uv_mode`, the mi grid libaom's
6675 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
6676 /// blockd.h). lane-t900 r12: the one-slot-per-column
6677 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
6678 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
6679 /// overwrote the row the pair's chroma-ref half then wanted to read --
6680 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
6681 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
6682 uv_mode_grid: Vec<u8>,
6683 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
6684 /// every other band here).
6685 uv_grid_cols: usize,
6686 /// Whether the block above/left of this column/row was coded `skip` --
6687 /// an inter frame's own `skip` context (spec `SkipContext`), which the
6688 /// key-frame writer never tracks (its skip context is always zero); a
6689 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
6690 /// `left_skip`.
6691 above_skip: Vec<bool>,
6692 left_skip: Vec<bool>,
6693 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
6694 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
6695 /// pixels last written over each unit by `set_txfm_ctxs`/
6696 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
6697 /// symbol reads its context from (lane-txselect, spec 5.11.17).
6698 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
6699 /// array is exactly libaom's per-superblock-row reset, since each mi row
6700 /// is only ever visited inside one superblock row.
6701 above_txfm: Vec<u8>,
6702 left_txfm: Vec<u8>,
6703 /// Whether the block above/left of this column/row coded `skip_mode`
6704 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
6705 /// lane-av1comp round 14.
6706 above_skip_mode: Vec<bool>,
6707 left_skip_mode: Vec<bool>,
6708 /// Whether the block above/left was coded inter -- the `is_inter`
6709 /// context (spec `av1_get_intra_inter_context`), a duplicate of
6710 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
6711 above_inter: Vec<bool>,
6712 left_inter: Vec<bool>,
6713 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
6714 /// alphabet) the block above/left of this column/row coded, or `-1` for
6715 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
6716 /// functions (`mvstack::ref_ctx` family) need the real reference, not
6717 /// just "was it inter" (lane-av1refs: every inter block used to be
6718 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
6719 /// enough).
6720 above_ref: Vec<i8>,
6721 left_ref: Vec<i8>,
6722 /// The block above/left's *second* reference frame when it was coded
6723 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
6724 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
6725 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
6726 /// `i8`, once a compound `read_ref_frames` lands.
6727 /// lane-publish2 audit: the "always `None` today" note this doc used to
6728 /// carry is long stale -- compound blocks do occur, and
6729 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
6730 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
6731 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
6732 /// [`crate::mvstack::NeighbourRef`] construction (class
6733 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
6734 above_ref1: Vec<Option<i8>>,
6735 left_ref1: Vec<Option<i8>>,
6736 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
6737 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
6738 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
6739 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
6740 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
6741 above_comp_group_idx: Vec<u8>,
6742 left_comp_group_idx: Vec<u8>,
6743 above_compound_idx: Vec<u8>,
6744 left_compound_idx: Vec<u8>,
6745 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
6746 /// `3` = "no info": an intra neighbour or the frame's own border) of the
6747 /// block above/left of this column/row -- spec
6748 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
6749 above_filter: Vec<[u8; 2]>,
6750 left_filter: Vec<[u8; 2]>,
6751 mi_cols: usize,
6752 mi_rows: usize,
6753 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
6754 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
6755 /// 7.15) never filters an 8x8 luma block whose covering coded block read
6756 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
6757 /// grain [`Self::record_mi`] already writes at), read back at 8x8
6758 /// granularity by [`apply_cdef`] since `skip` is constant across every
6759 /// mi cell one coded block covers.
6760 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
6761 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
6762 /// the `skip` bit at this mi cell during this frame. A fresh
6763 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
6764 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
6765 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
6766 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
6767 /// unobservable from the pixels alone. Counted by
6768 /// [`cdef_unwritten_skip_units`].
6769 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
6770 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
6771 /// which re-enables the loop filter at a prediction boundary between two
6772 /// skipped inter blocks (lane-mergefix r4). Written by
6773 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
6774 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
6775 /// that cell -- the other half of `pu_edge`: libaom tests the edge
6776 /// coordinate against the block's size in the FILTERED plane's own
6777 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
6778 blk_grid: Vec<BlkCell>,
6779 skip_grid_cols_mi: usize,
6780 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
6781 /// never splits a coded block's transform below its own size (round 2:
6782 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
6783 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
6784 /// edge-length lookup (`apply_deblock`).
6785 tx_grid: Vec<u8>,
6786 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
6787 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
6788 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
6789 tx_h_grid: Vec<u8>,
6790 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
6791 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
6792 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
6793 /// does NOT follow luma's `tx_depth` split, so deriving it as
6794 /// `tx_grid / 2` invented chroma transform edges the deblocker then
6795 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
6796 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
6797 /// every caller routes through.
6798 uv_tx_grid: Vec<u8>,
6799 uv_tx_h_grid: Vec<u8>,
6800 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
6801 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
6802 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
6803 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
6804 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
6805 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
6806 /// reference onto `LAST_FRAME`'s own delta).
6807 ref_grid: Vec<i8>,
6808 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
6809 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
6810 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
6811 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
6812 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
6813 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
6814 /// to know which mode produced the value.
6815 delta_lf_grid: Vec<[i8; 4]>,
6816 /// The block above/left's own palette-Y size (0 = not a palette block)
6817 /// and its base colours -- `av1_get_palette_mode_ctx`/
6818 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
6819 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
6820 above_palette_size: Vec<u8>,
6821 left_palette_size: Vec<u8>,
6822 above_palette_colors: Vec<[u16; 8]>,
6823 left_palette_colors: Vec<[u16; 8]>,
6824 /// As the four fields above, for the neighbour's own chroma (U-channel
6825 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
6826 /// palette size/colours (lane-palette2 r1).
6827 above_palette_uv_size: Vec<u8>,
6828 left_palette_uv_size: Vec<u8>,
6829 above_palette_uv_colors: Vec<[u16; 8]>,
6830 left_palette_uv_colors: Vec<[u16; 8]>,
6831 /// This tile's own top-left corner, in 4x4 mode-info units (spec
6832 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
6833 /// neighbour" check compares against this instead of literal `0`, since a
6834 /// block at the tile's own top/left edge has no usable neighbour even
6835 /// though a decoded block sits there in the picture (spec `decode_tile`'s
6836 /// per-tile `clear_above_context`/`left_available`/`up_available`).
6837 /// `0` for a single-tile frame, matching every existing caller exactly.
6838 tile_row0_mi: usize,
6839 tile_col0_mi: usize,
6840}
6841
6842#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6843impl Neighbours {
6844 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
6845 /// true (unpadded) size in 4x4 mode-info units.
6846 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
6847 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
6848 // neighbour state over the whole 64-row extent, past the frame's last
6849 // mi row (mi_rows 198, block rows 192..208). libaom's own context
6850 // buffers are superblock-aligned for exactly that reason
6851 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
6852 // side arrays to a superblock multiple and leave those cells unread --
6853 // every availability check uses the true `mi_rows`/`mi_cols` below.
6854 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
6855 let (cols, rows) = (
6856 cols.next_multiple_of(sb_sub),
6857 rows.next_multiple_of(sb_sub),
6858 );
6859 Self {
6860 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
6861 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
6862 above_mode: vec![DC_PRED; cols],
6863 left_mode: vec![DC_PRED; rows],
6864 above_uv_mode: vec![DC_PRED; cols],
6865 left_uv_mode: vec![DC_PRED; rows],
6866 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
6867 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
6868 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
6869 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
6870 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
6871 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
6872 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
6873 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
6874 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
6875 uv_grid_cols: cols * (SUB / MI),
6876 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
6877 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
6878 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
6879 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
6880 // 16x16 block beside it, which a SUB-grid slot cannot name
6881 // (class context-read-from-one-cell).
6882 above_skip: vec![false; cols * (SUB / MI)],
6883 left_skip: vec![false; rows * (SUB / MI)],
6884 above_skip_mode: vec![false; cols * (SUB / MI)],
6885 left_skip_mode: vec![false; rows * (SUB / MI)],
6886 above_inter: vec![false; cols * (SUB / MI)],
6887 left_inter: vec![false; rows * (SUB / MI)],
6888 above_ref: vec![-1; cols * (SUB / MI)],
6889 left_ref: vec![-1; rows * (SUB / MI)],
6890 above_ref1: vec![None; cols * (SUB / MI)],
6891 left_ref1: vec![None; rows * (SUB / MI)],
6892 above_comp_group_idx: vec![0; cols * (SUB / MI)],
6893 left_comp_group_idx: vec![0; rows * (SUB / MI)],
6894 above_compound_idx: vec![0; cols * (SUB / MI)],
6895 left_compound_idx: vec![0; rows * (SUB / MI)],
6896 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
6897 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
6898 mi_cols,
6899 mi_rows,
6900 blk_grid: vec![
6901 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
6902 cols * (SUB / MI) * rows * (SUB / MI)
6903 ],
6904 skip_grid_cols_mi: cols * (SUB / MI),
6905 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6906 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6907 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6908 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6909 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
6910 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
6911 above_palette_size: vec![0; cols * (SUB / MI)],
6912 left_palette_size: vec![0; rows * (SUB / MI)],
6913 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6914 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
6915 above_palette_uv_size: vec![0; cols * (SUB / MI)],
6916 left_palette_uv_size: vec![0; rows * (SUB / MI)],
6917 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6918 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
6919 tile_row0_mi: 0,
6920 tile_col0_mi: 0,
6921 }
6922 }
6923
6924 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
6925 /// tile's own column span (`col1_mi` exclusive), plus recording
6926 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
6927 /// availability check below. Left context resets every superblock row
6928 /// regardless of tile ([`Self::start_row`], already called once per SB
6929 /// row by every caller) so it needs no tile-specific reset here.
6930 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
6931 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
6932 // are tile-relative, same as every other neighbour lookup here.
6933 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
6934 self.tile_row0_mi = row0_mi;
6935 self.tile_col0_mi = col0_mi;
6936 let end = col1_mi.min(self.above.len());
6937 for i in col0_mi.min(end)..end {
6938 self.above[i] = Default::default();
6939 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
6940 }
6941 let (sc0, sc1) = (
6942 col0_mi / (SUB / MI),
6943 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
6944 );
6945 for i in sc0.min(sc1)..sc1 {
6946 self.above_mode[i] = DC_PRED;
6947 self.above_side[i] = NO_NEIGHBOUR_SIDE;
6948 }
6949 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
6950 // the tile's own mi column span directly.
6951 let mend = col1_mi.min(self.above_skip.len());
6952 for i in col0_mi.min(mend)..mend {
6953 self.above_skip[i] = false;
6954 self.above_skip_mode[i] = false;
6955 self.above_inter[i] = false;
6956 self.above_ref[i] = -1;
6957 self.above_ref1[i] = None;
6958 self.above_comp_group_idx[i] = 0;
6959 self.above_compound_idx[i] = 0;
6960 self.above_filter[i] = [3u8; 2];
6961 }
6962 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
6963 // stale `(row, mode)` from the tile to the LEFT names an mi row this
6964 // tile's first block would read as its own above neighbour.
6965 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
6966 for i in col0_mi.min(mcol_end)..mcol_end {
6967 self.sub8_mode_col[i] = (u16::MAX, 0);
6968 self.uv_mode_col[i] = (u16::MAX, 0);
6969 }
6970 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
6971 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
6972 // not zero) -- without it a second tile column reads the first one's
6973 // resolved transform sizes as its own above context.
6974 let tend = col1_mi.min(self.above_txfm.len());
6975 for i in col0_mi.min(tend)..tend {
6976 self.above_txfm[i] = TXFM_CTX_INIT;
6977 }
6978 }
6979
6980 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
6981 /// for a non-palette block, clearing any stale neighbour state) into every
6982 /// [`SUB`]-grid cell it covers on both the above and left edges --
6983 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
6984 /// call sites are all square blocks).
6985 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
6986 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
6987 }
6988
6989 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
6990 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
6991 /// [`Self::record`]): a true rect strip's above/left neighbour spans
6992 /// differ.
6993 fn record_palette_y_rect(
6994 &mut self,
6995 mi: (usize, usize),
6996 w: usize,
6997 h: usize,
6998 size: usize,
6999 colors: [u16; 8],
7000 ) {
7001 let (r, c) = mi;
7002 if crate::envflags::env_flag!("EC_PALPUB") {
7003 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7004 }
7005 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7006 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7007 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7008 // old SUB grid let a 16x8 strip pair share one slot, so the second
7009 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7010 // cache came out one entry short (class [[context-read-from-one-cell]]).
7011 for cell in 0..(w / MI).max(1) {
7012 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7013 *e = size as u8;
7014 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7015 // neighbour's colours only where its palette size > 0, so a
7016 // non-palette block need not stamp 16 bytes of zeroes here.
7017 if size > 0 {
7018 self.above_palette_colors[c + cell] = colors;
7019 }
7020 }
7021 }
7022 for cell in 0..(h / MI).max(1) {
7023 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7024 *e = size as u8;
7025 if size > 0 {
7026 self.left_palette_colors[r + cell] = colors;
7027 }
7028 }
7029 }
7030 }
7031
7032 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7033 /// neighbours that are themselves a palette-Y block, plus
7034 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7035 /// cache (pred_common.c:73).
7036 ///
7037 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7038 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7039 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7040 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7041 /// the ctx too made every superblock in the frame's second SB row read
7042 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7043 /// palette block decoded as "no palette" and the tile desynced from
7044 /// there (class [[cdf-row-held-constant]]).
7045 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7046 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7047 }
7048
7049 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7050 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7051 /// drops the above neighbour on a 64-px superblock boundary
7052 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7053 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7054 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7055 /// every strip in an SB's top cell row, which libaom does not do.
7056 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7057 let (r, c) = mi;
7058 let above_ok = r % 16 != 0;
7059 // `xd->above_mbmi` exists for every row but the tile's own first.
7060 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7061 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7062 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7063 } else {
7064 (0, [0u16; 8])
7065 };
7066 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7067 // is NULL whenever the block sits at its TILE's own left column
7068 // (`left_available`), not the frame's -- without this guard a second
7069 // tile column reads the previous tile's palette colours into its cache
7070 // and its `palette_y_mode` ctx.
7071 let left_ok = c > self.tile_col0_mi;
7072 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7073 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7074 } else {
7075 (0, [0u16; 8])
7076 };
7077 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7078 let mut cache = Vec::with_capacity(16);
7079 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7080 if cache.last() != Some(&v) {
7081 cache.push(v);
7082 }
7083 };
7084 let (mut ai, mut li) = (0usize, 0usize);
7085 while ai < above_n && li < left_n {
7086 let (va, vl) = (above_colors[ai], left_colors[li]);
7087 if vl < va {
7088 push_dedup(&mut cache, vl);
7089 li += 1;
7090 } else {
7091 push_dedup(&mut cache, va);
7092 ai += 1;
7093 if vl == va {
7094 li += 1;
7095 }
7096 }
7097 }
7098 while ai < above_n {
7099 push_dedup(&mut cache, above_colors[ai]);
7100 ai += 1;
7101 }
7102 while li < left_n {
7103 push_dedup(&mut cache, left_colors[li]);
7104 li += 1;
7105 }
7106 (ctx, cache)
7107 }
7108
7109 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7110 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7111 /// same way (lane-palette2 r1).
7112 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7113 self.record_palette_uv_rect(
7114 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7115 side,
7116 side,
7117 size,
7118 colors,
7119 );
7120 }
7121
7122 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7123 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7124 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7125 /// luma resolution regardless of which plane the recorded state is for).
7126 fn record_palette_uv_rect(
7127 &mut self,
7128 mi: (usize, usize),
7129 w: usize,
7130 h: usize,
7131 size: usize,
7132 colors: [u16; 8],
7133 ) {
7134 let (r, c) = mi;
7135 // mi granularity, see [`Self::record_palette_y_rect`].
7136 for cell in 0..(w / MI).max(1) {
7137 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7138 *e = size as u8;
7139 if size > 0 {
7140 self.above_palette_uv_colors[c + cell] = colors;
7141 }
7142 }
7143 }
7144 for cell in 0..(h / MI).max(1) {
7145 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7146 *e = size as u8;
7147 if size > 0 {
7148 self.left_palette_uv_colors[r + cell] = colors;
7149 }
7150 }
7151 }
7152 }
7153
7154 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7155 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7156 /// no neighbour lookup at all (it is this block's own just-decided Y
7157 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7158 /// so only the cache is wanted here.
7159 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7160 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7161 }
7162
7163 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7164 /// [`Self::palette_ctx_and_cache_mi`].
7165 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7166 let (r, c) = mi;
7167 let above_ok = r % 16 != 0;
7168 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7169 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7170 } else {
7171 (0, [0u16; 8])
7172 };
7173 // Same tile-relative left availability as the luma cache above.
7174 let left_ok = c > self.tile_col0_mi;
7175 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7176 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7177 } else {
7178 (0, [0u16; 8])
7179 };
7180 let mut cache = Vec::with_capacity(16);
7181 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7182 if cache.last() != Some(&v) {
7183 cache.push(v);
7184 }
7185 };
7186 let (mut ai, mut li) = (0usize, 0usize);
7187 while ai < above_n && li < left_n {
7188 let (va, vl) = (above_colors[ai], left_colors[li]);
7189 if vl < va {
7190 push_dedup(&mut cache, vl);
7191 li += 1;
7192 } else {
7193 push_dedup(&mut cache, va);
7194 ai += 1;
7195 if vl == va {
7196 li += 1;
7197 }
7198 }
7199 }
7200 while ai < above_n {
7201 push_dedup(&mut cache, above_colors[ai]);
7202 ai += 1;
7203 }
7204 while li < left_n {
7205 push_dedup(&mut cache, left_colors[li]);
7206 li += 1;
7207 }
7208 cache
7209 }
7210
7211 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7212 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7213 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7214 /// units as [`Self::fill_skip_grid`].
7215 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7216 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7217 }
7218
7219 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7220 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7221 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7222 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
7223 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
7224 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
7225 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
7226 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
7227 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
7228 /// block's published transform extent to its own size is exactly that
7229 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
7230 /// that needs it is the 128 root, whose chroma extent (64) is the one
7231 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
7232 /// never suppressed (libaom's `is_inter_block` term), so this is called
7233 /// only from the skipped-inter branch.
7234 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
7235 let (mi_r, mi_c) = at_mi;
7236 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
7237 for rr in 0..h_mi {
7238 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7239 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
7240 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
7241 }
7242 }
7243
7244 fn fill_lf_grid_rect(
7245 &mut self,
7246 at_mi: (usize, usize),
7247 w_mi: usize,
7248 h_mi: usize,
7249 tx_px: u8,
7250 tx_h_px: u8,
7251 ref_frame: i8, fctx: &crate::decode::FrameCtx,
7252 ) {
7253 let (mi_r, mi_c) = at_mi;
7254 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
7255 // half its luma one (min 4 px, the smallest transform), capped at
7256 // TX_32X32 -- independent of this block's luma `tx_depth`.
7257 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
7258 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
7259 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7260 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}");
7261 }
7262 let cur = fctx.current_delta_lf.with(|c| c.get());
7263 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
7264 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
7265 } else {
7266 [cur[0].clamp(-63, 63) as i8; 4]
7267 };
7268 for rr in 0..h_mi {
7269 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7270 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7271 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7272 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
7273 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
7274 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
7275 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
7276 }
7277 }
7278
7279 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
7280 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
7281 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
7282 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
7283 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
7284 /// dims from the LEAF span and so invented chroma transform edges the
7285 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
7286 /// are already correct from the block's own fill over the same span.
7287 fn fill_lf_grid_leaf_luma(
7288 &mut self,
7289 at_mi: (usize, usize),
7290 w_mi: usize,
7291 h_mi: usize,
7292 tx_px: u8,
7293 tx_h_px: u8,
7294 ) {
7295 let (mi_r, mi_c) = at_mi;
7296 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7297 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}");
7298 }
7299 for rr in 0..h_mi {
7300 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7301 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7302 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7303 }
7304 }
7305
7306 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
7307 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
7308 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
7309 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
7310 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
7311 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
7312 }
7313
7314 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
7315 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
7316 let (mi_r, mi_c) = at_mi;
7317 if skip && w_mi != h_mi {
7318 hit!(RECT_SKIP_BAND_HITS);
7319 }
7320 for rr in 0..h_mi {
7321 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7322 fill_span(
7323 &mut self.blk_grid,
7324 start,
7325 w_mi,
7326 BlkCell {
7327 skip,
7328 written: true,
7329 org: [mi_r as u16, mi_c as u16],
7330 dim: [w_mi as u8, h_mi as u8],
7331 },
7332 );
7333 }
7334 }
7335
7336 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
7337 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
7338 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
7339 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
7340 /// straddle the region with a mix of skip/non-skip blocks).
7341 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
7342 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
7343 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
7344 /// filtered edge's two sides are each exactly one coded block wide.
7345 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
7346 self.blk_grid
7347 .get(mi_r * self.skip_grid_cols_mi + mi_c)
7348 .is_some_and(|c| c.skip)
7349 }
7350
7351 /// The `skip_txfm` context of a block whose top-left mi cell is
7352 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
7353 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
7354 /// with an absent neighbour contributing 0. The mi grid is per tile, so
7355 /// row/column 0 is a tile edge and has no neighbour on that axis.
7356 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
7357 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
7358 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
7359 }
7360
7361 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
7362 (0..2).all(|rr| {
7363 (0..2).all(|cc| {
7364 self.blk_grid
7365 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
7366 .is_some_and(|c| c.skip)
7367 })
7368 })
7369 }
7370
7371 fn start_row(&mut self) {
7372 self.left.iter_mut().for_each(|l| *l = Default::default());
7373 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
7374 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
7375 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
7376 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
7377 self.left_skip.iter_mut().for_each(|s| *s = false);
7378 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
7379 self.left_inter.iter_mut().for_each(|i| *i = false);
7380 self.left_ref.iter_mut().for_each(|r| *r = -1);
7381 self.left_ref1.iter_mut().for_each(|r| *r = None);
7382 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
7383 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
7384 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
7385 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
7386 // context (a tile/SB-row boundary has no left neighbour).
7387 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7388 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7389 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
7390 // are per-mi maps like every other one here, so they reset with the
7391 // row too -- the left guard above is what actually stops a cross-tile
7392 // read, this keeps a stale colour out of the arrays at all.
7393 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
7394 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7395 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
7396 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7397 // lane-mergefix r2: `av1_zero_left_context` memsets
7398 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
7399 // every superblock row of every tile -- the var-tx left context does
7400 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
7401 // previous tile column's last block otherwise).
7402 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
7403 }
7404
7405 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
7406 /// block that reads it as a neighbour -- [`crate::tile`]'s
7407 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
7408 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
7409 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
7410 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
7411 /// the real value, not just `is_inter`).
7412 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7413 fn record_inter(
7414 &mut self,
7415 at: (usize, usize),
7416 side: usize,
7417 skip: bool,
7418 is_inter: bool,
7419 ref_frame: i8,
7420 filter: [u8; 2],
7421 skip_mode: bool,
7422 ) {
7423 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
7424 }
7425
7426 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
7427 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
7428 /// r1: a true rectangular strip's above-context span (its own width) and
7429 /// left-context span (its own height) differ, unlike every caller before
7430 /// this round (class neighbour-votes-all-its-fields).
7431 #[allow(clippy::too_many_arguments)]
7432 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7433 fn record_inter_rect(
7434 &mut self,
7435 at: (usize, usize),
7436 w_sub: usize,
7437 h_sub: usize,
7438 skip: bool,
7439 is_inter: bool,
7440 ref_frame: i8,
7441 filter: [u8; 2],
7442 skip_mode: bool,
7443 ) {
7444 let (r, c) = at;
7445 self.record_inter_rect_mi(
7446 (r * (SUB / MI), c * (SUB / MI)),
7447 w_sub / MI,
7448 h_sub / MI,
7449 skip,
7450 is_inter,
7451 ref_frame,
7452 filter,
7453 skip_mode,
7454 );
7455 }
7456
7457 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
7458 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
7459 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
7460 /// routes through the wrapper above.
7461 #[allow(clippy::too_many_arguments)]
7462 fn record_inter_rect_mi(
7463 &mut self,
7464 at_mi: (usize, usize),
7465 w_mi: usize,
7466 h_mi: usize,
7467 skip: bool,
7468 is_inter: bool,
7469 ref_frame: i8,
7470 filter: [u8; 2],
7471 skip_mode: bool,
7472 ) {
7473 let (r, c) = at_mi;
7474 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
7475 // writes for a whole block class): an INTER block left the luma mode
7476 // map untouched, so a later intra block's `get_intra_edge_filter_type`
7477 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
7478 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
7479 // block in that pixel row -- the directional edge filter then ran at
7480 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
7481 // which for an inter block is an INTER mode (>= NEARESTMV) and is
7482 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
7483 // already stamped it).
7484 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
7485 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
7486 // uv map must read DC_PRED over an inter block's cells too.
7487 if is_inter {
7488 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7489 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7490 }
7491 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
7492 self.above_skip[c..c + w_mi].fill(skip);
7493 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
7494 self.above_inter[c..c + w_mi].fill(is_inter);
7495 self.above_ref[c..c + w_mi].fill(ref_frame);
7496 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
7497 // this with the block's real second reference for a compound block,
7498 // called right after this one (lane-publish2 audit).
7499 self.above_ref1[c..c + w_mi].fill(None);
7500 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
7501 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
7502 // as `3`/`1` even though this block has no second reference.
7503 // `record_compound_ctx` overwrites this with the real bit for an
7504 // actual compound block's cells, called right after this one.
7505 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
7506 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
7507 self.above_filter[c..c + w_mi].fill(filter);
7508 self.left_skip[r..r + h_mi].fill(skip);
7509 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
7510 self.left_inter[r..r + h_mi].fill(is_inter);
7511 self.left_ref[r..r + h_mi].fill(ref_frame);
7512 self.left_ref1[r..r + h_mi].fill(None);
7513 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
7514 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
7515 self.left_filter[r..r + h_mi].fill(filter);
7516 }
7517
7518 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
7519 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
7520 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
7521 /// `get_comp_index_context`) -- called right after `record_inter` for
7522 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
7523 /// stamps `above_ref1`/`left_ref1` with the block's real second
7524 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
7525 /// this is the one caller that actually knows it) -- so the next block's
7526 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
7527 /// neighbour instead of `record_inter`'s single-ref default.
7528 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7529 fn record_compound_ctx(
7530 &mut self,
7531 at: (usize, usize),
7532 side: usize,
7533 ref1: i8,
7534 comp_group_idx: u8,
7535 compound_idx: u8,
7536 ) {
7537 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
7538 }
7539
7540 /// [`Self::record_compound_ctx`] with independent above/left extents,
7541 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
7542 #[allow(clippy::too_many_arguments)]
7543 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7544 fn record_compound_ctx_rect(
7545 &mut self,
7546 at: (usize, usize),
7547 w_sub: usize,
7548 h_sub: usize,
7549 ref1: i8,
7550 comp_group_idx: u8,
7551 compound_idx: u8,
7552 ) {
7553 let (r, c) = at;
7554 self.record_compound_ctx_rect_mi(
7555 (r * (SUB / MI), c * (SUB / MI)),
7556 w_sub / MI,
7557 h_sub / MI,
7558 ref1,
7559 comp_group_idx,
7560 compound_idx,
7561 );
7562 }
7563
7564 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
7565 /// [`Self::record_inter_rect_mi`]).
7566 fn record_compound_ctx_rect_mi(
7567 &mut self,
7568 at_mi: (usize, usize),
7569 w_mi: usize,
7570 h_mi: usize,
7571 ref1: i8,
7572 comp_group_idx: u8,
7573 compound_idx: u8,
7574 ) {
7575 let (r, c) = at_mi;
7576 for cell in 0..w_mi {
7577 self.above_ref1[c + cell] = Some(ref1);
7578 self.above_comp_group_idx[c + cell] = comp_group_idx;
7579 self.above_compound_idx[c + cell] = compound_idx;
7580 }
7581 for cell in 0..h_mi {
7582 self.left_ref1[r + cell] = Some(ref1);
7583 self.left_comp_group_idx[r + cell] = comp_group_idx;
7584 self.left_compound_idx[r + cell] = compound_idx;
7585 }
7586 }
7587
7588 /// The context of a block's partition symbol: delegates to the mi-precise
7589 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
7590 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
7591 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
7592 /// only touches the finer mi arrays -- leaves them stale for the *next*
7593 /// sibling's own partition symbol.
7594 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
7595 let (r, c) = at;
7596 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
7597 }
7598
7599 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
7600 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
7601 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
7602 /// than the enclosing 16x16 slot's stale, shared state.
7603 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
7604 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
7605 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
7606 }
7607
7608 /// The gathered coded/DC-sign state of the blocks above and to the left
7609 /// of a block `side` samples across, per plane.
7610 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7611 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
7612 }
7613
7614 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
7615 /// units, for the same reason [`Self::record_mi`] does.
7616 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7617 let side_mi = side / MI;
7618 // One pass over the cells accumulating all three planes, not one pass
7619 // per plane: the three planes of a cell live in the same
7620 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
7621 // cache lines three times (lane-publish).
7622 let mut out = [(false, false, 0i32); 3];
7623 for cell in 0..side_mi {
7624 let above = &self.above[mi_c + cell];
7625 let left = &self.left[mi_r + cell];
7626 for (plane, o) in out.iter_mut().enumerate() {
7627 o.0 |= above[plane].level != 0;
7628 o.1 |= left[plane].level != 0;
7629 o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc);
7630 }
7631 }
7632 out
7633 }
7634
7635 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
7636 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
7637 /// extent pattern for a true rectangular strip's own coefficient context.
7638 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7639 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
7640 }
7641
7642 /// [`Self::around_rect`] taking the block's position directly in 4x4
7643 /// mode-info units, mirroring [`Self::around_mi`].
7644 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7645 let (w_mi, h_mi) = (w / MI, h / MI);
7646 // [`Self::around_mi`]'s single pass, with the two extents split.
7647 let mut out = [(false, false, 0i32); 3];
7648 for cell in 0..w_mi {
7649 let above = &self.above[mi_c + cell];
7650 for (plane, o) in out.iter_mut().enumerate() {
7651 o.0 |= above[plane].level != 0;
7652 o.2 += dc_vote(above[plane].dc);
7653 }
7654 }
7655 for cell in 0..h_mi {
7656 let left = &self.left[mi_r + cell];
7657 for (plane, o) in out.iter_mut().enumerate() {
7658 o.1 |= left[plane].level != 0;
7659 o.2 += dc_vote(left[plane].dc);
7660 }
7661 }
7662 if crate::envflags::env_flag!("EC_DCDUMP") {
7663 for (plane, o) in out.iter().enumerate() {
7664 let vote = o.2;
7665 let ab: Vec<String> = (0..w_mi)
7666 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
7667 .collect();
7668 let lf: Vec<String> = (0..h_mi)
7669 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
7670 .collect();
7671 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
7672 }
7673 }
7674 out
7675 }
7676
7677 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
7678 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
7679 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
7680 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
7681 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
7682 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
7683 /// is always 0, spec's `plane_bsize == tx_size` branch).
7684 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
7685 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
7686 }
7687
7688 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
7689 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
7690 /// context over `tx_size_wide` and the left one over `tx_size_high`.
7691 fn luma_skip_ctx_rect(
7692 &self,
7693 (mi_r, mi_c): (usize, usize),
7694 w_mi: usize,
7695 h_mi: usize,
7696 ) -> usize {
7697 let side_mi = w_mi;
7698 let mut top = 0u8;
7699 let mut left = 0u8;
7700 for cell in 0..w_mi {
7701 top |= self.above[mi_c + cell][0].level;
7702 }
7703 for cell in 0..h_mi {
7704 left |= self.left[mi_r + cell][0].level;
7705 }
7706 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
7707 if crate::envflags::env_flag!("EC_ECDUMP") {
7708 let ab: Vec<String> =
7709 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
7710 let lf: Vec<String> =
7711 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
7712 eprintln!(
7713 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
7714 ab.join(","), lf.join(",")
7715 );
7716 }
7717 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7718 eprintln!(
7719 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
7720 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
7721 );
7722 }
7723 ctx
7724 }
7725
7726 /// Writes one coded block into every cell it covers, on both grids: the
7727 /// mode/side arrays up to `side`'s own width, and the coefficient-context
7728 /// arrays up to the true frame edge — the units past it are left at their
7729 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
7730 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
7731 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
7732 /// not from this block's own side).
7733 fn record(
7734 &mut self,
7735 at: (usize, usize),
7736 side: usize,
7737 mode: usize,
7738 uv_mode: usize,
7739 grids: &[&[i32]; 3],
7740 ) {
7741 self.record_rect(at, side, side, mode, uv_mode, grids);
7742 }
7743
7744 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
7745 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
7746 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
7747 /// spec's per-edge partition-context rule, so a true rectangular block
7748 /// naturally wants two different values here rather than one.
7749 /// Writes this block's luma `mode` into the mi-granular
7750 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
7751 /// position a *later* neighbour would read it from: the block's LAST mi
7752 /// row for every column it spans (what the block below reads via
7753 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
7754 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
7755 /// read these back, and only when the recorded position is exactly their
7756 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
7757 fn record_mode_mi(
7758 &mut self,
7759 mi_r: usize,
7760 mi_c: usize,
7761 mi_w: usize,
7762 mi_h: usize,
7763 mode: usize,
7764 ) {
7765 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
7766 let mode = mode as u8;
7767 for cell in 0..mi_w {
7768 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
7769 *slot = (last_r, mode);
7770 }
7771 }
7772 for cell in 0..mi_h {
7773 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
7774 *slot = (last_c, mode);
7775 }
7776 }
7777 }
7778
7779 /// The mi-exact above/left neighbour luma mode for a block whose top-left
7780 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
7781 /// mi position (then the coarse [`SUB`]-grid slot is right by
7782 /// construction). See [`Self::record_mode_mi`].
7783 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7784 match self.sub8_mode_col.get(mi_c) {
7785 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
7786 _ => None,
7787 }
7788 }
7789
7790 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7791 match self.sub8_mode_row.get(mi_r) {
7792 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
7793 _ => None,
7794 }
7795 }
7796
7797 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
7798 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
7799 fn record_uv_mode_mi(
7800 &mut self,
7801 mi_r: usize,
7802 mi_c: usize,
7803 mi_w: usize,
7804 mi_h: usize,
7805 uv_mode: usize,
7806 ) {
7807 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
7808 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
7809 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
7810 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
7811 // covers, so the chroma neighbour read below is a plain grid read.
7812 let stride = self.uv_grid_cols;
7813 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
7814 for row in mi_r..=last_r {
7815 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
7816 }
7817 }
7818
7819 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
7820 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
7821 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
7822 /// block has recorded the exact neighbouring mi.
7823 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
7824 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
7825 // REFERENCE block, not off the mi that carries the chroma syntax.
7826 // `set_mi_row_col` (`blockd.h`) takes
7827 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
7828 // only then `chroma_above_mbmi = base_mi[-stride]` /
7829 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
7830 // the ODD mi, so without the snap we looked one mi row/column too far
7831 // down/right -- the mi-exact slot never matched and the coarse
7832 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
7833 // 8x4 at (688, 100) = mi (51, 344): libaom's
7834 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
7835 // `UV_SMOOTH_PRED`), ours was 0, which flips
7836 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
7837 // false for type 1, TRUE for type 0) and upsampled an edge libaom
7838 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
7839 // predicting from it (class `context-read-from-one-cell`).
7840 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
7841 }
7842
7843 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
7844 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
7845 /// counter wants this: it measures how often the snap CHANGES the answer,
7846 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
7847 /// decode path uses the snapping form.
7848 fn smooth_uv_neighbour_unsnapped(
7849 &self,
7850 mi_r: usize,
7851 mi_c: usize,
7852 r: usize,
7853 c: usize,
7854 ) -> bool {
7855 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
7856 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
7857 // array that `start_tile` does not clear, so a block on a tile's first
7858 // mi row used to read the uv_mode of the block above it in the tile
7859 // ABOVE and filter its chroma edge at that neighbour's strength
7860 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
7861 // at chroma (120, 32), the top-right tile's first block).
7862 let have_above = mi_r > self.tile_row0_mi;
7863 let have_left = mi_c > self.tile_col0_mi;
7864 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
7865 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
7866 {
7867 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
7868 }
7869 // The mi grid is libaom's own read; the two maps below stay as the
7870 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
7871 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
7872 (col < self.uv_grid_cols)
7873 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
7874 .flatten()
7875 .filter(|&m| m != u8::MAX)
7876 .map(usize::from)
7877 };
7878 let above = match self.uv_mode_col.get(mi_c) {
7879 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
7880 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
7881 _ if have_above => self.above_uv_mode[c],
7882 _ => DC_PRED,
7883 };
7884 let left = match self.uv_mode_row.get(mi_r) {
7885 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
7886 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
7887 _ if have_left => self.left_uv_mode[r],
7888 _ => DC_PRED,
7889 };
7890 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
7891 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
7892 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
7893 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
7894 }) {
7895 hit!(UV_MODE_GRID_OVERRIDE_HITS);
7896 }
7897 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
7898 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
7899 // have been filtered at the wrong strength by the coarse map alone.
7900 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
7901 hit!(UV_MODE_MI_OVERRIDE_HITS);
7902 }
7903 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
7904 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
7905 {
7906 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
7907 }
7908 is_smooth_mode(above) || is_smooth_mode(left)
7909 }
7910
7911 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
7912 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
7913 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
7914 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
7915 /// holding an OLDER, larger block's mode -- it only ever recorded into the
7916 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
7917 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
7918 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
7919 /// a different CDF for the same mode value).
7920 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
7921 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
7922 /// only when `up_available` and `left_mbmi` only when `left_available`;
7923 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
7924 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
7925 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
7926 /// strip's mode as its "left neighbour" (measured on the band fixture at
7927 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
7928 fn modes_above_left_mi(
7929 &self,
7930 mi_r: usize,
7931 mi_c: usize,
7932 fallback: (usize, usize),
7933 ) -> (usize, usize) {
7934 let above = if mi_r > self.tile_row0_mi {
7935 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
7936 } else {
7937 DC_PRED
7938 };
7939 let left = if mi_c > self.tile_col0_mi {
7940 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
7941 } else {
7942 DC_PRED
7943 };
7944 (above, left)
7945 }
7946
7947 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
7948 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
7949 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
7950 /// per superblock row and never per tile, so the first block column of
7951 /// tile 2..N read the previous tile's mode as its left neighbour, and the
7952 /// above band survives across a tile ROW boundary the same way lane-mtfix's
7953 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
7954 /// `up_available`/`left_available` and uses DC_PRED otherwise
7955 /// ([`Self::modes_above_left_mi`]).
7956 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
7957 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7958 let (above, left) =
7959 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
7960 if above != self.above_mode[c] || left != self.left_mode[r] {
7961 hit!(MODE_MI_OVERRIDE_HITS);
7962 }
7963 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
7964 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
7965 {
7966 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
7967 }
7968 // A neighbour the coarse band offered where the tile edge makes it
7969 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
7970 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
7971 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
7972 {
7973 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
7974 }
7975 (above, left)
7976 }
7977
7978 fn record_rect(
7979 &mut self,
7980 at: (usize, usize),
7981 w: usize,
7982 h: usize,
7983 mode: usize,
7984 uv_mode: usize,
7985 grids: &[&[i32]; 3],
7986 ) {
7987 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
7988 }
7989
7990 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
7991 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
7992 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
7993 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
7994 /// the [`SUB`]-unit path does).
7995 fn record_rect_mi(
7996 &mut self,
7997 at_mi: (usize, usize),
7998 w: usize,
7999 h: usize,
8000 mode: usize,
8001 uv_mode: usize,
8002 grids: &[&[i32]; 3],
8003 ) {
8004 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8005 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8006 // last 16-px column/row stamps only the cells that exist (libaom's
8007 // arrays are padded past the frame and those cells are never read).
8008 for cell in 0..w / SUB {
8009 if c + cell >= self.above_mode.len() {
8010 break;
8011 }
8012 self.above_mode[c + cell] = mode;
8013 self.above_uv_mode[c + cell] = uv_mode;
8014 self.above_side[c + cell] = w;
8015 }
8016 for cell in 0..h / SUB {
8017 if r + cell >= self.left_mode.len() {
8018 break;
8019 }
8020 self.left_mode[r + cell] = mode;
8021 self.left_uv_mode[r + cell] = uv_mode;
8022 self.left_side[r + cell] = h;
8023 }
8024 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8025 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8026 self.record_mi_rect(at_mi, w, h, grids);
8027 }
8028
8029 /// The coefficient-context half of [`Self::record`], taking the block's
8030 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8031 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8032 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8033 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8034 self.record_mi_rect(at_mi, side, side, grids);
8035 }
8036
8037 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8038 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8039 fn record_mi_rect(
8040 &mut self,
8041 at_mi: (usize, usize),
8042 w: usize,
8043 h: usize,
8044 grids: &[&[i32]; 3],
8045 ) {
8046 let (mi_r, mi_c) = at_mi;
8047 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8048 let (w_mi, h_mi) = (w / MI, h / MI);
8049 if crate::envflags::env_flag!("EC_ECPUB") {
8050 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8051 }
8052 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8053 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8054 // A chroma 4x4 unit straddling the true luma edge is still whole in
8055 // chroma's own halved grid, so libaom rounds the luma bound up to the
8056 // plane's own 4x4 unit before clamping a subsampled plane
8057 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8058 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8059 let bound_h = [
8060 self.mi_rows,
8061 round_up_even(self.mi_rows),
8062 round_up_even(self.mi_rows),
8063 ];
8064 let bound_w = [
8065 self.mi_cols,
8066 round_up_even(self.mi_cols),
8067 round_up_even(self.mi_cols),
8068 ];
8069 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8070 // past the padded side arrays (mi_rows 198, block rows 192..208);
8071 // libaom's own arrays are superblock-sized, so those cells simply
8072 // have no reader -- [`fill_span`] drops them, as the `break` did.
8073 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8074 // predicate is three contiguous runs: all planes, chroma only, none
8075 // (lane-mi).
8076 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8077 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8078 let uv_only = [Neighbour::default(), states[1], states[2]];
8079 fill_span(&mut self.left, mi_r, luma_h, states);
8080 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8081 fill_span(
8082 &mut self.left,
8083 mi_r + chroma_h,
8084 h_mi - chroma_h,
8085 [Neighbour::default(); 3],
8086 );
8087 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8088 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8089 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8090 fill_span(&mut self.above, mi_c, luma_w, states);
8091 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8092 fill_span(
8093 &mut self.above,
8094 mi_c + chroma_w,
8095 w_mi - chroma_w,
8096 [Neighbour::default(); 3],
8097 );
8098 }
8099
8100 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8101 /// inside a coded block whose luma transform is smaller than its own
8102 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8103 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8104 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8105 /// [`Self::record_split_luma`] still writes once for the whole block.
8106 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8107 /// the caller's own [`Self::record_split_luma`] call sets those once,
8108 /// at the block's own true side, not this TU's.
8109 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8110 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8111 }
8112
8113 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8114 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8115 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8116 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8117 /// coefficient-context arrays are indexed by luma mi, the convention
8118 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8119 /// clamp included.
8120 fn record_mi_chroma(
8121 &mut self,
8122 (mi_r, mi_c): (usize, usize),
8123 w_px: usize,
8124 h_px: usize,
8125 plane: usize,
8126 grid: &[i32],
8127 ) {
8128 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8129 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8130 let state = neighbour_state(grid);
8131 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8132 self.left[mi_r + cell][plane] = state;
8133 }
8134 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
8135 self.above[mi_c + cell][plane] = state;
8136 }
8137 }
8138
8139 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
8140 /// r1): the above context spans the unit's width, the left context its
8141 /// height, which for a square unit is the same loop it always was.
8142 fn record_mi_luma_rect(
8143 &mut self,
8144 (mi_r, mi_c): (usize, usize),
8145 w_px: usize,
8146 h_px: usize,
8147 grid: &[i32],
8148 ) {
8149 let state = neighbour_state(grid);
8150 if crate::envflags::env_flag!("EC_ECPUB") {
8151 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
8152 }
8153 for cell in 0..h_px / MI {
8154 if mi_r + cell < self.mi_rows {
8155 self.left[mi_r + cell][0] = state;
8156 }
8157 }
8158 for cell in 0..w_px / MI {
8159 if mi_c + cell < self.mi_cols {
8160 self.above[mi_c + cell][0] = state;
8161 }
8162 }
8163 }
8164
8165 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
8166 /// block whose luma was decoded as several transform units through
8167 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
8168 /// whole-block luma write -- everything [`Self::record`] does except
8169 /// plane 0, which is already correct per-TU by the time this runs.
8170 fn record_split_luma(
8171 &mut self,
8172 at: (usize, usize),
8173 side: usize,
8174 mode: usize,
8175 uv_mode: usize,
8176 chroma_grids: [&[i32]; 2],
8177 ) {
8178 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
8179 }
8180
8181 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
8182 /// extents in pixels (lane-rectsplit r1), the same relationship
8183 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
8184 /// luma transform split into several square units needs exactly this
8185 /// bookkeeping, at its own true rectangular extents.
8186 fn record_split_luma_rect(
8187 &mut self,
8188 at: (usize, usize),
8189 w: usize,
8190 h: usize,
8191 mode: usize,
8192 uv_mode: usize,
8193 chroma_grids: [&[i32]; 2],
8194 ) {
8195 let (r, c) = at;
8196 self.record_split_luma_rect_mi(
8197 (r * (SUB / MI), c * (SUB / MI)),
8198 w,
8199 h,
8200 mode,
8201 uv_mode,
8202 chroma_grids,
8203 );
8204 }
8205
8206 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
8207 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
8208 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
8209 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
8210 /// convention [`decode_block_rect4`] already established for 1:4 strips.
8211 fn record_split_luma_rect_mi(
8212 &mut self,
8213 at_mi: (usize, usize),
8214 w: usize,
8215 h: usize,
8216 mode: usize,
8217 uv_mode: usize,
8218 chroma_grids: [&[i32]; 2],
8219 ) {
8220 let (mi_r, mi_c) = at_mi;
8221 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8222 for cell in 0..w.div_ceil(SUB) {
8223 if c + cell >= self.above_mode.len() {
8224 break;
8225 }
8226 self.above_mode[c + cell] = mode;
8227 self.above_uv_mode[c + cell] = uv_mode;
8228 self.above_side[c + cell] = w;
8229 }
8230 for cell in 0..h.div_ceil(SUB) {
8231 if r + cell >= self.left_mode.len() {
8232 break;
8233 }
8234 self.left_mode[r + cell] = mode;
8235 self.left_uv_mode[r + cell] = uv_mode;
8236 self.left_side[r + cell] = h;
8237 }
8238
8239 let (w_mi, h_mi) = (w / MI, h / MI);
8240 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
8241 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
8242 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8243 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8244 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8245 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8246 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
8247 let plane = plane_idx + 1;
8248 let state = neighbour_state(grid);
8249 for cell in 0..h_mi {
8250 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
8251 self.left[mi_r + cell][plane] = state;
8252 }
8253 }
8254 for cell in 0..w_mi {
8255 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
8256 self.above[mi_c + cell][plane] = state;
8257 }
8258 }
8259 }
8260 }
8261}
8262
8263/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
8264/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
8265/// exactly — including its skip context, which the real key-frame writer
8266/// always writes at a fixed context of zero (it never tracks a neighbour-based
8267/// one for intra blocks; that is the inter-frame writer's rule instead).
8268/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
8269/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
8270/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
8271/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
8272/// plain DC chroma.
8273/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
8274/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
8275/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
8276/// instead (the defect commit 1a89ed9 fixed at the square sites).
8277pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
8278 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
8279 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
8280}
8281
8282/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
8283/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
8284/// bound (spec `filter_intra_mode_info` never reads a symbol there).
8285pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
8286 match side {
8287 4 => Some(0),
8288 8 => Some(1),
8289 16 => Some(2),
8290 32 => Some(3),
8291 _ => None,
8292 }
8293}
8294
8295/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
8296/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
8297/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
8298/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
8299fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8300 match (bw, bh) {
8301 (32, 16) => Some(4),
8302 (16, 32) => Some(5),
8303 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
8304 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
8305 // here dropped that symbol on every DC_PRED strip of that size and
8306 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
8307 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
8308 (16, 8) => Some(6),
8309 (8, 16) => Some(7),
8310 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
8311 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
8312 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
8313 (4, 8) => Some(8),
8314 (8, 4) => Some(9),
8315 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
8316 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
8317 // `use_filter_intra` symbol on those strips although aomenc writes
8318 // one for every DC_PRED block of that shape with
8319 // `--enable-filter-intra=1` (its default), silently desyncing the
8320 // tile (class symbol-consumption-gap).
8321 (32, 8) => Some(10),
8322 (8, 32) => Some(11),
8323 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
8324 // strips), rows 17/16 of `default_filter_intra_cdfs`.
8325 (16, 4) => Some(12),
8326 (4, 16) => Some(13),
8327 _ if bw == bh => filter_intra_size_class(bw),
8328 _ => None,
8329 }
8330}
8331
8332/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
8333/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
8334/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8335/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8336/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8337pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8338 palette_bsize_ctx_wh(side, side)
8339}
8340
8341/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
8342/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
8343/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
8344/// for ANY bsize, not just the square ones a hand-picked table happened to
8345/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
8346/// row breaks the moment its indexing field moves off the diagonal, and a
8347/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
8348/// block dimension is a power of two, so `bw*bh` always is too and
8349/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
8350/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
8351fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
8352 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
8353 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
8354 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
8355 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
8356 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
8357 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
8358 if bw > 64 || bh > 64 || bw * bh < 64 {
8359 return None;
8360 }
8361 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
8362}
8363
8364/// A just-decoded palette-Y block's own size, base colours (only the first
8365/// `size` entries are real), and per-pixel colour-index map (`side*side`,
8366/// row-major, each entry `< size`).
8367struct PaletteY {
8368 size: usize,
8369 colors: [u16; 8],
8370 map: Vec<u8>,
8371}
8372
8373/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
8374/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
8375/// shared between U and V, both co-located after 4:2:0 subsampling) plus
8376/// each plane's own base colours.
8377struct PaletteUv {
8378 size: usize,
8379 u_colors: [u16; 8],
8380 v_colors: [u16; 8],
8381 map: Vec<u8>,
8382}
8383
8384/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
8385/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8386/// `get_unsigned_bits`, which is the same formula): smallest `n` with
8387/// `2^n >= x`, `0` for `x <= 1`.
8388pub(crate) fn ceil_log2(x: u32) -> u32 {
8389 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8390}
8391
8392/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
8393/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
8394fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
8395 let l = ceil_log2(n as u32);
8396 let m = (1usize << l) - n;
8397 let v = dec.literal(l - 1) as usize;
8398 if v < m {
8399 v
8400 } else {
8401 (v << 1) - m + dec.literal(1) as usize
8402 }
8403}
8404
8405/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
8406/// colours (already-known, from the above/left neighbours) with the
8407/// ascending `transmitted` ones (delta-coded off the wire) back into one
8408/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
8409/// value picks the cached copy first, matching the C `<=`.
8410fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
8411 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
8412 let (mut ci, mut ti) = (0, 0);
8413 while ci < cached.len() && ti < transmitted.len() {
8414 if cached[ci] <= transmitted[ti] {
8415 out.push(cached[ci]);
8416 ci += 1;
8417 } else {
8418 out.push(transmitted[ti]);
8419 ti += 1;
8420 }
8421 }
8422 out.extend_from_slice(&cached[ci..]);
8423 out.extend_from_slice(&transmitted[ti..]);
8424 out
8425}
8426
8427/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
8428/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
8429/// each delta's width, the `range` bound and the clamp) is sized by
8430/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
8431/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
8432/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
8433/// the msac range, so a cross-decoder range ladder stays bit-identical
8434/// through the whole miscount -- only the decoded VALUE differs (class
8435/// `compare-range-not-tell`'s blind spot). (this
8436/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
8437/// (one flag bit each, in cache order), then delta-codes the remainder
8438/// (first value raw, each following delta `>= 1` off a shrinking bit width),
8439/// and merges the two ascending lists back together.
8440fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
8441 let mut cached = Vec::with_capacity(n);
8442 for &c in cache {
8443 if cached.len() >= n {
8444 break;
8445 }
8446 if dec.literal(1) == 1 {
8447 cached.push(c);
8448 }
8449 }
8450 let bd = u32::from(bit_depth(fctx));
8451 let max_val = (1i32 << bd) - 1;
8452 let mut colors = [0u16; 8];
8453 let n_cached = cached.len();
8454 if n_cached < n {
8455 let mut transmitted = Vec::with_capacity(n - n_cached);
8456 let first = dec.literal(bd) as u16;
8457 transmitted.push(first);
8458 if n_cached + 1 < n {
8459 let min_bits = bd - 3;
8460 let mut bits = min_bits + dec.literal(2);
8461 let mut range = (1i32 << bd) - i32::from(first) - 1;
8462 for _ in (n_cached + 1)..n {
8463 let delta = dec.literal(bits) as i32 + 1;
8464 let prev = *transmitted.last().unwrap();
8465 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
8466 range -= i32::from(val) - i32::from(prev);
8467 bits = bits.min(ceil_log2(range.max(0) as u32));
8468 transmitted.push(val);
8469 }
8470 }
8471 let merged = merge_colors(&transmitted, &cached);
8472 colors[..n].copy_from_slice(&merged);
8473 } else {
8474 colors[..n].copy_from_slice(&cached[..n]);
8475 }
8476 colors
8477}
8478
8479/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
8480/// `bit_depth` (see [`read_palette_colors_y`]): U reads
8481/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
8482/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
8483/// unbiased by `+1` -- both differences from Y's own reader, matching the C
8484/// side by side). V never uses a cache: a leading bit picks either `n` raw
8485/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
8486/// rather than clamp.
8487fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
8488 let mut cached = Vec::with_capacity(n);
8489 for &c in cache {
8490 if cached.len() >= n {
8491 break;
8492 }
8493 if dec.literal(1) == 1 {
8494 cached.push(c);
8495 }
8496 }
8497 let bd = u32::from(bit_depth(fctx));
8498 let max_val = 1i32 << bd;
8499 let mut u_colors = [0u16; 8];
8500 let n_cached = cached.len();
8501 if n_cached < n {
8502 let mut transmitted = Vec::with_capacity(n - n_cached);
8503 let first = dec.literal(bd) as u16;
8504 transmitted.push(first);
8505 if n_cached + 1 < n {
8506 let min_bits = bd - 3;
8507 let mut bits = min_bits + dec.literal(2);
8508 let mut range = max_val - i32::from(first);
8509 for _ in (n_cached + 1)..n {
8510 let delta = dec.literal(bits) as i32;
8511 let prev = *transmitted.last().unwrap();
8512 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
8513 range -= i32::from(val) - i32::from(prev);
8514 bits = bits.min(ceil_log2(range.max(0) as u32));
8515 transmitted.push(val);
8516 }
8517 }
8518 let merged = merge_colors(&transmitted, &cached);
8519 u_colors[..n].copy_from_slice(&merged);
8520 } else {
8521 u_colors[..n].copy_from_slice(&cached[..n]);
8522 }
8523 let mut v_colors = [0u16; 8];
8524 if dec.literal(1) == 1 {
8525 let min_bits_v = bd - 4;
8526 let bits = min_bits_v + dec.literal(2);
8527 v_colors[0] = dec.literal(bd) as u16;
8528 for i in 1..n {
8529 let mut delta = dec.literal(bits) as i32;
8530 if delta != 0 && dec.literal(1) == 1 {
8531 delta = -delta;
8532 }
8533 let mut val = i32::from(v_colors[i - 1]) + delta;
8534 if val < 0 {
8535 val += max_val;
8536 }
8537 if val >= max_val {
8538 val -= max_val;
8539 }
8540 v_colors[i] = val as u16;
8541 }
8542 } else {
8543 for i in 0..n {
8544 v_colors[i] = dec.literal(bd) as u16;
8545 }
8546 }
8547 (u_colors, v_colors)
8548}
8549
8550/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
8551/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
8552/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
8553const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
8554
8555/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
8556/// map's own per-pixel context and colour-order permutation, from the
8557/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
8558/// selection sort). `map`'s stride is `side` (this decoder never crops a
8559/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
8560/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
8561/// actual colour index to store.
8562pub(crate) fn palette_color_index_context(
8563 map: &[u8],
8564 side: usize,
8565 row: usize,
8566 col: usize,
8567 n: usize,
8568) -> (usize, [u8; 8]) {
8569 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
8570 let up_left = if col >= 1 && row >= 1 {
8571 Some(map[(row - 1) * side + col - 1])
8572 } else {
8573 None
8574 };
8575 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
8576 let mut scores = [0i32; 8];
8577 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
8578 if let Some(v) = neighbour {
8579 scores[v as usize] += weight;
8580 }
8581 }
8582 let mut color_order = [0u8; 8];
8583 for i in 0..8 {
8584 color_order[i] = i as u8;
8585 }
8586 for i in 0..3 {
8587 let mut max = scores[i];
8588 let mut max_idx = i;
8589 for j in (i + 1)..n {
8590 if scores[j] > max {
8591 max = scores[j];
8592 max_idx = j;
8593 }
8594 }
8595 if max_idx != i {
8596 let max_score = scores[max_idx];
8597 let max_color = color_order[max_idx];
8598 for k in (i + 1..=max_idx).rev() {
8599 scores[k] = scores[k - 1];
8600 color_order[k] = color_order[k - 1];
8601 }
8602 scores[i] = max_score;
8603 color_order[i] = max_color;
8604 }
8605 }
8606 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
8607 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
8608 (ctx as usize, color_order)
8609}
8610
8611/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
8612/// map's wavefront decode over a `side x side` grid -- this decoder's
8613/// palette blocks are always square and never straddle the frame's true
8614/// (possibly odd) edge without already allocating the full `side*side`
8615/// region (every other skip/residual path here does the same), so no
8616/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
8617/// libaom's own non-block-aligned split.
8618fn decode_color_index_map(
8619 dec: &mut SymbolDecoder,
8620 cdfs: &mut Cdfs,
8621 n: usize,
8622 side: usize,
8623 uv: bool,
8624) -> Vec<u8> {
8625 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
8626}
8627
8628/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
8629/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
8630/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
8631/// independently rather than one shared `side` -- the square call above is
8632/// just `bw == bh`.
8633fn decode_color_index_map_wh(
8634 dec: &mut SymbolDecoder,
8635 cdfs: &mut Cdfs,
8636 n: usize,
8637 bw: usize,
8638 bh: usize,
8639 uv: bool,
8640) -> Vec<u8> {
8641 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8642 let mut map = vec![0u8; bw * bh];
8643 if trace {
8644 let (rng, _) = dec.debug_state();
8645 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
8646 }
8647 map[0] = read_uniform(dec, n) as u8;
8648 if trace {
8649 let (rng, _) = dec.debug_state();
8650 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
8651 }
8652 for i in 1..(bw + bh - 1) {
8653 let j_hi = i.min(bw - 1);
8654 let j_lo = i.saturating_sub(bh - 1);
8655 for j in (j_lo..=j_hi).rev() {
8656 let row = i - j;
8657 let col = j;
8658 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
8659 if trace {
8660 let (rng, _) = dec.debug_state();
8661 let row_cdf = if uv {
8662 &cdfs.palette_uv_color_index[n - 2][ctx]
8663 } else {
8664 &cdfs.palette_y_color_index[n - 2][ctx]
8665 };
8666 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
8667 }
8668 let symbol = if uv {
8669 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
8670 } else {
8671 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
8672 };
8673 map[row * bw + col] = color_order[symbol];
8674 if trace {
8675 let (rng, _) = dec.debug_state();
8676 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
8677 }
8678 }
8679 }
8680 map
8681}
8682
8683/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
8684/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
8685/// size class comes from [`filter_intra_size_class_rect`] instead of the
8686/// square-only [`filter_intra_size_class`], and the palette read (when
8687/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
8688/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
8689/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
8690/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
8691#[allow(clippy::too_many_arguments)]
8692fn read_intra_mode_rect(
8693 dec: &mut SymbolDecoder,
8694 cdfs: &mut Cdfs,
8695 above_mode: usize,
8696 left_mode: usize,
8697 cfl: bool,
8698 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
8699 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
8700 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
8701 // chroma is coded once, on the closing strip). Every other caller is a
8702 // block big enough to own its chroma and passes `true`.
8703 has_chroma: bool,
8704 bw: usize,
8705 bh: usize,
8706 enable_filter_intra: bool,
8707 skip_ctx: usize,
8708 allow_screen_content_tools: bool,
8709 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
8710 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
8711 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
8712 palette: Option<(usize, &[u16])>,
8713 palette_uv_cache: &[u16],
8714 mi_r: usize,
8715 mi_c: usize, fctx: &crate::decode::FrameCtx,
8716) -> Result<(
8717 bool,
8718 usize,
8719 i32,
8720 usize,
8721 i32,
8722 Option<(i32, i32)>,
8723 Option<usize>,
8724 Option<PaletteY>,
8725 Option<PaletteUv>,
8726)> {
8727 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
8728 if ec_istep {
8729 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
8730 // (decodemv.c:818), printed at the same point: before the first
8731 // mode-info symbol of the block, so a cross-decoder range ladder can
8732 // be keyed on the BLOCK, not just on the symbol sequence.
8733 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);
8734 }
8735 macro_rules! istep {
8736 ($name:literal, $val:expr) => {
8737 if ec_istep {
8738 let (rng, _) = dec.debug_state();
8739 eprintln!(
8740 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
8741 $name, $val
8742 );
8743 }
8744 };
8745 }
8746 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
8747 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
8748 // the one point every rect caller routes through, so no call site can
8749 // offer the 14-symbol CFL alphabet on a 64-axis block (class
8750 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
8751 let cfl = if cfl && bw.max(bh) > 32 {
8752 hit!(NOCFL_UV_MODE_HITS);
8753 false
8754 } else {
8755 cfl
8756 };
8757 // lane-intra14 r1: on the INTER block path everything up to and including
8758 // `is_inter` was already read by [`decode_inter_block`], so this reader
8759 // starts at the mode syntax with the `skip` that caller read.
8760 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
8761 let skip = if let Some((_, skip)) = inter {
8762 skip
8763 } else {
8764 // Same `intra_segment_id` placement as the square reader above.
8765 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
8766 if seg_id_pre_skip(fctx) {
8767 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
8768 }
8769 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8770 istep!("skip", skip as i32);
8771 if !seg_id_pre_skip(fctx) {
8772 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
8773 }
8774 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
8775 istep!("cdef", 0);
8776 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
8777 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
8778 // `false`.
8779 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8780 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8781 istep!("dq", 0);
8782 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
8783 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
8784 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
8785 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
8786 // rect strips read it exactly like square leaves ([`read_intra_mode`],
8787 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
8788 // decoder at the FIRST symbol of the first rect block of every
8789 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
8790 // block at this shape is out of scope, so the flag is consumed and
8791 // refused by name when it fires.
8792 if allow_intrabc_frame(fctx) {
8793 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8794 hit!(RECT_INTRABC_READS);
8795 istep!("intrabc", use_intrabc as i32);
8796 if use_intrabc {
8797 hit!(INTRABC_HITS);
8798 return Err(unsupported(
8799 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
8800 ));
8801 }
8802 }
8803 skip
8804 };
8805 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
8806 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
8807 // off `kf_y_mode_cdf[above][left]`).
8808 let mode = if let Some((size_group, _)) = inter {
8809 dec.symbol(&mut cdfs.y_mode[size_group])
8810 } else {
8811 let above_ctx = INTRA_MODE_CTX[above_mode];
8812 let left_ctx = INTRA_MODE_CTX[left_mode];
8813 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
8814 };
8815 istep!("mode", mode as i32);
8816 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8817 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8818 } else {
8819 0
8820 };
8821 istep!("angle_y", angle_delta_y);
8822 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
8823 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
8824 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
8825 // here, from the block's own size, is the single point every caller routes
8826 // through -- a caller passing `true` for a >32 strip used to pick the
8827 // 14-symbol CFL CDF, same value but a different range (class
8828 // wrong-alphabet-same-value).
8829 let cfl = cfl && bw <= 32 && bh <= 32;
8830 let uv_mode = if !has_chroma {
8831 DC_PRED
8832 } else if cfl {
8833 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
8834 } else {
8835 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
8836 };
8837 istep!("uv_mode", uv_mode as i32);
8838 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
8839 Some(read_cfl_alphas(dec, cdfs))
8840 } else {
8841 None
8842 };
8843 if has_chroma && (9..=12).contains(&uv_mode) {
8844 hit!(SMOOTH_UV_HITS);
8845 }
8846 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
8847 hit!(DIRECTIONAL_UV_HITS);
8848 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8849 } else {
8850 0
8851 };
8852 istep!("angle_uv", angle_delta_uv);
8853 if angle_delta_uv != 0 {
8854 hit!(UV_ANGLE_DELTA_HITS);
8855 }
8856 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
8857 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
8858 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
8859 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
8860 // colours only here, the colour-index maps deferred past `filter_intra`
8861 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
8862 // runs from the caller, after the whole mode-info read).
8863 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
8864 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
8865 if allow_screen_content_tools
8866 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
8867 {
8868 // r6: this is the exact site the removed blanket refusal used to
8869 // guard -- reached for EVERY rect strip in a screen-content frame,
8870 // independent of whether the block ends up using a palette.
8871 hit!(RECT_SCREEN_CONTENT_HITS);
8872 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
8873 let use_palette_y =
8874 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
8875 if use_palette_y {
8876 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8877 let colors = read_palette_colors_y(dec, n, cache, fctx);
8878 palette_y_pending = Some((n, colors));
8879 }
8880 let palette_uv_mode_ctx = usize::from(use_palette_y);
8881 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
8882 if has_chroma
8883 && uv_mode == DC_PRED
8884 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
8885 {
8886 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8887 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
8888 palette_uv_pending = Some((n, u_colors, v_colors));
8889 }
8890 }
8891 let mut filter_intra = None;
8892 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8893 let (rng, _) = dec.debug_state();
8894 eprintln!(
8895 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
8896 class={:?} rng={rng}",
8897 enable_filter_intra as i32,
8898 filter_intra_size_class_rect(bw, bh)
8899 );
8900 }
8901 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
8902 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
8903 if mode == DC_PRED
8904 && enable_filter_intra
8905 && palette_y_pending.is_none()
8906 && let Some(class) = filter_intra_size_class_rect(bw, bh)
8907 {
8908 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
8909 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8910 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
8911 }
8912 istep!("use_filter_intra", use_filter_intra as i32);
8913 if use_filter_intra {
8914 hit!(FILTER_INTRA_HITS);
8915 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
8916 istep!("filter_intra_mode", fi_mode as i32);
8917 filter_intra = Some(fi_mode);
8918 }
8919 }
8920 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
8921 // same order as [`read_intra_mode`]'s own square path.
8922 let palette_y = palette_y_pending.map(|(n, colors)| {
8923 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
8924 hit!(PALETTE_HITS);
8925 hit!(PALETTE_RECT_HITS);
8926 PaletteY { size: n, colors, map }
8927 });
8928 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
8929 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
8930 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
8931 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
8932 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
8933 // chroma palette and desynced the tile from there.
8934 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
8935 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
8936 hit!(PALETTE_UV_HITS);
8937 PaletteUv { size: n, u_colors, v_colors, map }
8938 });
8939 Ok((
8940 skip,
8941 mode,
8942 angle_delta_y,
8943 uv_mode,
8944 angle_delta_uv,
8945 alpha,
8946 filter_intra,
8947 palette_y,
8948 palette_uv,
8949 ))
8950}
8951
8952/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
8953/// at the strip's REAL mi position. `av1_get_palette_cache` reads
8954/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
8955/// block, so each strip owns its own rows and columns and no aliasing rule
8956/// is needed (lane-kf900 r6).
8957#[allow(clippy::too_many_arguments)]
8958fn record_strip_palette(
8959 n: &mut Neighbours,
8960 mi: (usize, usize),
8961 bw: usize,
8962 bh: usize,
8963 y_size: usize,
8964 y_colors: [u16; 8],
8965 uv_size: usize,
8966 uv_colors: [u16; 8],
8967) {
8968 let (r, c) = mi;
8969 // lane-t900 r23 rung: every publication of a block's palette state into
8970 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
8971 // path left a stale `left_palette_size` behind when
8972 // `av1_get_palette_mode_ctx` disagrees with libaom's.
8973 if crate::envflags::env_flag!("EC_PALPUB") {
8974 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
8975 }
8976 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
8977 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
8978 // existed because the 16px [`SUB`] cell held one slot for all the strips
8979 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
8980 // real neighbour leaf 1 reads.
8981 {
8982 for cell in 0..(bw / MI).max(1) {
8983 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
8984 *e = y_size as u8;
8985 n.above_palette_uv_size[c + cell] = uv_size as u8;
8986 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
8987 // colours of a size-0 neighbour are never read.
8988 if y_size > 0 {
8989 n.above_palette_colors[c + cell] = y_colors;
8990 }
8991 if uv_size > 0 {
8992 n.above_palette_uv_colors[c + cell] = uv_colors;
8993 }
8994 }
8995 }
8996 }
8997 {
8998 for cell in 0..(bh / MI).max(1) {
8999 if n.left_palette_size.get(r + cell).is_none() {
9000 break;
9001 }
9002 n.left_palette_size[r + cell] = y_size as u8;
9003 n.left_palette_uv_size[r + cell] = uv_size as u8;
9004 if y_size > 0 {
9005 n.left_palette_colors[r + cell] = y_colors;
9006 }
9007 if uv_size > 0 {
9008 n.left_palette_uv_colors[r + cell] = uv_colors;
9009 }
9010 }
9011 }
9012}
9013
9014/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
9015/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
9016/// above against this block's own *width* and the neighbour to the left
9017/// against its own *height* -- for a square block those are the same value,
9018/// which is why the square-only version can get away with one `own_side`.
9019fn tx_size_context_rect(
9020 n: &Neighbours,
9021 (mi_r, mi_c): (usize, usize),
9022 own_w: usize,
9023 own_h: usize,
9024) -> usize {
9025 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
9026 // not the block's own side: no transform is wider or taller than 64, so a
9027 // block with a 128 side resolves against 64 (the square path already caps
9028 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
9029 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
9030 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
9031 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
9032 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
9033 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9034 eprintln!(
9035 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
9036 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
9037 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
9038 usize::from(above) + usize::from(left)
9039 );
9040 }
9041 usize::from(above) + usize::from(left)
9042}
9043
9044/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9045fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9046 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9047}
9048
9049/// Everything a rect strip already read out of the stream before its luma
9050/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9051/// (nine values that would otherwise be nine more parameters).
9052struct RectStripModes {
9053 skip: bool,
9054 mode: usize,
9055 angle_delta_y: i32,
9056 uv_predict_mode: usize,
9057 angle_delta_uv: i32,
9058 alpha: Option<(i32, i32)>,
9059 filter_intra: Option<usize>,
9060 smooth_neighbor: bool,
9061 smooth_neighbor_uv: bool,
9062 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9063 /// mapped through the colour table), sliced per transform unit below --
9064 /// palette prediction reads no edge pixels, so a unit's slice of the
9065 /// whole-block map IS its prediction. Without this a palette strip whose
9066 /// transform splits predicted DC and came out flat grey while the entropy
9067 /// stream stayed in sync (the coefficients are read either way).
9068 palette_y: Option<Vec<u16>>,
9069 /// As `palette_y`, for the un-split chroma transform (U, V).
9070 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9071}
9072
9073/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9074/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9075/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9076/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9077/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9078/// TX_32X16`) and only the second reaches a square -- the reason
9079/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9080/// already square) mis-tiled 1:4 strips.
9081fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
9082 let (mut w, mut h) = (bw.min(64), bh.min(64));
9083 for _ in 0..depth {
9084 match w.cmp(&h) {
9085 std::cmp::Ordering::Greater => w /= 2,
9086 std::cmp::Ordering::Less => h /= 2,
9087 std::cmp::Ordering::Equal => {
9088 w /= 2;
9089 h /= 2;
9090 }
9091 }
9092 }
9093 (w, h)
9094}
9095
9096/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9097/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9098/// rect path here refused by name until now ("per-unit rect prediction is not
9099/// ported").
9100///
9101/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9102/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9103/// strip the very first step already lands on a SQUARE transform
9104/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9105/// every further step halves a square) -- so each unit is square and reads
9106/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9107/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9108/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9109/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9110/// split by luma's depth.
9111///
9112/// Each unit predicts off whatever the earlier units of this same block
9113/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9114/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9115/// what predicting the whole strip in one shot got wrong.
9116#[allow(clippy::too_many_arguments)]
9117fn decode_rect_split(
9118 dec: &mut SymbolDecoder,
9119 cdfs: &mut Cdfs,
9120 neighbours: &mut Neighbours,
9121 at_mi: (usize, usize),
9122 bw: usize,
9123 bh: usize,
9124 // The transform unit's own width and height in pixels. Square for every
9125 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9126 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9127 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9128 tx_w: usize,
9129 tx_h: usize,
9130 m: &RectStripModes,
9131 y: &mut PlaneBuf<'static>,
9132 u: &mut PlaneBuf<'static>,
9133 v: &mut PlaneBuf<'static>,
9134 base_q_idx: u8,
9135 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9136) -> Result<()> {
9137 let (mi_r, mi_c) = at_mi;
9138 let (px, py) = (mi_c * MI, mi_r * MI);
9139 let (cpx, cpy) = (px / 2, py / 2);
9140 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9141 // The chroma transform is picked before any symbol is read, so an
9142 // unsupported chroma shape refuses before this strip desyncs the tile.
9143 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9144 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9145 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9146 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9147 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9148 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9149 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9150 // squares a rect transform down to a CDF set by
9151 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9152 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9153 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9154 // paths already prove for these same shapes.
9155 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9156 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9157 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9158 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9159 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9160 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9161 _ => None,
9162 };
9163 if !m.skip {
9164 if let Some(i) = match (chroma_w, chroma_h) {
9165 (32, 8) => Some(0),
9166 (8, 32) => Some(1),
9167 (8, 4) => Some(2),
9168 (4, 8) => Some(3),
9169 _ => None,
9170 } {
9171 hit_do! {
9172 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9173 let mut hits = c.get();
9174 hits[i] += 1;
9175 c.set(hits);
9176 });
9177 }
9178 }
9179 if chroma.is_none() {
9180 // Diagnostic for the next caller that lands here (class
9181 // refusal-names-a-correlate: the message names the tool, not the
9182 // shape); the refusal below keeps its inventory-pinned wording.
9183 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9184 }
9185 }
9186 // lane-rectsplit r2 (verifier finding): with both callers wired
9187 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9188 // 64x32/32x64) every shape that reaches here has a table above, so this
9189 // arm is UNREACHABLE today. It stays as the shape guard for the next
9190 // caller -- a new strip size would otherwise hit the `expect` below and
9191 // panic instead of refusing by name -- and so stays in
9192 // `refusal_inventory::REFUSALS`.
9193 if !m.skip && chroma.is_none() {
9194 return Err(unsupported(
9195 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9196 ));
9197 }
9198 hit!(RECT_SPLIT_TX_HITS);
9199 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9200 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9201 }
9202 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9203 // A square unit reads through the ordinary square [`read_plane`]; a rect
9204 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9205 // the very tables the unsplit 16x8/32x16 paths use.
9206 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9207 (w, h) if w == h => None,
9208 (16, 8) | (8, 16) => Some((
9209 if reduced_tx_set {
9210 TxbSet::LumaRect16x8
9211 } else {
9212 TxbSet::LumaRect16x8Set1
9213 },
9214 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9215 )),
9216 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9217 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9218 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9219 // strip, read through the `luma_64corner` arm below instead of a rect
9220 // table -- a 64-length axis codes only its low 32 coefficients
9221 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9222 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9223 // depth-0 arm already reads on the key-frame path.
9224 //
9225 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9226 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9227 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9228 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9229 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9230 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9231 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9232 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9233 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9234 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9235 (64, 32) | (32, 64) => None,
9236 _ => {
9237 return Err(unsupported(format!(
9238 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9239 coefficient tables for that shape here)"
9240 )))
9241 }
9242 };
9243 // The `None` above that is NOT the square arm.
9244 let luma_64corner = tx_w != tx_h;
9245 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9246 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9247 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9248 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9249 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9250 // per-unit rect walk stay wired above/below; the round that finds that
9251 // defect deletes this refusal and nothing else.
9252 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9253 let luma_scan = default_scan(tx_w.min(tx_h));
9254 let zero_tu = vec![0i32; tx_w * tx_h];
9255 // The strip's OWN edge availability, the fallback for a transform unit
9256 // whose top-right/bottom-left pixels fall outside the strip.
9257 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9258 for tu_row in 0..bh / tx_h {
9259 for tu_col in 0..bw / tx_w {
9260 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9261 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9262 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9263 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9264 // libaom clips `av1_foreach_transformed_block_in_plane` to
9265 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9266 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9267 // TOP-LEFT sample falls outside the frame is never coded. We read
9268 // coefficients for those phantom units and desynced the stream at
9269 // the very next symbol.
9270 if tu_px >= y.true_width || tu_py >= y.true_height {
9271 continue;
9272 }
9273 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9274 // transform unit INSIDE a block, which is a different rule from
9275 // the standalone-block table [`Reach::of`] applies -- and the
9276 // reason a depth-2 superblock strip came out one sample off
9277 // before this: `Reach::of(tx, ..)` answered as if the unit were
9278 // its own block at that superblock position.
9279 // * top-right: if the unit's right neighbour is still inside the
9280 // strip the pixels are already reconstructed (`col_off +
9281 // tx_wide < plane_bw`); otherwise only the strip's own top row
9282 // of units can reach past it, through the block-level answer.
9283 // * bottom-left: a unit that is not in the strip's left column
9284 // has none (`col_off > 0` returns 0); inside the strip
9285 // (`row_off + tx_high < plane_bh`) they are the left
9286 // neighbour's, already reconstructed; the last row falls back
9287 // to the block-level answer.
9288 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9289 // The unit's own window on the block's palette prediction.
9290 if let Some(buf) = &m.palette_y {
9291 let tu_buf: Vec<u16> = (0..tx_h)
9292 .flat_map(|i| {
9293 let base = (row_off + i) * bw + col_off;
9294 buf[base..base + tx_w].iter().copied()
9295 })
9296 .collect();
9297 set_palette_pred(tu_buf, fctx);
9298 }
9299 if m.skip {
9300 push_intra_rect(0,
9301 tu_px,
9302 tu_py,
9303 tx_w,
9304 tx_h,
9305 m.mode,
9306 m.angle_delta_y,
9307 tu_reach,
9308 &zero_tu,
9309 None,
9310 m.filter_intra,
9311 m.smooth_neighbor, fctx,
9312 );
9313 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9314 } else if luma_64corner && luma_rect.is_none() {
9315 // The un-split 64-level luma transform: `read_coeffs` on the
9316 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9317 // and the real rect shape passed through for
9318 // `av1_nz_map_ctx_offset` -- byte for byte
9319 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9320 // 64-level strip gate already proves. `tx_type` is not coded
9321 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9322 // the square-up size is TX_64X64), and this unit covers its
9323 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9324 if crate::envflags::env_flag!("EC_RECT64TU") {
9325 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9326 }
9327 hit_do! {
9328 RECT64_CORNER_TU_HITS.with(|c| {
9329 let mut v = c.get();
9330 v[usize::from(tx_h > tx_w)] += 1;
9331 c.set(v);
9332 });
9333 }
9334 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9335 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
9336 let (corner, tu_tx_type) = read_coeffs(
9337 dec,
9338 &mut coding,
9339 default_scan(TX32),
9340 0,
9341 dc_sign_ctx(tu_around.2),
9342 TxType::DctDct,
9343 Some((tx_w, tx_h)),
9344 )?;
9345 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
9346 let mut tu_grid = vec![0i32; tx_w * tx_h];
9347 for row in 0..ch {
9348 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
9349 }
9350 let residual = dequant_and_inverse_typed_wh(
9351 &tu_grid,
9352 tx_w,
9353 tx_h,
9354 crate::decode::bit_depth(fctx),
9355 block_q_idx(fctx),
9356 plane_q_delta(0, fctx).0,
9357 plane_q_delta(0, fctx).1,
9358 tu_tx_type,
9359 );
9360 push_intra_rect(0,
9361 tu_px,
9362 tu_py,
9363 tx_w,
9364 tx_h,
9365 m.mode,
9366 m.angle_delta_y,
9367 tu_reach,
9368 &residual,
9369 None,
9370 m.filter_intra,
9371 m.smooth_neighbor, fctx,
9372 );
9373 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9374 } else if let Some((rect_set, rect_scan)) = luma_rect {
9375 // The rect-unit twin of the square arm below: same contexts,
9376 // same order, through the rect coefficient reader. The
9377 // `tx_type` CDF row of a filter-intra block is
9378 // `fimode_to_intradir[filter_intra_mode]`, never the block's
9379 // own (always DC_PRED) mode -- [`read_plane`] applies that
9380 // for the square arm, so this one must too.
9381 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9382 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
9383 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
9384 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
9385 // neighbour-magnitude table is for a unit SMALLER than its
9386 // block. [`decode_block_rect`]'s own unsplit read passes a
9387 // literal 0 for the same reason; this arm applied the table
9388 // unconditionally and desynced every depth-0 rect strip that
9389 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
9390 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
9391 0
9392 } else {
9393 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
9394 };
9395 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
9396 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9397 dec,
9398 &mut coding,
9399 rect_scan,
9400 tx_w,
9401 tx_h,
9402 tu_skip_ctx,
9403 dc_sign_ctx(tu_around.2),
9404 TxType::DctDct,
9405 )?;
9406 let residual = dequant_and_inverse_typed_wh(
9407 &tu_grid,
9408 tx_w,
9409 tx_h,
9410 crate::decode::bit_depth(fctx),
9411 block_q_idx(fctx),
9412 plane_q_delta(0, fctx).0,
9413 plane_q_delta(0, fctx).1,
9414 tu_tx_type,
9415 );
9416 push_intra_rect(0,
9417 tu_px,
9418 tu_py,
9419 tx_w,
9420 tx_h,
9421 m.mode,
9422 m.angle_delta_y,
9423 tu_reach,
9424 &residual,
9425 None,
9426 m.filter_intra,
9427 m.smooth_neighbor, fctx,
9428 );
9429 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9430 } else {
9431 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9432 // This unit is smaller than the block it sits in, so
9433 // `txb_skip_ctx` is the neighbour-magnitude table, not the
9434 // lone-TU 0 (spec `get_txb_ctx_general`).
9435 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9436 let tu_grid = read_plane(
9437 dec,
9438 cdfs,
9439 luma_set,
9440 &luma_scan,
9441 0,
9442 tu_around,
9443 m.mode,
9444 m.mode,
9445 m.angle_delta_y,
9446 tu_reach,
9447 y,
9448 tu_px,
9449 tu_py,
9450 tx_w,
9451 tx_w,
9452 base_q_idx,
9453 None,
9454 m.filter_intra,
9455 Some(tu_skip_ctx),
9456 m.smooth_neighbor, fctx,
9457 )?;
9458 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9459 }
9460 }
9461 }
9462 // CHROMA: one un-split rect transform for the whole strip.
9463 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9464 let reach = block_reach;
9465 let (u_grid, v_grid) = if m.skip {
9466 let zero = Grid::Zero(chroma_w * chroma_h);
9467 if let Some((ub, _)) = &m.palette_uv {
9468 set_palette_pred(ub.clone(), fctx);
9469 }
9470 push_intra_rect(1,
9471 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9472 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
9473 );
9474 if let Some((_, vb)) = &m.palette_uv {
9475 set_palette_pred(vb.clone(), fctx);
9476 }
9477 push_intra_rect(2,
9478 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9479 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
9480 );
9481 (zero.clone(), zero)
9482 } else {
9483 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
9484 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
9485 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
9486 // so only the 16x8/8x16 pair takes the mode-indexed default.
9487 let default_tx = if chroma_w.max(chroma_h) >= 32 {
9488 TxType::DctDct
9489 } else {
9490 default_intra_tx_type(m.uv_predict_mode as u8)
9491 };
9492 let around = neighbours.around_mi_rect(at_mi, bw, bh);
9493 let mut grids: Vec<Grid> = Vec::with_capacity(2);
9494 for plane_idx in 1..=2 {
9495 let skip_ctx =
9496 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
9497 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
9498 let (levels, tx_type) = read_coeffs_rect(
9499 dec,
9500 &mut coding,
9501 chroma_scan,
9502 chroma_w,
9503 chroma_h,
9504 skip_ctx,
9505 dc_sign_ctx(around[plane_idx].2),
9506 default_tx,
9507 )?;
9508 // The same delta_q proof the unsplit rect64 path records
9509 // (lane-rectsplit r4: lifting the split-transform refusal moved
9510 // superblock strips onto this path, so only counting there would
9511 // leave the delta_q gate's counter silent for them).
9512 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
9513 hit!(RECT64_QIDX_DRIFT_HITS);
9514 }
9515 let residual = dequant_and_inverse_typed_wh(
9516 &levels,
9517 chroma_w,
9518 chroma_h,
9519 crate::decode::bit_depth(fctx),
9520 fctx.current_q_idx.with(|c| c.get()),
9521 plane_q_delta(plane_idx, fctx).0,
9522 plane_q_delta(plane_idx, fctx).1,
9523 tx_type,
9524 );
9525 let cfl = m
9526 .alpha
9527 .zip(ac)
9528 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
9529 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9530 if let Some((ub, vb)) = &m.palette_uv {
9531 let buf = if plane_idx == 1 { ub } else { vb };
9532 set_palette_pred(buf.clone(), fctx);
9533 }
9534 push_intra_rect(plane_idx,
9535 cpx,
9536 cpy,
9537 chroma_w,
9538 chroma_h,
9539 m.uv_predict_mode,
9540 m.angle_delta_uv,
9541 reach,
9542 &residual,
9543 cfl,
9544 None,
9545 m.smooth_neighbor_uv, fctx,
9546 );
9547 grids.push(levels);
9548 }
9549 let mut it = grids.into_iter();
9550 (it.next().unwrap(), it.next().unwrap())
9551 };
9552 neighbours.record_split_luma_rect_mi(
9553 at_mi,
9554 bw,
9555 bh,
9556 m.mode,
9557 m.uv_predict_mode,
9558 [&u_grid, &v_grid],
9559 );
9560 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
9561 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
9562 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9563 let (rng, _) = dec.debug_state();
9564 eprintln!(
9565 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
9566 tx={tx_w}x{tx_h} rng={rng}"
9567 );
9568 }
9569 Ok(())
9570}
9571
9572/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
9573/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
9574/// because it predicts squares only. Every pixel here goes through the rect
9575/// machinery the key-frame paths already prove: [`decode_rect_split`], which
9576/// at `depth == 0` is the unsplit strip as a single transform unit and
9577/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9578///
9579/// What is genuinely different from [`decode_block_rect`] is the mode
9580/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9581/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9582/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9583/// intra-in-inter arm's own reads at the rect footprint, including its
9584/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9585/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9586/// square and this arm) and a nonzero luma angle delta refused by name.
9587///
9588/// The strip's own neighbour records (luma per transform unit, chroma, skip
9589/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9590/// inter-side bands and the mi map.
9591#[allow(clippy::too_many_arguments)]
9592/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9593/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9594/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9595/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9596/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9597/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
9598/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
9599/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
9600/// table here rather than a shift of `bw.min(bh)`.
9601fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
9602 Some(match (bw.min(bh), bw.max(bh)) {
9603 (8, 16) => (1usize, 1usize),
9604 (16, 32) => (2, 2),
9605 (32, 64) => (3, 3),
9606 (8, 32) => (1, 2),
9607 (16, 64) => (2, 3),
9608 _ => return None,
9609 })
9610}
9611
9612/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
9613/// block path"): the shapes that can reach that arm, enumerated against the
9614/// MEASURED domain of the inter block path
9615/// ([`INTER_BLOCK_SHAPES`], the census the gate
9616/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
9617/// fills from three real streams).
9618///
9619/// [`decode_intra_rect_in_inter`] is called from one site, under
9620/// `write_w != side || write_h != side`, and only after two earlier arms have
9621/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
9622/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
9623/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
9624/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
9625/// and each of those has a row, so the refusal names a shape no measured
9626/// stream can present.
9627#[test]
9628fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
9629 let mut checked = 0;
9630 for &(side, w, h) in &INTER_BLOCK_SHAPES {
9631 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
9632 continue;
9633 }
9634 assert!(
9635 intra_in_inter_size_row(w, h).is_some(),
9636 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
9637 the \"no size-group/tx-category row\" refusal"
9638 );
9639 checked += 1;
9640 }
9641 assert_eq!(
9642 checked, 10,
9643 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
9644 lookup, not the 10 this claim was measured over"
9645 );
9646}
9647
9648/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
9649/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
9650/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
9651/// matched before the square arm's `log2` shortcut).
9652///
9653/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
9654/// row here"; the enumeration below is what proves no conformant block can
9655/// reach it.
9656pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
9657 Some(match (write_w, write_h) {
9658 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
9659 // below maps 128 to row 4 (BLOCK_16X32).
9660 (64, 128) => 14,
9661 (128, 64) => 15,
9662 (128, 128) => 16,
9663 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
9664 (16, 32) => 4,
9665 (32, 16) => 5,
9666 (32, 64) => 6,
9667 (64, 32) => 7,
9668 (8, 32) => 8,
9669 (32, 8) => 9,
9670 (16, 64) => 10,
9671 (64, 16) => 11,
9672 // lane-inter4 r3: the 16x16-level rect inter leaves.
9673 (8, 16) => 12,
9674 (16, 8) => 13,
9675 _ => return None,
9676 })
9677}
9678
9679/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
9680/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
9681/// `block_size_wide`/`block_size_high`).
9682#[cfg(test)]
9683const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
9684 (4, 4),
9685 (4, 8),
9686 (8, 4),
9687 (8, 8),
9688 (8, 16),
9689 (16, 8),
9690 (16, 16),
9691 (16, 32),
9692 (32, 16),
9693 (32, 32),
9694 (32, 64),
9695 (64, 32),
9696 (64, 64),
9697 (64, 128),
9698 (128, 64),
9699 (128, 128),
9700 (4, 16),
9701 (16, 4),
9702 (8, 32),
9703 (32, 8),
9704 (16, 64),
9705 (64, 16),
9706];
9707
9708/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
9709/// shape with no CDF row here" names a shape no conformant stream can present.
9710///
9711/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
9712/// whose `write_w.min(write_h) >= 8` clause is libaom's
9713/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
9714/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
9715/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
9716/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
9717/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
9718/// clause rejects before the lookup.
9719#[test]
9720fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
9721 let mut rows = std::collections::BTreeSet::new();
9722 let mut excluded = 0;
9723 for (w, h) in BLOCK_SIZES_ALL_WH {
9724 if w.min(h) < 8 {
9725 excluded += 1;
9726 assert!(
9727 w == 4 || h == 4,
9728 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
9729 );
9730 continue;
9731 }
9732 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
9733 panic!(
9734 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
9735 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
9736 )
9737 });
9738 assert!(
9739 row < 17,
9740 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
9741 );
9742 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
9743 }
9744 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
9745 assert_eq!(
9746 rows.len(),
9747 17,
9748 "17 eligible footprints must fill all 17 rows of the motion_mode table"
9749 );
9750}
9751
9752fn decode_intra_rect_in_inter(
9753 dec: &mut SymbolDecoder,
9754 cdfs: &mut Cdfs,
9755 neighbours: &mut Neighbours,
9756 at: (usize, usize),
9757 bw: usize,
9758 bh: usize,
9759 skip: bool,
9760 allow_screen_content_tools: bool,
9761 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
9762 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
9763 strip16: Option<(bool, bool)>,
9764 y: &mut PlaneBuf<'static>,
9765 u: &mut PlaneBuf<'static>,
9766 v: &mut PlaneBuf<'static>,
9767 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
9768) -> Result<()> {
9769 // `at` is in MI units (the inter path's own unit since lane-inter4);
9770 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
9771 // below are still keyed by.
9772 let (mi_r, mi_c) = at;
9773 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9774 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
9775 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
9776 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
9777 // finding -- the category is NOT the same for every strip size).
9778 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
9779 // it is refused by name rather than read from the wrong CDF row.
9780 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
9781 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
9782 // tx-depth category is 1 -- but nothing here has to know either, because
9783 // the strip decodes through the very body the KEY FRAME path proves for
9784 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
9785 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
9786 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
9787 // inter-frame difference is the mode-info read, which
9788 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
9789 // `y_mode[0]` plus the `skip` this caller already read.
9790 if let Some((horz, has_chroma)) = strip16 {
9791 // lane-t900 r22: the screen-content refusal here was STALE (class
9792 // stale-premise): [`decode_rect4_16_strip`] takes
9793 // `allow_screen_content_tools` and reads the whole palette syntax
9794 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
9795 // pair) -- the key frame proves that body. Lifted with the 10-bit
9796 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
9797 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
9798 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
9799 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
9800 let res = decode_rect4_16_strip(
9801 dec,
9802 cdfs,
9803 neighbours,
9804 (mi_r, mi_c),
9805 horz,
9806 has_chroma,
9807 // The inter strips of the same partition publish their own
9808 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
9809 // has nothing to add here.
9810 None,
9811 y,
9812 u,
9813 v,
9814 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9815 allow_screen_content_tools,
9816 base_q_idx,
9817 fctx.tx_select_inter.with(std::cell::Cell::get),
9818 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9819 );
9820 fctx.intra_in_inter_mode.with(|c| c.set(None));
9821 let (mode, uv, (tx_w, tx_h)) = res?;
9822 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
9823 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
9824 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
9825 // block of an inter frame, intra ones included, and
9826 // `txfm_partition_update` for the var-tx context. The key-frame body
9827 // writes neither (a key frame has no var-tx tree and its own readers
9828 // use the deblock grid), so the block AFTER this strip read a stale
9829 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
9830 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
9831 // 16x16 row.
9832 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9833 for i in 0..bw / MI {
9834 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
9835 *cell = tx_w as u8;
9836 }
9837 }
9838 for i in 0..bh / MI {
9839 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
9840 *cell = tx_h as u8;
9841 }
9842 }
9843 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
9844 // coarse 16-px cell holds one entry for the whole 16x16 and the last
9845 // block to write it wins).
9846 neighbours.above_mode[c] = mode;
9847 neighbours.left_mode[r] = mode;
9848 if let Some(uvm) = uv {
9849 neighbours.above_uv_mode[c] = uvm;
9850 neighbours.left_uv_mode[r] = uvm;
9851 }
9852 neighbours.above_side[c] = bw;
9853 neighbours.left_side[r] = bh;
9854 if crate::envflags::env_flag!("EC_INTRA16X4") {
9855 eprintln!(
9856 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
9857 mi_c * MI,
9858 mi_r * MI
9859 );
9860 }
9861 hit_do! {
9862 INTRA16X4_IN_INTER_HITS.with(|h| {
9863 let mut v = h.get();
9864 v[usize::from(!horz)] += 1;
9865 v[2] += usize::from(has_chroma);
9866 h.set(v);
9867 });
9868 }
9869 return Ok(());
9870 }
9871 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
9872 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
9873 // puts BLOCK_128X64/64X128/128X128 in group 3 and
9874 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
9875 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
9876 // block decodes through the very body the KEY FRAME path proves for this
9877 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
9878 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
9879 // `Reach` rule and the frame-edge write clip). The only inter-frame
9880 // differences live inside that body: the mode-info read
9881 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
9882 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
9883 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
9884 // palette (>64) do not exist at this size and are refused by name there.
9885 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
9886 // `intra128_in_inter_witness2.obu` (gate
9887 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
9888 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
9889 // all 15 frames, so the hits are counted out of exact frames (class
9890 // `counter-from-refused-stream`). What r16/r17 could not find, and what
9891 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
9892 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
9893 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
9894 // where the frame EDGE forces it: a partial last superblock row has
9895 // `has_rows128 == false`, so the 128x64 top half is implied, and a
9896 // partial last column implies the 64x128 left half. Put content no
9897 // reference holds (a fresh smooth ramp) in exactly those two bands of an
9898 // inter frame and the encoder codes those forced halves INTRA.
9899 if bw.max(bh) == 128 {
9900 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
9901 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
9902 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
9903 // palette_syntax`), so a 128-root half consumes no palette syntax and
9904 // a screen-content frame's half is syntactically identical to the
9905 // non-screen one this arm already decodes byte-exact.
9906 if coeff_trace_on() {
9907 // lane-t900 r16: which decode-order frame this arm fires in --
9908 // interleaved with the `EC_COEFF_FRAME` markers, this is what
9909 // proves the hit is counted out of a frame that compares exact
9910 // (class `counter-from-refused-stream`).
9911 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
9912 }
9913 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
9914 let res = decode_block_128rect(
9915 dec,
9916 cdfs,
9917 neighbours,
9918 (r, c),
9919 bw,
9920 bh,
9921 y,
9922 u,
9923 v,
9924 base_q_idx,
9925 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9926 allow_screen_content_tools,
9927 fctx.tx_select_inter.with(std::cell::Cell::get),
9928 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9929 );
9930 fctx.intra_in_inter_mode.with(|c| c.set(None));
9931 return res;
9932 }
9933 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
9934 if crate::envflags::env_flag!("EC_OBMCREC") {
9935 eprintln!(
9936 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
9937 );
9938 }
9939 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
9940 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
9941 // can arrive here are enumerated against the measured block-shape
9942 // census ([`INTER_BLOCK_SHAPES`]) by
9943 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
9944 // -- every one of them has a row, so this arm names a shape no stream
9945 // has been able to present.
9946 return Err(unsupported(format!(
9947 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
9948 )));
9949 };
9950 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
9951 // screen-content frame ("palette syntax is consumed for square blocks
9952 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
9953 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
9954 // it, while the 2:1 reader inlined further down now codes the same syntax
9955 // itself. A real `--tune-content=screen` inter stream reached this refusal
9956 // on 8x16 / 16x8 strips (gate
9957 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
9958 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
9959 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
9960 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
9961 // luma/chroma transform tables, the per-unit split walk and the strip's
9962 // own neighbour records). The ONLY difference on an inter frame is the
9963 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
9964 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
9965 // this caller already read. `tx_cat` above is the same category those
9966 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
9967 // `decode_block_rect64`), asserted here so a future shape cannot drift.
9968 if bw.max(bh) == 4 * bw.min(bh) {
9969 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
9970 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
9971 let res = if bw.max(bh) == 64 {
9972 decode_block_rect64(
9973 dec,
9974 cdfs,
9975 neighbours,
9976 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
9977 bw,
9978 bh,
9979 y,
9980 u,
9981 v,
9982 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9983 allow_screen_content_tools,
9984 base_q_idx,
9985 fctx.tx_select_inter.with(std::cell::Cell::get),
9986 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9987 )
9988 } else {
9989 decode_block_rect4(
9990 dec,
9991 cdfs,
9992 neighbours,
9993 (mi_r, mi_c),
9994 bw,
9995 bh,
9996 None,
9997 y,
9998 u,
9999 v,
10000 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10001 allow_screen_content_tools,
10002 base_q_idx,
10003 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10004 )
10005 .map(|_| ())
10006 };
10007 fctx.intra_in_inter_mode.with(|c| c.set(None));
10008 res?;
10009 let shape = match (bw, bh) {
10010 (64, 16) => 0,
10011 (16, 64) => 1,
10012 (32, 8) => 2,
10013 _ => 3,
10014 };
10015 hit_do! {
10016 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10017 let mut v = h.get();
10018 v[shape] += 1;
10019 h.set(v);
10020 });
10021 }
10022 return Ok(());
10023 }
10024 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10025 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10026 // own, so a cross-decoder bisection could only see the block's first
10027 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10028 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10029 if step_trace {
10030 eprintln!(
10031 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10032 dec.debug_state().0
10033 );
10034 }
10035 if mode >= 13 {
10036 return Err(unsupported(
10037 "an intra mode this decoder does not code (round 2)",
10038 ));
10039 }
10040 // lane-angleinter (merged on main for the square intra-in-inter arm):
10041 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10042 // directional predictor; this arm refused a nonzero one before the merge.
10043 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10044 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10045 } else {
10046 0
10047 };
10048 if angle_delta_y != 0 {
10049 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10050 }
10051 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10052 // superblock-level strip reads the no-CFL alphabet -- the same split
10053 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10054 let cfl_allowed = bw.max(bh) <= 32;
10055 let uv_mode = if cfl_allowed {
10056 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10057 } else {
10058 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10059 };
10060 if step_trace {
10061 eprintln!(
10062 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10063 u8::from(cfl_allowed),
10064 dec.debug_state().0
10065 );
10066 }
10067 if (9..=12).contains(&uv_mode) {
10068 hit!(SMOOTH_UV_HITS);
10069 }
10070 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10071 Some(read_cfl_alphas(dec, cdfs))
10072 } else {
10073 None
10074 };
10075 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10076 DC_PRED
10077 } else {
10078 uv_mode
10079 };
10080 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10081 hit!(DIRECTIONAL_UV_HITS);
10082 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10083 } else {
10084 0
10085 };
10086 if angle_delta_uv != 0 {
10087 hit!(UV_ANGLE_DELTA_HITS);
10088 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10089 }
10090 // `read_palette_mode_info` (spec 5.11.13), in the position
10091 // `read_intra_block_mode_info` writes it: after the chroma mode and
10092 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10093 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10094 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10095 // skipping the syntax here desynced the tile at the strip's own symbol.
10096 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10097 // context and colour cache at its own mi position, and the two
10098 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10099 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10100 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10101 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10102 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10103 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10104 if allow_screen_content_tools
10105 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10106 {
10107 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10108 let use_palette_y =
10109 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10110 if use_palette_y {
10111 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10112 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10113 }
10114 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10115 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10116 let use_palette_uv =
10117 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10118 if crate::envflags::env_flag!("EC_PALSYN") {
10119 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);
10120 }
10121 if use_palette_uv {
10122 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10123 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10124 palette_uv_pending = Some((n, u_colors, v_colors));
10125 }
10126 }
10127 // lane-fiinter (merged on main for the square intra-in-inter arm):
10128 // `read_filter_intra_mode_info` is the tail of
10129 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10130 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10131 // 2:1 strips with both sides <= 32 -- their own CDF rows
10132 // ([`filter_intra_size_class_rect`]).
10133 let mut filter_intra = None;
10134 if mode == DC_PRED
10135 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10136 // `av1_filter_intra_allowed` excludes a palette-Y block.
10137 && palette_y_pending.is_none()
10138 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10139 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10140 {
10141 hit!(FILTER_INTRA_HITS);
10142 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10143 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10144 }
10145 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10146 let palette_y = palette_y_pending.map(|(n, colors)| {
10147 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
10148 hit!(PALETTE_HITS);
10149 hit!(PALETTE_RECT_HITS);
10150 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10151 PaletteY { size: n, colors, map }
10152 });
10153 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10154 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10155 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
10156 hit!(PALETTE_UV_HITS);
10157 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10158 PaletteUv { size: n, u_colors, v_colors, map }
10159 });
10160 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10161 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10162 // chroma ones -- [`decode_block_rect`]'s own pair.
10163 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10164 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10165 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10166 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10167 // one exactly as [`decode_leaf8`] already does (class
10168 // context-read-from-one-cell).
10169 let coarse_pair = neighbours.modes_above_left(r, c);
10170 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10171 if (nb_above_mode, nb_left_mode) != coarse_pair {
10172 hit!(EDGE_FILTER_MI_FIX_HITS);
10173 }
10174 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10175 if smooth_neighbor {
10176 hit!(SMOOTH_LUMA_HITS);
10177 }
10178 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10179 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10180 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
10181 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
10182 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10183 let d = match tx_cat {
10184 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10185 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10186 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10187 };
10188 if step_trace {
10189 eprintln!(
10190 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10191 dec.debug_state().0
10192 );
10193 }
10194 d
10195 } else {
10196 0
10197 };
10198 if depth != 0 {
10199 hit!(TX_DEPTH_HITS);
10200 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10201 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10202 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10203 hit_do! {
10204 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10205 let mut v = h.get();
10206 v[depth.min(2)] += 1;
10207 h.set(v);
10208 });
10209 }
10210 }
10211 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10212 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10213 // the two are indistinguishable when the diagnostic fires on splits alone.
10214 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10215 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10216 }
10217 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10218 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10219 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10220 // of an inter frame, intra ones included -- with the skip term 0 it
10221 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10222 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10223 // wrote neither, so the next block's var-tx `txfm_partition` context read
10224 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10225 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10226 // mi(16,0) and desyncing the tile at that symbol.
10227 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10228 let modes = RectStripModes {
10229 skip,
10230 mode,
10231 angle_delta_y,
10232 uv_predict_mode,
10233 angle_delta_uv,
10234 alpha,
10235 filter_intra,
10236 smooth_neighbor,
10237 smooth_neighbor_uv,
10238 palette_y: palette_y
10239 .as_ref()
10240 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10241 palette_uv: palette_uv.as_ref().map(|p| {
10242 (
10243 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10244 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10245 )
10246 }),
10247 };
10248 decode_rect_split(
10249 dec,
10250 cdfs,
10251 neighbours,
10252 (mi_r, mi_c),
10253 bw,
10254 bh,
10255 tx_w,
10256 tx_h,
10257 &modes,
10258 y,
10259 u,
10260 v,
10261 base_q_idx,
10262 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10263 )?;
10264 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
10265 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
10266 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
10267 // left column over its height. This arm wrote neither before lane-intrasplit
10268 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
10269 // context across the strip's footprint.
10270 for i in 0..bw / MI {
10271 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10272 *cell = tx_w as u8;
10273 }
10274 }
10275 for i in 0..bh / MI {
10276 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10277 *cell = tx_h as u8;
10278 }
10279 }
10280 // The strip's own palette state into the mi-granular neighbour bands, so
10281 // the next block's colour cache and `palette_y_mode` context are libaom's.
10282 record_strip_palette(
10283 neighbours,
10284 (mi_r, mi_c),
10285 bw,
10286 bh,
10287 palette_y.as_ref().map_or(0, |p| p.size),
10288 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
10289 palette_uv.as_ref().map_or(0, |p| p.size),
10290 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
10291 );
10292 let class = match bw.max(bh) {
10293 64 => 0,
10294 32 => 1,
10295 _ => 2,
10296 };
10297 hit_do! {
10298 INTRA_RECT_IN_INTER_HITS.with(|h| {
10299 let mut v = h.get();
10300 v[class] += 1;
10301 h.set(v);
10302 });
10303 }
10304 Ok(())
10305}
10306
10307/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
10308/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
10309/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
10310/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
10311/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
10312/// has no rectangular-transform coefficient reader, and a chroma plane here
10313/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
10314/// with no depth-based square-tiling escape the way luma's own resolved
10315/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
10316/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
10317#[allow(clippy::too_many_arguments)]
10318fn decode_block_rect(
10319 dec: &mut SymbolDecoder,
10320 cdfs: &mut Cdfs,
10321 neighbours: &mut Neighbours,
10322 at: (usize, usize),
10323 bw: usize,
10324 bh: usize,
10325 y: &mut PlaneBuf<'static>,
10326 u: &mut PlaneBuf<'static>,
10327 v: &mut PlaneBuf<'static>,
10328 enable_filter_intra: bool,
10329 allow_screen_content_tools: bool,
10330 base_q_idx: u8,
10331 tx_select: bool,
10332 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10333) -> Result<()> {
10334 let (r, c) = at;
10335 let (px, py) = (c * SUB, r * SUB);
10336 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10337 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10338 let palette_uv_cache = neighbours.palette_uv_cache(at);
10339 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10340 read_intra_mode_rect(
10341 dec,
10342 cdfs,
10343 nb_above_mode,
10344 nb_left_mode,
10345 true,
10346 true,
10347 bw,
10348 bh,
10349 enable_filter_intra,
10350 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10351 allow_screen_content_tools,
10352 Some((palette_ctx, &palette_cache)),
10353 &palette_uv_cache,
10354 r * (SUB / MI),
10355 c * (SUB / MI), fctx,
10356 )?;
10357 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10358 if smooth_neighbor {
10359 hit!(SMOOTH_LUMA_HITS);
10360 }
10361 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
10362 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
10363 // `uv_mode`, not the luma one.
10364 let smooth_neighbor_uv =
10365 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10366 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
10367 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
10368 // rectangle just as happily), so a `use_filter_intra` strip at this level
10369 // predicts instead of refusing. The below-16x16 leaf arm
10370 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
10371 if filter_intra.is_some() {
10372 hit!(FILTER_INTRA_RECT_HITS);
10373 }
10374 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10375 DC_PRED
10376 } else {
10377 uv_mode
10378 };
10379 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10380 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
10381 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
10382 // one did not, so with `--enable-tx-size-search=0` -- which several gate
10383 // recipes use -- the decoder consumed a symbol the encoder never wrote and
10384 // desynced the tile from that point on. That is why both strips of the
10385 // pinned HORZ quadrant were wrong from their very first pixel, and why our
10386 // range after the read equalled the oracle's range for the whole block.
10387 let depth = if tx_select {
10388 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10389 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10390 // the 16x4 intra-in-inter strips already do); the key frame's
10391 // deblock-grid approximation is only right where those bands were never
10392 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10393 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10394 // `tx_size_cat2` row 1 where libaom reads row 2.
10395 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10396 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10397 } else {
10398 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10399 };
10400 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10401 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10402 eprintln!(
10403 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10404 dec.debug_state().0
10405 );
10406 }
10407 d
10408 } else {
10409 0
10410 };
10411 if depth != 0 {
10412 hit!(TX_DEPTH_HITS);
10413 // lane-rectsplit r1: a split transform is predicted and reconstructed
10414 // per transform unit, each unit taking its edges from the previous
10415 // unit's reconstruction inside this same strip (spec 5.11.36) --
10416 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10417 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10418 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10419 eprintln!(
10420 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10421 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10422 angle_y={angle_delta_y}"
10423 );
10424 }
10425 let modes = RectStripModes {
10426 skip,
10427 mode,
10428 angle_delta_y,
10429 uv_predict_mode,
10430 angle_delta_uv,
10431 alpha,
10432 filter_intra,
10433 smooth_neighbor,
10434 smooth_neighbor_uv,
10435 palette_y: palette_y
10436 .as_ref()
10437 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10438 palette_uv: palette_uv.as_ref().map(|p| {
10439 (
10440 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10441 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10442 )
10443 }),
10444 };
10445 if palette_y.is_some() || palette_uv.is_some() {
10446 hit!(PALETTE_SPLIT_TX_HITS);
10447 }
10448 decode_rect_split(
10449 dec,
10450 cdfs,
10451 neighbours,
10452 (mi_r, mi_c),
10453 bw,
10454 bh,
10455 tx_w,
10456 tx_h,
10457 &modes,
10458 y,
10459 u,
10460 v,
10461 base_q_idx,
10462 reduced_tx_set, fctx,
10463 )?;
10464 // This early return skips this fn's own tail, so the palette
10465 // neighbour state has to be stamped HERE too: without it a split-tx
10466 // strip left the above/left palette arrays holding a DEAD block's
10467 // colours, and the next block's colour cache
10468 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
10469 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
10470 // and only those pixels were wrong (lane-palette2 r10).
10471 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10472 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10473 let (puv_size, puv_colors) =
10474 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10475 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10476 hit!(RECT_PARTITION_HITS);
10477 return Ok(());
10478 }
10479 let (tx_w, tx_h) = (bw, bh);
10480 let (cpx, cpy) = (px / 2, py / 2);
10481 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10482 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10483 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10484 let (rng, _) = dec.debug_state();
10485 eprintln!(
10486 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
10487 skip={} tx={depth} rng={rng}",
10488 skip as i32
10489 );
10490 }
10491 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
10492 // block's prediction is the reconstructed colour-index map, set fresh
10493 // right before each `reconstruct_rect` call below (lane-palette2 r4).
10494 if let Some(ref pyv) = palette_y {
10495 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10496 set_palette_pred(buf, fctx);
10497 }
10498 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10499 (
10500 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10501 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10502 )
10503 });
10504 if skip {
10505 push_intra_rect(0,
10506 px,
10507 py,
10508 bw,
10509 bh,
10510 mode,
10511 angle_delta_y,
10512 reach,
10513 &ZERO_RESIDUAL[..bw * bh],
10514 None,
10515 filter_intra,
10516 smooth_neighbor, fctx,
10517 );
10518 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10519 if let Some((ub, _)) = &palette_uv_bufs {
10520 set_palette_pred(ub.clone(), fctx);
10521 }
10522 push_intra_rect(1,
10523 cpx,
10524 cpy,
10525 chroma_w,
10526 chroma_h,
10527 uv_predict_mode,
10528 angle_delta_uv,
10529 reach,
10530 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10531 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10532 None,
10533 smooth_neighbor_uv, fctx,
10534 );
10535 if let Some((_, vb)) = &palette_uv_bufs {
10536 set_palette_pred(vb.clone(), fctx);
10537 }
10538 push_intra_rect(2,
10539 cpx,
10540 cpy,
10541 chroma_w,
10542 chroma_h,
10543 uv_predict_mode,
10544 angle_delta_uv,
10545 reach,
10546 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10547 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10548 None,
10549 smooth_neighbor_uv, fctx,
10550 );
10551 neighbours.record_rect(
10552 at,
10553 bw,
10554 bh,
10555 mode,
10556 uv_predict_mode,
10557 &[
10558 &ZERO_RESIDUAL[..bw * bh],
10559 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10560 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10561 ],
10562 );
10563 } else {
10564 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
10565 // reduces both size pairs to their square-up CDF sets
10566 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
10567 // doc comments); the scan order and 2D context tables are the real
10568 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
10569 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
10570 (&SCAN_32X16, &SCAN_16X8)
10571 } else {
10572 (&SCAN_16X32, &SCAN_8X16)
10573 };
10574 // lane-rectwire r3: real coefficients desync a pixel-exact gate
10575 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
10576 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
10577 // pixel (not a subtle context-table off-by-one), while the sibling
10578 // non-rect quadrants of the same frame match. Range-ladder bisection
10579 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
10580 // but the intra key-frame path has no traced symbol between the
10581 // partition read and the first coefficient block (mode/skip/tx_depth
10582 // reads are all untraced in libaom's decodeframe.c intra path, unlike
10583 // the inter EC_TRACE_MODE this round added), so a same-length range
10584 // comparison wasn't reachable within budget -- see
10585 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10586 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10587 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10588 // libaom and match). lane-rectwire r4: range-ladder against the
10589 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10590 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10591 // both confirmed in sync -- rng=58692 on both sides right after
10592 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10593 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10594 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10595 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
10596 // its own tx_size read) unless oracle's tx symbol is a near-certainty
10597 // CDF that barely narrows the range -- i.e. this decoder's
10598 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
10599 // a 32x16/16x32 strip is the first diverging symbol, not the
10600 // coefficient-context math r3 already cleared. Not confirmed byte-
10601 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
10602 // `read_tx_size`'s own rng, not attempted this round -- budget), so
10603 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
10604 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
10605 // it unconditionally where both square paths gate on `tx_select`. With
10606 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
10607 // decoder consumed one that was never there.
10608 {
10609 let around = neighbours.around_rect(at, bw, bh);
10610 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
10611 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10612 dec,
10613 &mut luma_coding,
10614 luma_scan,
10615 bw,
10616 bh,
10617 0,
10618 dc_sign_ctx(around[0].2),
10619 TxType::DctDct,
10620 )?;
10621 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10622 let (rng, _) = dec.debug_state();
10623 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10624 }
10625 let luma_residual = dequant_and_inverse_typed_wh(
10626 &luma_levels,
10627 bw,
10628 bh,
10629 crate::decode::bit_depth(fctx),
10630 block_q_idx(fctx),
10631 plane_q_delta(0, fctx).0,
10632 plane_q_delta(0, fctx).1,
10633 luma_tx_type,
10634 );
10635 push_intra_rect(0,
10636 px,
10637 py,
10638 bw,
10639 bh,
10640 mode,
10641 angle_delta_y,
10642 reach,
10643 &luma_residual,
10644 None,
10645 filter_intra,
10646 smooth_neighbor, fctx,
10647 );
10648 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10649 if let Some((ub, _)) = &palette_uv_bufs {
10650 set_palette_pred(ub.clone(), fctx);
10651 }
10652 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10653 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10654 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10655 let (u_levels, u_tx_type) = read_coeffs_rect(
10656 dec,
10657 &mut u_coding,
10658 chroma_scan,
10659 chroma_w,
10660 chroma_h,
10661 u_skip_ctx,
10662 dc_sign_ctx(around[1].2),
10663 u_default_tx,
10664 )?;
10665 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10666 let (rng, _) = dec.debug_state();
10667 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10668 }
10669 let u_residual = dequant_and_inverse_typed_wh(
10670 &u_levels,
10671 chroma_w,
10672 chroma_h,
10673 crate::decode::bit_depth(fctx),
10674 block_q_idx(fctx),
10675 plane_q_delta(1, fctx).0,
10676 plane_q_delta(1, fctx).1,
10677 u_tx_type,
10678 );
10679 push_intra_rect(1,
10680 cpx,
10681 cpy,
10682 chroma_w,
10683 chroma_h,
10684 uv_predict_mode,
10685 angle_delta_uv,
10686 reach,
10687 &u_residual,
10688 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10689 None,
10690 smooth_neighbor_uv, fctx,
10691 );
10692 if let Some((_, vb)) = &palette_uv_bufs {
10693 set_palette_pred(vb.clone(), fctx);
10694 }
10695 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10696 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10697 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10698 let (v_levels, v_tx_type) = read_coeffs_rect(
10699 dec,
10700 &mut v_coding,
10701 chroma_scan,
10702 chroma_w,
10703 chroma_h,
10704 v_skip_ctx,
10705 dc_sign_ctx(around[2].2),
10706 v_default_tx,
10707 )?;
10708 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10709 let (rng, _) = dec.debug_state();
10710 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10711 }
10712 let v_residual = dequant_and_inverse_typed_wh(
10713 &v_levels,
10714 chroma_w,
10715 chroma_h,
10716 crate::decode::bit_depth(fctx),
10717 block_q_idx(fctx),
10718 plane_q_delta(2, fctx).0,
10719 plane_q_delta(2, fctx).1,
10720 v_tx_type,
10721 );
10722 push_intra_rect(2,
10723 cpx,
10724 cpy,
10725 chroma_w,
10726 chroma_h,
10727 uv_predict_mode,
10728 angle_delta_uv,
10729 reach,
10730 &v_residual,
10731 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10732 None,
10733 smooth_neighbor_uv, fctx,
10734 );
10735 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
10736 hit!(RECT_COEFF_HITS);
10737 }
10738 }
10739 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10740 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10741 let (puv_size, puv_colors) =
10742 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10743 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10744 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10745 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10746 hit!(RECT_PARTITION_HITS);
10747 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10748 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
10749 }
10750 Ok(())
10751}
10752
10753/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
10754/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
10755/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
10756/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
10757/// the second strip of a HORZ/VERT split sits offset by half the 16x16
10758/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
10759/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
10760/// previous strip is directly above (same column, `mi_h` rows up) or
10761/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
10762/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
10763/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
10764/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
10765/// this strip's real position, never the coarse `record_rect` (which the
10766/// caller uses once, after both strips, exactly like the `VERT_B` arm next
10767/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
10768/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
10769/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
10770/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
10771#[allow(clippy::too_many_arguments)]
10772fn decode_leaf_rect(
10773 dec: &mut SymbolDecoder,
10774 cdfs: &mut Cdfs,
10775 neighbours: &mut Neighbours,
10776 outer_at: (usize, usize),
10777 leaf_mi: (usize, usize),
10778 bw: usize,
10779 bh: usize,
10780 prev_leaf: Option<((usize, usize), usize)>,
10781 y: &mut PlaneBuf<'static>,
10782 u: &mut PlaneBuf<'static>,
10783 v: &mut PlaneBuf<'static>,
10784 enable_filter_intra: bool,
10785 allow_screen_content_tools: bool,
10786 base_q_idx: u8,
10787 tx_select: bool,
10788 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10789) -> Result<usize> {
10790 let _ = base_q_idx;
10791 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10792 eprintln!(
10793 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
10794 dec.debug_state().0
10795 );
10796 }
10797 let (r, c) = outer_at;
10798 let mut above_mode = neighbours.above_mode[c];
10799 let mut left_mode = neighbours.left_mode[r];
10800 let (mi_w, mi_h) = (bw / MI, bh / MI);
10801 if let Some(((pr, pc), pmode)) = prev_leaf {
10802 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
10803 above_mode = pmode;
10804 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
10805 left_mode = pmode;
10806 }
10807 }
10808 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
10809 // cannot hold the modes a split (or a pair of strips) leaves behind, so
10810 // when the map holds the block at exactly this strip's above/left mi it
10811 // is the neighbour libaom's `above_mi`/`left_mi` reads.
10812 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
10813 // availability-correct -- four 16x8 strips share one coarse 16x16
10814 // `left_mode` cell too, so the fallback must not stand in for an absent
10815 // tile-edge neighbour.
10816 let (above_mode, left_mode) =
10817 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
10818 let smooth_neighbor =
10819 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10820 if smooth_neighbor {
10821 hit!(SMOOTH_LUMA_HITS);
10822 }
10823 // The palette-Y mode CDF row is picked by the neighbours' palette use
10824 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
10825 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
10826 // a palette narrows the wrong interval and desyncs the tile even when the
10827 // decoded bit is the same. The cell is the 16px-SUB cell containing the
10828 // leaf (the palette neighbour arrays have no finer granularity).
10829 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
10830 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
10831 // exclusion and the neighbour palette lookup itself are mi-granular
10832 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
10833 let pal_at = leaf_mi;
10834 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
10835 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
10836 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10837 read_intra_mode_rect(
10838 dec,
10839 cdfs,
10840 above_mode,
10841 left_mode,
10842 true,
10843 true,
10844 bw,
10845 bh,
10846 enable_filter_intra,
10847 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
10848 allow_screen_content_tools,
10849 Some((palette_ctx, &palette_cache)),
10850 &palette_uv_cache,
10851 leaf_mi.0,
10852 leaf_mi.1, fctx,
10853 )?;
10854 // lane-kf900 r4: palette prediction on this shape, the same colour-index
10855 // map -> base colours buffer [`decode_block_rect`] hands each
10856 // `reconstruct_rect` through [`set_palette_pred`].
10857 if palette_y.is_some() || palette_uv.is_some() {
10858 hit!(RECT4_PALETTE_HITS);
10859 }
10860 let palette_y_buf: Option<Vec<u16>> = palette_y
10861 .as_ref()
10862 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
10863 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
10864 (
10865 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10866 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10867 )
10868 });
10869 let (pal_y_size, pal_y_colors) =
10870 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10871 let (pal_uv_size, pal_uv_colors) =
10872 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10873 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10874 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
10875 }
10876 if filter_intra.is_some() {
10877 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
10878 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
10879 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
10880 // below already makes; this refusal was square-only prose.
10881 hit!(FILTER_INTRA_RECT_HITS);
10882 hit!(FILTER_INTRA_RECT_SUB16_HITS);
10883 }
10884 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
10885 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
10886 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
10887 // a constant `false`.
10888 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
10889 let depth = if tx_select {
10890 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
10891 // every other rect reader now does -- a no-op on a key frame.
10892 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10893 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
10894 } else {
10895 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
10896 };
10897 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
10898 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
10899 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
10900 // count (3), different CDF row: a wrong-table read of a real symbol,
10901 // the class that cost lane-rectsplit r1 its 64x32 depth.
10902 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
10903 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
10904 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
10905 // function also decodes) sit at depth 2, so they read
10906 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
10907 // while `tx_size_cat2` belongs to the 32-level shapes
10908 // ([`decode_block_rect`]). Both tables carry three symbols, so the
10909 // wrong one decodes a plausible depth from the wrong probabilities:
10910 // the range diverges silently at the first such leaf and every later
10911 // symbol in the tile is read from the wrong place (class
10912 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
10913 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
10914 } else {
10915 0
10916 };
10917 if depth != 0 {
10918 // The same per-transform-unit walk the bigger strips take
10919 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
10920 // depth 2), addressed at this leaf's own mi position.
10921 hit!(TX_DEPTH_HITS);
10922 hit!(SUB16_SPLIT_HITS);
10923 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10924 let modes = RectStripModes {
10925 skip,
10926 mode,
10927 angle_delta_y,
10928 uv_predict_mode,
10929 angle_delta_uv,
10930 alpha,
10931 filter_intra,
10932 smooth_neighbor,
10933 // lane-rectsplitx r3: the split arm hard-coded `false` here while
10934 // the unsplit arm below passes the real neighbour answer -- chroma
10935 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
10936 smooth_neighbor_uv,
10937 palette_y: palette_y_buf.clone(),
10938 palette_uv: palette_uv_bufs.clone(),
10939 };
10940 if palette_y.is_some() || palette_uv.is_some() {
10941 hit!(PALETTE_SPLIT_TX_HITS);
10942 }
10943 decode_rect_split(
10944 dec,
10945 cdfs,
10946 neighbours,
10947 leaf_mi,
10948 bw,
10949 bh,
10950 tx_w,
10951 tx_h,
10952 &modes,
10953 y,
10954 u,
10955 v,
10956 base_q_idx,
10957 reduced_tx_set, fctx,
10958 )?;
10959 record_strip_palette(
10960 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10961 );
10962 return Ok(mode);
10963 }
10964 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
10965 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10966 let (cpx, cpy) = (px / 2, py / 2);
10967 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10968 let (luma_levels, u_levels, v_levels);
10969 if skip {
10970 luma_levels = Grid::Zero(bw * bh);
10971 u_levels = Grid::Zero(chroma_w * chroma_h);
10972 v_levels = Grid::Zero(chroma_w * chroma_h);
10973 if let Some(b) = &palette_y_buf {
10974 set_palette_pred(b.clone(), fctx);
10975 }
10976 push_intra_rect(0,
10977 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
10978 smooth_neighbor, fctx,
10979 );
10980 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10981 if let Some((ub, _)) = &palette_uv_bufs {
10982 set_palette_pred(ub.clone(), fctx);
10983 }
10984 push_intra_rect(1,
10985 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
10986 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
10987 );
10988 if let Some((_, vb)) = &palette_uv_bufs {
10989 set_palette_pred(vb.clone(), fctx);
10990 }
10991 push_intra_rect(2,
10992 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
10993 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
10994 );
10995 } else {
10996 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
10997 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
10998 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
10999 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
11000 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
11001 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
11002 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
11003 (&SCAN_16X8, &SCAN_8X4)
11004 } else {
11005 (&SCAN_8X16, &SCAN_4X8)
11006 };
11007 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
11008 let luma_set = if reduced_tx_set {
11009 TxbSet::LumaRect16x8
11010 } else {
11011 TxbSet::LumaRect16x8Set1
11012 };
11013 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
11014 let (l_levels, luma_tx_type) = read_coeffs_rect(
11015 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
11016 )?;
11017 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11018 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
11019 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
11020 }
11021 luma_levels = l_levels;
11022 let luma_residual = dequant_and_inverse_typed_wh(
11023 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
11024 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
11025 );
11026 if let Some(b) = &palette_y_buf {
11027 set_palette_pred(b.clone(), fctx);
11028 }
11029 push_intra_rect(0,
11030 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
11031 smooth_neighbor, fctx,
11032 );
11033 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11034 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11035 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11036 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11037 let (u_l, u_tx_type) = read_coeffs_rect(
11038 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11039 dc_sign_ctx(around[1].2), u_default_tx,
11040 )?;
11041 u_levels = u_l;
11042 let u_residual = dequant_and_inverse_typed_wh(
11043 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11044 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
11045 );
11046 if let Some((ub, _)) = &palette_uv_bufs {
11047 set_palette_pred(ub.clone(), fctx);
11048 }
11049 push_intra_rect(1,
11050 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
11051 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11052 );
11053 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11054 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11055 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11056 let (v_l, v_tx_type) = read_coeffs_rect(
11057 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11058 dc_sign_ctx(around[2].2), v_default_tx,
11059 )?;
11060 v_levels = v_l;
11061 let v_residual = dequant_and_inverse_typed_wh(
11062 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11063 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
11064 );
11065 if let Some((_, vb)) = &palette_uv_bufs {
11066 set_palette_pred(vb.clone(), fctx);
11067 }
11068 push_intra_rect(2,
11069 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
11070 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11071 );
11072 hit!(RECT_LEAF_COEFF_HITS);
11073 }
11074 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11075 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
11076 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11077 // The leaf's own palette state (`0` clears, as this site always did
11078 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
11079 // AXIS only until the pair's closing leaf: the coarse cell holds one
11080 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
11081 // real left neighbour leaf 1 reads (lane-kf900 r4).
11082 record_strip_palette(
11083 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11084 );
11085 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
11086 // rows -- record the whole span, not one cell.
11087 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
11088 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
11089 Ok(mode)
11090}
11091
11092/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
11093/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
11094/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
11095/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
11096/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
11097/// strip's mode so this one's mode context sees its true above/left
11098/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
11099///
11100/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
11101/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
11102/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
11103/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
11104/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
11105/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
11106/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
11107///
11108/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
11109/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
11110/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
11111/// unexamined.
11112#[allow(clippy::too_many_arguments)]
11113fn decode_block_rect4(
11114 dec: &mut SymbolDecoder,
11115 cdfs: &mut Cdfs,
11116 neighbours: &mut Neighbours,
11117 strip_mi: (usize, usize),
11118 bw: usize,
11119 bh: usize,
11120 prev_strip: Option<((usize, usize), usize)>,
11121 y: &mut PlaneBuf<'static>,
11122 u: &mut PlaneBuf<'static>,
11123 v: &mut PlaneBuf<'static>,
11124 enable_filter_intra: bool,
11125 allow_screen_content_tools: bool,
11126 base_q_idx: u8,
11127 tx_select: bool, fctx: &crate::decode::FrameCtx,
11128) -> Result<(usize, usize)> {
11129 let _ = base_q_idx;
11130 let (mi_r, mi_c) = strip_mi;
11131 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11132 let (mi_w, mi_h) = (bw / MI, bh / MI);
11133 let mut above_mode = neighbours.above_mode[c];
11134 let mut left_mode = neighbours.left_mode[r];
11135 if let Some(((pr, pc), pmode)) = prev_strip {
11136 if pc == mi_c && mi_r == pr + mi_h {
11137 above_mode = pmode;
11138 } else if pr == mi_r && mi_c == pc + mi_w {
11139 left_mode = pmode;
11140 }
11141 }
11142 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
11143 // availability-correct neighbour modes (see
11144 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
11145 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
11146 let (above_mode, left_mode) =
11147 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
11148 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
11149 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
11150 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
11151 // wrong interval, so a screen-content tile desynced at the first strip
11152 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
11153 let pal_at = (mi_r, mi_c);
11154 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11155 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11156 let (
11157 skip,
11158 mode,
11159 angle_delta_y,
11160 uv_mode,
11161 angle_delta_uv,
11162 alpha,
11163 filter_intra,
11164 palette_y,
11165 palette_uv,
11166 ) = read_intra_mode_rect(
11167 dec,
11168 cdfs,
11169 above_mode,
11170 left_mode,
11171 true,
11172 true,
11173 bw,
11174 bh,
11175 enable_filter_intra,
11176 neighbours.skip_txfm_ctx(mi_r, mi_c),
11177 allow_screen_content_tools,
11178 Some((palette_ctx, &palette_cache)),
11179 &palette_uv_cache,
11180 mi_r,
11181 mi_c, fctx,
11182 )?;
11183 // lane-kf900 r4: palette prediction on this shape, exactly as
11184 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
11185 // mapped through the base colours IS the prediction (it reads no edge
11186 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
11187 if palette_y.is_some() || palette_uv.is_some() {
11188 hit!(RECT4_PALETTE_HITS);
11189 }
11190 let palette_y_buf: Option<Vec<u16>> = palette_y
11191 .as_ref()
11192 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11193 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11194 (
11195 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11196 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11197 )
11198 });
11199 let (pal_y_size, pal_y_colors) =
11200 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11201 let (pal_uv_size, pal_uv_colors) =
11202 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11203 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11204 if smooth_neighbor {
11205 hit!(SMOOTH_LUMA_HITS);
11206 }
11207 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
11208 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
11209 // `r * (SUB / MI)` names a different mi column and the chroma
11210 // edge-filter strength was read from the wrong neighbour (measured:
11211 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
11212 // with luma bit-exact).
11213 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11214 if filter_intra.is_some() {
11215 hit!(FILTER_INTRA_RECT_HITS);
11216 if bw > bh {
11217 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
11218 } else {
11219 hit!(FILTER_INTRA_RECT4_VERT_HITS);
11220 }
11221 }
11222 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11223 DC_PRED
11224 } else {
11225 uv_mode
11226 };
11227 let depth = if tx_select {
11228 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11229 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11230 // the 16x4 intra-in-inter strips already do); the key frame's
11231 // deblock-grid approximation is only right where those bands were never
11232 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11233 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11234 // `tx_size_cat2` row 1 where libaom reads row 2.
11235 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11236 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11237 } else {
11238 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11239 };
11240 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11241 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11242 eprintln!(
11243 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11244 dec.debug_state().0
11245 );
11246 }
11247 d
11248 } else {
11249 0
11250 };
11251 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11252 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11253 publish_txfm_bands_if_in_inter(
11254 neighbours,
11255 (mi_r, mi_c),
11256 depth_to_tx_wh(bw, bh, depth),
11257 (bw, bh), fctx,
11258 );
11259 if depth != 0 {
11260 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
11261 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
11262 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
11263 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
11264 // both interleave in every real stream.
11265 hit!(TX_DEPTH_HITS);
11266 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11267 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
11268 // predicted -- depth 1 fires FIRST in every attempt that splits at
11269 // all, so a depth-2-only lift could never be gated. The r1 mismatch
11270 // was never the rect unit: it was the neighbour MODE the strip reads
11271 // (see `modes_above_left_mi`).
11272 let which = if depth == 1 {
11273 &RECT4_SPLIT_DEPTH1_HITS
11274 } else {
11275 &RECT4_SPLIT_DEPTH2_HITS
11276 };
11277 hit_do! { which.with(|c| c.set(c.get() + 1)); }
11278 let modes = RectStripModes {
11279 skip,
11280 mode,
11281 angle_delta_y,
11282 uv_predict_mode,
11283 angle_delta_uv,
11284 alpha,
11285 filter_intra,
11286 smooth_neighbor,
11287 smooth_neighbor_uv,
11288 palette_y: palette_y_buf.clone(),
11289 palette_uv: palette_uv_bufs.clone(),
11290 };
11291 if palette_y.is_some() || palette_uv.is_some() {
11292 hit!(PALETTE_SPLIT_TX_HITS);
11293 }
11294 decode_rect_split(
11295 dec,
11296 cdfs,
11297 neighbours,
11298 (mi_r, mi_c),
11299 bw,
11300 bh,
11301 tx_w,
11302 tx_h,
11303 &modes,
11304 y,
11305 u,
11306 v,
11307 base_q_idx,
11308 false, fctx,
11309 )?;
11310 record_strip_palette(
11311 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11312 pal_uv_colors,
11313 );
11314 if bw > bh {
11315 hit!(RECT4_32_HORZ_HITS);
11316 } else {
11317 hit!(RECT4_32_VERT_HITS);
11318 }
11319 if !skip {
11320 hit!(RECT4_COEFF_HITS);
11321 }
11322 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11323 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11324 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11325 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11326 // transform size in both TXFM_CONTEXT bands. Without it the next block
11327 // reads the row's stale value.
11328 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11329 return Ok((mode, uv_predict_mode));
11330 }
11331 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
11332 // that is 8 px tall, so each strip stamps every cell it touches and the
11333 // LAST strip wins -- which is the right answer for the block below/right
11334 // of the 32x32, the only reader outside it. Written after this strip's
11335 // own context read above, never before.
11336 for cell in 0..bw.div_ceil(SUB) {
11337 neighbours.above_mode[c + cell] = mode;
11338 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
11339 neighbours.above_side[c + cell] = bw;
11340 }
11341 for cell in 0..bh.div_ceil(SUB) {
11342 neighbours.left_mode[r + cell] = mode;
11343 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
11344 neighbours.left_side[r + cell] = bh;
11345 }
11346 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
11347 // [`decode_leaf_rect`] does (the split arm above records these through
11348 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
11349 // `sub8_mode_row` holding the previous block, and the next 32x32's
11350 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
11351 // fixture).
11352 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
11353 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
11354 let (px, py) = (mi_c * MI, mi_r * MI);
11355 let (cpx, cpy) = (px / 2, py / 2);
11356 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11357 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11358 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
11359 (&SCAN_32X8, &SCAN_16X4)
11360 } else {
11361 (&SCAN_8X32, &SCAN_4X16)
11362 };
11363 let (luma_levels, u_levels, v_levels) = if skip {
11364 (
11365 vec![0i32; bw * bh],
11366 vec![0i32; chroma_w * chroma_h],
11367 vec![0i32; chroma_w * chroma_h],
11368 )
11369 } else {
11370 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11371 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
11372 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11373 dec,
11374 &mut luma_coding,
11375 luma_scan,
11376 bw,
11377 bh,
11378 0,
11379 dc_sign_ctx(around[0].2),
11380 TxType::DctDct,
11381 )?;
11382 let mut planes = Vec::with_capacity(2);
11383 for plane in 1..3 {
11384 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11385 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11386 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11387 let (levels, tx_type) = read_coeffs_rect(
11388 dec,
11389 &mut coding,
11390 chroma_scan,
11391 chroma_w,
11392 chroma_h,
11393 skip_ctx,
11394 dc_sign_ctx(around[plane].2),
11395 default_tx,
11396 )?;
11397 planes.push((levels, tx_type));
11398 }
11399 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11400 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11401 hit!(RECT4_COEFF_HITS);
11402 let luma_residual = dequant_and_inverse_typed_wh(
11403 &luma_levels,
11404 bw,
11405 bh,
11406 crate::decode::bit_depth(fctx),
11407 block_q_idx(fctx),
11408 plane_q_delta(0, fctx).0,
11409 plane_q_delta(0, fctx).1,
11410 luma_tx_type,
11411 );
11412 if let Some(b) = &palette_y_buf {
11413 set_palette_pred(b.clone(), fctx);
11414 }
11415 push_intra_rect(0,
11416 px,
11417 py,
11418 bw,
11419 bh,
11420 mode,
11421 angle_delta_y,
11422 reach,
11423 &luma_residual,
11424 None,
11425 filter_intra,
11426 smooth_neighbor, fctx,
11427 );
11428 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11429 for (plane, _buf, levels, tx_type) in [
11430 (1usize, &mut *u, &u_levels, u_tx_type),
11431 (2, &mut *v, &v_levels, v_tx_type),
11432 ] {
11433 let residual = dequant_and_inverse_typed_wh(
11434 levels,
11435 chroma_w,
11436 chroma_h,
11437 crate::decode::bit_depth(fctx),
11438 block_q_idx(fctx),
11439 plane_q_delta(plane, fctx).0,
11440 plane_q_delta(plane, fctx).1,
11441 tx_type,
11442 );
11443 if let Some((ub, vb)) = &palette_uv_bufs {
11444 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11445 }
11446 push_intra_rect(plane,
11447 cpx,
11448 cpy,
11449 chroma_w,
11450 chroma_h,
11451 uv_predict_mode,
11452 angle_delta_uv,
11453 reach,
11454 &residual,
11455 alpha
11456 .zip(ac)
11457 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11458 None,
11459 smooth_neighbor_uv, fctx,
11460 );
11461 }
11462 neighbours.record_mi_rect(
11463 (mi_r, mi_c),
11464 bw,
11465 bh,
11466 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
11467 );
11468 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11469 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11470 record_strip_palette(
11471 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11472 pal_uv_colors,
11473 );
11474 if bw > bh {
11475 hit!(RECT4_32_HORZ_HITS);
11476 } else {
11477 hit!(RECT4_32_VERT_HITS);
11478 }
11479 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11480 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11481 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11482 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11483 // transform size in both TXFM_CONTEXT bands. Without it the next block
11484 // reads the row's stale value.
11485 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11486 return Ok((mode, uv_predict_mode));
11487 };
11488 if let Some(b) = &palette_y_buf {
11489 set_palette_pred(b.clone(), fctx);
11490 }
11491 push_intra_rect(0,
11492 px,
11493 py,
11494 bw,
11495 bh,
11496 mode,
11497 angle_delta_y,
11498 reach,
11499 &luma_levels,
11500 None,
11501 filter_intra,
11502 smooth_neighbor, fctx,
11503 );
11504 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11505 if let Some((ub, _)) = &palette_uv_bufs {
11506 set_palette_pred(ub.clone(), fctx);
11507 }
11508 push_intra_rect(1,
11509 cpx,
11510 cpy,
11511 chroma_w,
11512 chroma_h,
11513 uv_predict_mode,
11514 angle_delta_uv,
11515 reach,
11516 &u_levels,
11517 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11518 None,
11519 smooth_neighbor_uv, fctx,
11520 );
11521 if let Some((_, vb)) = &palette_uv_bufs {
11522 set_palette_pred(vb.clone(), fctx);
11523 }
11524 push_intra_rect(2,
11525 cpx,
11526 cpy,
11527 chroma_w,
11528 chroma_h,
11529 uv_predict_mode,
11530 angle_delta_uv,
11531 reach,
11532 &v_levels,
11533 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11534 None,
11535 smooth_neighbor_uv, fctx,
11536 );
11537 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11538 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11539 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11540 record_strip_palette(
11541 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11542 );
11543 if bw > bh {
11544 hit!(RECT4_32_HORZ_HITS);
11545 } else {
11546 hit!(RECT4_32_VERT_HITS);
11547 }
11548 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11549 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11550 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11551 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11552 // transform size in both TXFM_CONTEXT bands. Without it the next block
11553 // reads the row's stale value.
11554 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11555 Ok((mode, uv_predict_mode))
11556}
11557
11558/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
11559/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
11560/// down, and the first shape here whose luma block is a single mi row (or
11561/// column).
11562///
11563/// What is new at this size is CHROMA. `is_chroma_reference`
11564/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
11565/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
11566/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
11567/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
11568/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
11569/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
11570/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
11571///
11572/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
11573/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
11574/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
11575/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
11576/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
11577/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
11578/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
11579/// shape's own CDF row.
11580///
11581/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
11582/// refuses by name rather than guess-decode.
11583#[allow(clippy::too_many_arguments)]
11584fn decode_rect4_16(
11585 dec: &mut SymbolDecoder,
11586 cdfs: &mut Cdfs,
11587 neighbours: &mut Neighbours,
11588 at16: (usize, usize),
11589 horz: bool,
11590 y: &mut PlaneBuf<'static>,
11591 u: &mut PlaneBuf<'static>,
11592 v: &mut PlaneBuf<'static>,
11593 enable_filter_intra: bool,
11594 allow_screen_content_tools: bool,
11595 base_q_idx: u8,
11596 tx_select: bool,
11597 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11598) -> Result<()> {
11599 let (r, c) = at16;
11600 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
11601 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
11602 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
11603 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11604 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11605 let mut prev: Option<((usize, usize), usize)> = None;
11606 let mut last_mode = DC_PRED;
11607 let mut last_uv_mode = DC_PRED;
11608 for i in 0..4usize {
11609 let lmi = if horz {
11610 (mi_row0 + i, mi_col0)
11611 } else {
11612 (mi_row0, mi_col0 + i)
11613 };
11614 let has_chroma = i % 2 == 1;
11615 let (mode, uv, _tx) = decode_rect4_16_strip(
11616 dec,
11617 cdfs,
11618 neighbours,
11619 lmi,
11620 horz,
11621 has_chroma,
11622 prev,
11623 y,
11624 u,
11625 v,
11626 enable_filter_intra,
11627 allow_screen_content_tools,
11628 base_q_idx,
11629 tx_select,
11630 reduced_tx_set, fctx,
11631 )?;
11632 if let Some(m) = uv {
11633 last_uv_mode = m;
11634 }
11635 last_mode = mode;
11636 prev = Some((lmi, mode));
11637 }
11638 // The coarse 16-px cell holds one entry for the whole 16x16: the last
11639 // strip is what a block below (right) sees through it, the mi-exact maps
11640 // above answering everything finer.
11641 neighbours.above_mode[c] = last_mode;
11642 neighbours.left_mode[r] = last_mode;
11643 neighbours.above_uv_mode[c] = last_uv_mode;
11644 neighbours.left_uv_mode[r] = last_uv_mode;
11645 neighbours.above_side[c] = bw;
11646 neighbours.left_side[r] = bh;
11647 Ok(())
11648}
11649
11650/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
11651/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
11652/// block path can decode a SINGLE intra strip of a partition whose other
11653/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
11654/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
11655/// every strip publishes its own mi-exact mode). Returns
11656/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
11657#[allow(clippy::too_many_arguments)]
11658fn decode_rect4_16_strip(
11659 dec: &mut SymbolDecoder,
11660 cdfs: &mut Cdfs,
11661 neighbours: &mut Neighbours,
11662 lmi: (usize, usize),
11663 horz: bool,
11664 has_chroma: bool,
11665 prev: Option<((usize, usize), usize)>,
11666 y: &mut PlaneBuf<'static>,
11667 u: &mut PlaneBuf<'static>,
11668 v: &mut PlaneBuf<'static>,
11669 enable_filter_intra: bool,
11670 allow_screen_content_tools: bool,
11671 base_q_idx: u8,
11672 tx_select: bool,
11673 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11674) -> Result<(usize, Option<usize>, (usize, usize))> {
11675 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
11676 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
11677 let (mi_w, mi_h) = (bw / MI, bh / MI);
11678 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11679 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11680 let mut last_uv_mode: Option<usize> = None;
11681 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
11682 // aliases all four strips onto one entry, so the mi-exact map wins and
11683 // the previous strip stands in on the split axis.
11684 let mut above_mode = neighbours.above_mode[c];
11685 let mut left_mode = neighbours.left_mode[r];
11686 if let Some(((pr, pc), pmode)) = prev {
11687 if pc == lmi.1 && lmi.0 == pr + mi_h {
11688 above_mode = pmode;
11689 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
11690 left_mode = pmode;
11691 }
11692 }
11693 let (above_mode, left_mode) =
11694 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
11695 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
11696 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
11697 // off CDF row 0 and every cache hit off an empty cache.
11698 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
11699 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
11700 let (
11701 skip,
11702 mode,
11703 angle_delta_y,
11704 uv_mode,
11705 angle_delta_uv,
11706 alpha,
11707 filter_intra,
11708 palette_y,
11709 palette_uv,
11710 ) = read_intra_mode_rect(
11711 dec,
11712 cdfs,
11713 above_mode,
11714 left_mode,
11715 true,
11716 has_chroma,
11717 bw,
11718 bh,
11719 enable_filter_intra,
11720 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
11721 allow_screen_content_tools,
11722 Some((palette_ctx, &palette_cache)),
11723 &palette_uv_cache,
11724 lmi.0,
11725 lmi.1, fctx,
11726 )?;
11727 if palette_y.is_some() || palette_uv.is_some() {
11728 hit!(RECT4_PALETTE_HITS);
11729 }
11730 // The colour-index map through the base colours IS the prediction.
11731 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
11732 // chroma transform this closing strip codes.
11733 let palette_y_buf: Option<Vec<u16>> = palette_y
11734 .as_ref()
11735 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11736 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11737 (
11738 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11739 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11740 )
11741 });
11742 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11743 if smooth_neighbor {
11744 hit!(SMOOTH_LUMA_HITS);
11745 }
11746 if filter_intra.is_some() {
11747 hit!(FILTER_INTRA_RECT_HITS);
11748 }
11749 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
11750 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
11751 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
11752 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
11753 let depth = if tx_select {
11754 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
11755 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
11756 // the 2:1 intra-in-inter strip already does); the key frame's
11757 // deblock-grid approximation is only right where those bands were
11758 // never written.
11759 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11760 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
11761 } else {
11762 tx_size_context_rect(neighbours, lmi, bw, bh)
11763 };
11764 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
11765 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11766 eprintln!(
11767 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
11768 lmi.0,
11769 lmi.1,
11770 dec.debug_state().0
11771 );
11772 }
11773 d
11774 } else {
11775 0
11776 };
11777 if depth != 0 {
11778 hit!(TX_DEPTH_HITS);
11779 hit!(RECT4_16_SPLIT_HITS);
11780 }
11781 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11782 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11783 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11784 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
11785 if depth != 0 {
11786 // [`decode_rect_split`]'s per-unit walk, inlined because the
11787 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
11788 // the strip (that function codes one chroma transform per block).
11789 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
11790 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
11791 // unit predicts off the units before it in raster order.
11792 let rect_unit = tx_w != tx_h;
11793 let zero_tu = vec![0i32; tx_w * tx_h];
11794 for tu_row in 0..bh / tx_h {
11795 for tu_col in 0..bw / tx_w {
11796 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
11797 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11798 let tu_reach = Reach::of_tu(
11799 bw,
11800 bh,
11801 tu_col * tx_w,
11802 tu_row * tx_h,
11803 tx_w,
11804 tx_h,
11805 reach,
11806 );
11807 if let Some(b) = &palette_y_buf {
11808 let tu_buf: Vec<u16> = (0..tx_h)
11809 .flat_map(|i| {
11810 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
11811 b[base..base + tx_w].iter().copied()
11812 })
11813 .collect();
11814 set_palette_pred(tu_buf, fctx);
11815 }
11816 if skip {
11817 push_intra_rect(0,
11818 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
11819 None, filter_intra, smooth_neighbor, fctx,
11820 );
11821 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11822 } else if rect_unit {
11823 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
11824 // 32 coded positions and the `TX_4X4` `tx_type` row:
11825 // exactly [`TxbSet::LumaRect4x8`].
11826 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11827 let tu_skip_ctx =
11828 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
11829 let set = if reduced_tx_set {
11830 TxbSet::LumaRect4x8
11831 } else {
11832 TxbSet::LumaRect4x8Set1
11833 };
11834 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
11835 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11836 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11837 dec,
11838 &mut coding,
11839 tu_scan,
11840 tx_w,
11841 tx_h,
11842 tu_skip_ctx,
11843 dc_sign_ctx(tu_around.2),
11844 TxType::DctDct,
11845 )?;
11846 let residual = dequant_and_inverse_typed_wh(
11847 &tu_grid,
11848 tx_w,
11849 tx_h,
11850 crate::decode::bit_depth(fctx),
11851 block_q_idx(fctx),
11852 plane_q_delta(0, fctx).0,
11853 plane_q_delta(0, fctx).1,
11854 tu_tx_type,
11855 );
11856 push_intra_rect(0,
11857 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
11858 None, filter_intra, smooth_neighbor, fctx,
11859 );
11860 if tu_grid.iter().any(|&l| l != 0) {
11861 hit!(RECT4_16_COEFF_HITS);
11862 }
11863 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11864 } else {
11865 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
11866 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
11867 let tu_grid = read_plane(
11868 dec,
11869 cdfs,
11870 txbset_for(tx_w, reduced_tx_set),
11871 default_scan(tx_w),
11872 0,
11873 tu_around,
11874 mode,
11875 mode,
11876 angle_delta_y,
11877 tu_reach,
11878 y,
11879 tu_px,
11880 tu_py,
11881 tx_w,
11882 tx_w,
11883 base_q_idx,
11884 None,
11885 filter_intra,
11886 Some(tu_skip_ctx),
11887 smooth_neighbor, fctx,
11888 )?;
11889 if tu_grid.iter().any(|&l| l != 0) {
11890 hit!(RECT4_16_COEFF_HITS);
11891 }
11892 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
11893 }
11894 }
11895 }
11896 } else {
11897 let levels = if skip {
11898 let zeros = Grid::Zero(bw * bh);
11899 if let Some(b) = &palette_y_buf {
11900 set_palette_pred(b.clone(), fctx);
11901 }
11902 push_intra_rect(0,
11903 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
11904 smooth_neighbor, fctx,
11905 );
11906 zeros
11907 } else {
11908 // The strip's luma TU *is* the strip (`plane_bsize ==
11909 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
11910 // `txb_skip_ctx` at 0.
11911 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
11912 let set = if reduced_tx_set {
11913 TxbSet::LumaRect16x4
11914 } else {
11915 TxbSet::LumaRect16x4Set1
11916 };
11917 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11918 let (levels, tx_type) = read_coeffs_rect(
11919 dec,
11920 &mut coding,
11921 scan,
11922 bw,
11923 bh,
11924 0,
11925 dc_sign_ctx(around.2),
11926 TxType::DctDct,
11927 )?;
11928 let residual = dequant_and_inverse_typed_wh(
11929 &levels,
11930 bw,
11931 bh,
11932 crate::decode::bit_depth(fctx),
11933 block_q_idx(fctx),
11934 plane_q_delta(0, fctx).0,
11935 plane_q_delta(0, fctx).1,
11936 tx_type,
11937 );
11938 if let Some(b) = &palette_y_buf {
11939 set_palette_pred(b.clone(), fctx);
11940 }
11941 push_intra_rect(0,
11942 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
11943 smooth_neighbor, fctx,
11944 );
11945 hit!(RECT4_16_COEFF_HITS);
11946 levels
11947 };
11948 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
11949 }
11950 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
11951 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
11952 // `update_partition_context` writes `partition_context_lookup[
11953 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
11954 // the left (mirrored under VERT_4).
11955 for cell in 0..mi_w {
11956 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
11957 *slot = bw as u8;
11958 }
11959 }
11960 for cell in 0..mi_h {
11961 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
11962 *slot = bh as u8;
11963 }
11964 }
11965 if has_chroma {
11966 hit!(RECT4_16_CHROMA_HITS);
11967 let pair_mi = if horz {
11968 (lmi.0 - 1, lmi.1)
11969 } else {
11970 (lmi.0, lmi.1 - 1)
11971 };
11972 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
11973 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
11974 let (cpx, cpy) = (ppx / 2, ppy / 2);
11975 let (cw, ch) = (pw / 2, ph / 2);
11976 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11977 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
11978 hit!(RECT4_16_CHROMA_DIR_HITS);
11979 }
11980 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
11981 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
11982 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
11983 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
11984 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
11985 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
11986 // the pair's top-left luma mi, never this leaf's odd row/column.
11987 // Reading `lmi` here named the leaf directly above (a non-chroma
11988 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
11989 // SMOOTH neighbour: filt_type 0 instead of 1 turned
11990 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
11991 // directional chroma strip, moving 4 samples by 1.
11992 let smooth_neighbor_uv =
11993 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
11994 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
11995 {
11996 hit!(RECT4_16_UV_PAIR_FILT_HITS);
11997 }
11998 let (u_levels, v_levels) = if skip {
11999 let zeros = Grid::Zero(cw * ch);
12000 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
12001 // ~1000) predicts EVERY plane and only guards the residual on
12002 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
12003 // DC + alpha * luma-AC. Dropping the CfL term here left a
12004 // chroma-only bounded box on ReelC's key frames.
12005 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12006 if alpha.is_some() {
12007 hit!(CHROMA_SKIP_CFL_HITS);
12008 }
12009 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
12010 if let Some((ub, vb)) = &palette_uv_bufs {
12011 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12012 }
12013 push_intra_rect(plane,
12014 cpx,
12015 cpy,
12016 cw,
12017 ch,
12018 uv_predict_mode,
12019 angle_delta_uv,
12020 pair_reach,
12021 &zeros,
12022 alpha
12023 .zip(ac)
12024 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12025 None,
12026 smooth_neighbor_uv, fctx,
12027 );
12028 }
12029 (zeros.clone(), zeros)
12030 } else {
12031 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
12032 let mut planes = Vec::with_capacity(2);
12033 for plane in 1..3 {
12034 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12035 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12036 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12037 let (levels, tx_type) = read_coeffs_rect(
12038 dec,
12039 &mut coding,
12040 chroma_scan,
12041 cw,
12042 ch,
12043 skip_ctx,
12044 dc_sign_ctx(around[plane].2),
12045 default_tx,
12046 )?;
12047 planes.push((levels, tx_type));
12048 }
12049 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12050 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12051 // CfL averages the luma of the WHOLE pair, the region this one
12052 // chroma transform covers.
12053 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12054 for (plane, _buf, levels, tx_type) in [
12055 (1usize, &mut *u, &u_levels, u_tx_type),
12056 (2, &mut *v, &v_levels, v_tx_type),
12057 ] {
12058 let residual = dequant_and_inverse_typed_wh(
12059 levels,
12060 cw,
12061 ch,
12062 crate::decode::bit_depth(fctx),
12063 block_q_idx(fctx),
12064 plane_q_delta(plane, fctx).0,
12065 plane_q_delta(plane, fctx).1,
12066 tx_type,
12067 );
12068 if let Some((ub, vb)) = &palette_uv_bufs {
12069 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12070 }
12071 push_intra_rect(plane,
12072 cpx,
12073 cpy,
12074 cw,
12075 ch,
12076 uv_predict_mode,
12077 angle_delta_uv,
12078 pair_reach,
12079 &residual,
12080 alpha
12081 .zip(ac)
12082 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12083 None,
12084 smooth_neighbor_uv, fctx,
12085 );
12086 }
12087 (u_levels, v_levels)
12088 };
12089 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
12090 // The chroma planes' coefficient context, over the PAIR's mi span
12091 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
12092 // the luma one rounded up to its 4x4 unit).
12093 let u_state = neighbour_state(&u_levels);
12094 let v_state = neighbour_state(&v_levels);
12095 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12096 let bound_h = round_up_even(neighbours.mi_rows);
12097 let bound_w = round_up_even(neighbours.mi_cols);
12098 for cell in 0..(ph / MI) {
12099 if pair_mi.0 + cell < bound_h
12100 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
12101 {
12102 slot[1] = u_state;
12103 slot[2] = v_state;
12104 }
12105 }
12106 for cell in 0..(pw / MI) {
12107 if pair_mi.1 + cell < bound_w
12108 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
12109 {
12110 slot[1] = u_state;
12111 slot[2] = v_state;
12112 }
12113 }
12114 last_uv_mode = Some(uv_predict_mode);
12115 }
12116 if horz {
12117 hit!(RECT4_16_HORZ_HITS);
12118 } else {
12119 hit!(RECT4_16_VERT_HITS);
12120 }
12121 let (pal_y_size, pal_y_colors) =
12122 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12123 let (pal_uv_size, pal_uv_colors) =
12124 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12125 record_strip_palette(
12126 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12127 );
12128 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12129 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12130 // frame): the above row records `tx_size_wide` over the block's width and
12131 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12132 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12133 // and it published neither band -- so the block after a 64x16 strip read
12134 // the row's init value 64 as its left transform height and took
12135 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12136 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12137 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12138 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
12139 Ok((mode, last_uv_mode, (tx_w, tx_h)))
12140}
12141
12142
12143/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
12144/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
12145/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
12146/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
12147/// cap, so LUMA needs the same corner truncation [`decode_block`] already
12148/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
12149/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
12150/// this function's own charter/report), so both strips read a real 32x32
12151/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
12152/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
12153/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
12154/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
12155/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
12156/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
12157/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
12158/// that function, only the single-transform-unit (`tx_depth == 0`) case is
12159/// supported: a split transform refuses by name rather than guess-decode.
12160#[allow(clippy::too_many_arguments)]
12161fn decode_block_rect64(
12162 dec: &mut SymbolDecoder,
12163 cdfs: &mut Cdfs,
12164 neighbours: &mut Neighbours,
12165 at: (usize, usize),
12166 bw: usize,
12167 bh: usize,
12168 y: &mut PlaneBuf<'static>,
12169 u: &mut PlaneBuf<'static>,
12170 v: &mut PlaneBuf<'static>,
12171 enable_filter_intra: bool,
12172 allow_screen_content_tools: bool,
12173 base_q_idx: u8,
12174 tx_select: bool,
12175 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12176) -> Result<()> {
12177 let (r, c) = at;
12178 let (px, py) = (c * SUB, r * SUB);
12179 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12180 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12181 let palette_uv_cache = neighbours.palette_uv_cache(at);
12182 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12183 read_intra_mode_rect(
12184 dec,
12185 cdfs,
12186 nb_above_mode,
12187 nb_left_mode,
12188 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
12189 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
12190 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
12191 // correct), CFL must never be offered here -- passing `true`
12192 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
12193 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
12194 // from this block's very first symbol (lane-sbpart r3 bisect).
12195 false,
12196 true,
12197 bw,
12198 bh,
12199 enable_filter_intra,
12200 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12201 allow_screen_content_tools,
12202 Some((palette_ctx, &palette_cache)),
12203 &palette_uv_cache,
12204 r * (SUB / MI),
12205 c * (SUB / MI), fctx,
12206 )?;
12207 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
12208 // lane-t900 r34: a non-skip palette block on a superblock-level strip
12209 // -- counted so its gate cannot go vacuous (this was a refusal until
12210 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
12211 // decodes_pixel_exact`).
12212 hit!(PALETTE_SB_STRIP_HITS);
12213 }
12214 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12215 if smooth_neighbor {
12216 hit!(SMOOTH_LUMA_HITS);
12217 }
12218 let smooth_neighbor_uv =
12219 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
12220 if filter_intra.is_some() {
12221 // `filter_intra_size_class_rect` already returns `None` for both
12222 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
12223 // 32 on both axes), so this symbol is never read at this level --
12224 // kept only as the same defensive refusal [`decode_block_rect`] has.
12225 return Err(unsupported(
12226 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
12227 av1_filter_intra_allowed_bsize caps at 32x32)",
12228 ));
12229 }
12230 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12231 DC_PRED
12232 } else {
12233 uv_mode
12234 };
12235 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12236 let depth = if tx_select {
12237 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
12238 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
12239 // the 16x4 intra-in-inter strips already do); the key frame's
12240 // deblock-grid approximation is only right where those bands were never
12241 // written. Measured on the 10-bit 1920x792 128-superblock stream,
12242 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12243 // `tx_size_cat2` row 1 where libaom reads row 2.
12244 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12245 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
12246 } else {
12247 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12248 };
12249 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
12250 // counts `sub_tx_size_map` steps from the block's own max rect
12251 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
12252 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
12253 // steps, so this level's category is 3 (the same one a 64x64 square
12254 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
12255 // here was a wrong-table read of a real symbol.
12256 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
12257 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12258 eprintln!(
12259 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
12260 dec.debug_state().0
12261 );
12262 }
12263 d
12264 } else {
12265 0
12266 };
12267 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12268 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12269 publish_txfm_bands_if_in_inter(
12270 neighbours,
12271 (mi_r, mi_c),
12272 depth_to_tx_wh(bw, bh, depth),
12273 (bw, bh), fctx,
12274 );
12275 if depth != 0 {
12276 hit!(TX_DEPTH_HITS);
12277 // lane-rectsplit r1/r4: the superblock-level strip splits its
12278 // transform through the very same per-unit path as its 32x32-level
12279 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
12280 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
12281 // measured the old square formula mis-tiling exactly that strip).
12282 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
12283 if bw.max(bh) / bw.min(bh) == 4 {
12284 let which = if depth == 1 {
12285 &RECT4_SPLIT_DEPTH1_HITS
12286 } else {
12287 &RECT4_SPLIT_DEPTH2_HITS
12288 };
12289 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12290 }
12291 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12292 eprintln!(
12293 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12294 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12295 angle_y={angle_delta_y}"
12296 );
12297 }
12298 let modes = RectStripModes {
12299 skip,
12300 mode,
12301 angle_delta_y,
12302 uv_predict_mode,
12303 angle_delta_uv,
12304 alpha,
12305 filter_intra,
12306 smooth_neighbor,
12307 smooth_neighbor_uv,
12308 palette_y: palette_y
12309 .as_ref()
12310 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12311 palette_uv: palette_uv.as_ref().map(|p| {
12312 (
12313 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12314 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12315 )
12316 }),
12317 };
12318 if palette_y.is_some() || palette_uv.is_some() {
12319 hit!(PALETTE_SPLIT_TX_HITS);
12320 }
12321 decode_rect_split(
12322 dec,
12323 cdfs,
12324 neighbours,
12325 (mi_r, mi_c),
12326 bw,
12327 bh,
12328 tx_w,
12329 tx_h,
12330 &modes,
12331 y,
12332 u,
12333 v,
12334 base_q_idx,
12335 reduced_tx_set, fctx,
12336 )?;
12337 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
12338 // (lane-palette2 r10): this return skips the fn's own tail, so a
12339 // split-tx superblock strip would otherwise leave the above/left
12340 // palette arrays holding a dead block's colours.
12341 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12342 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12343 let (puv_size, puv_colors) =
12344 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12345 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12346 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
12347 // return skips the fn's own tail, so a SPLIT superblock-level strip
12348 // published no TXFM_CONTEXT band and the next block read the row's init
12349 // value 64 as its left transform height. Measured on the 10-bit
12350 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
12351 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
12352 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
12353 // bands carry the SPLIT unit's size, not the block's.
12354 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12355 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
12356 hit!(RECT_PARTITION_HITS);
12357 return Ok(());
12358 }
12359 let (tx_w, tx_h) = (bw, bh);
12360 let (cpx, cpy) = (px / 2, py / 2);
12361 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12362 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12363 if let Some(ref pyv) = palette_y {
12364 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12365 set_palette_pred(buf, fctx);
12366 }
12367 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12368 (
12369 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12370 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12371 )
12372 });
12373 if skip {
12374 push_intra_rect(0,
12375 px,
12376 py,
12377 bw,
12378 bh,
12379 mode,
12380 angle_delta_y,
12381 reach,
12382 &ZERO_RESIDUAL[..bw * bh],
12383 None,
12384 filter_intra,
12385 smooth_neighbor, fctx,
12386 );
12387 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12388 if let Some((ub, _)) = &palette_uv_bufs {
12389 set_palette_pred(ub.clone(), fctx);
12390 }
12391 push_intra_rect(1,
12392 cpx,
12393 cpy,
12394 chroma_w,
12395 chroma_h,
12396 uv_predict_mode,
12397 angle_delta_uv,
12398 reach,
12399 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12400 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12401 None,
12402 smooth_neighbor_uv, fctx,
12403 );
12404 if let Some((_, vb)) = &palette_uv_bufs {
12405 set_palette_pred(vb.clone(), fctx);
12406 }
12407 push_intra_rect(2,
12408 cpx,
12409 cpy,
12410 chroma_w,
12411 chroma_h,
12412 uv_predict_mode,
12413 angle_delta_uv,
12414 reach,
12415 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12416 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12417 None,
12418 smooth_neighbor_uv, fctx,
12419 );
12420 neighbours.record_rect(
12421 at,
12422 bw,
12423 bh,
12424 mode,
12425 uv_predict_mode,
12426 &[
12427 &ZERO_RESIDUAL[..bw * bh],
12428 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12429 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12430 ],
12431 );
12432 } else {
12433 let around = neighbours.around_rect(at, bw, bh);
12434 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
12435 // (see this function's own doc comment). A 64-length axis codes only
12436 // its low 32 coefficients, so the corner is `min(bw, 32)` x
12437 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
12438 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
12439 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
12440 let scan32 = default_scan(TX32);
12441 if coeff_trace_on() {
12442 let (rng, _) = dec.debug_state();
12443 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
12444 }
12445 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
12446 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
12447 read_coeffs(
12448 dec,
12449 &mut luma_coding,
12450 &scan32,
12451 0,
12452 dc_sign_ctx(around[0].2),
12453 TxType::DctDct,
12454 Some((bw, bh)),
12455 )?
12456 } else {
12457 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
12458 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
12459 // (`scan.c`) gives both the very same `default_scan_32x16` /
12460 // `default_scan_16x32` the 2:1 sizes use ("Half of the
12461 // coefficients of tx64 at higher frequencies are set to zeros. So
12462 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
12463 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
12464 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
12465 // 512-position eob group) -- BOTH identical to TX_32X16, so the
12466 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
12467 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
12468 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
12469 // what `base_ctx_rect` computes at (32, 16).
12470 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
12471 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
12472 read_coeffs_rect(
12473 dec,
12474 &mut luma_coding,
12475 luma_scan,
12476 luma_cw,
12477 luma_ch,
12478 0,
12479 dc_sign_ctx(around[0].2),
12480 TxType::DctDct,
12481 )?
12482 };
12483 if coeff_trace_on() {
12484 let (rng, _) = dec.debug_state();
12485 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
12486 }
12487 let mut luma_levels = vec![0i32; bw * bh];
12488 for row in 0..luma_ch {
12489 luma_levels[row * bw..][..luma_cw]
12490 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
12491 }
12492 {
12493 let cur = block_q_idx(fctx);
12494 if cur != i32::from(base_q_idx) {
12495 hit!(RECT64_QIDX_DRIFT_HITS);
12496 }
12497 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12498 eprintln!(
12499 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
12500 );
12501 }
12502 }
12503 let luma_residual = dequant_and_inverse_typed_wh(
12504 &luma_levels,
12505 bw,
12506 bh,
12507 crate::decode::bit_depth(fctx),
12508 block_q_idx(fctx),
12509 plane_q_delta(0, fctx).0,
12510 plane_q_delta(0, fctx).1,
12511 luma_tx_type,
12512 );
12513 push_intra_rect(0,
12514 px,
12515 py,
12516 bw,
12517 bh,
12518 mode,
12519 angle_delta_y,
12520 reach,
12521 &luma_residual,
12522 None,
12523 filter_intra,
12524 smooth_neighbor, fctx,
12525 );
12526 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12527 let leftcol: Vec<u16> = if px > 0 {
12528 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
12529 } else {
12530 vec![]
12531 };
12532 eprintln!(
12533 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
12534 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
12535 luma_corner.iter().any(|&v| v != 0),
12536 &y.data[py * y.width + px..][..bw],
12537 leftcol,
12538 );
12539 }
12540 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
12541 // corner crop needed (see doc comment).
12542 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12543 // The chroma plane is never truncated (both axes <= 32 after
12544 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
12545 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
12546 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
12547 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
12548 // set, and only the scan is new (lane-tx64x16).
12549 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
12550 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
12551 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
12552 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12553 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12554 };
12555 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12556 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12557 if coeff_trace_on() {
12558 let (rng, _) = dec.debug_state();
12559 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12560 }
12561 let (u_levels, u_tx_type) = read_coeffs_rect(
12562 dec,
12563 &mut u_coding,
12564 chroma_scan,
12565 chroma_w,
12566 chroma_h,
12567 u_skip_ctx,
12568 dc_sign_ctx(around[1].2),
12569 TxType::DctDct,
12570 )?;
12571 if coeff_trace_on() {
12572 let (rng, _) = dec.debug_state();
12573 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
12574 }
12575 {
12576 let cur = block_q_idx(fctx);
12577 if cur != i32::from(base_q_idx) {
12578 hit!(RECT64_QIDX_DRIFT_HITS);
12579 }
12580 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12581 eprintln!(
12582 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
12583 );
12584 }
12585 }
12586 let u_residual = dequant_and_inverse_typed_wh(
12587 &u_levels,
12588 chroma_w,
12589 chroma_h,
12590 crate::decode::bit_depth(fctx),
12591 block_q_idx(fctx),
12592 plane_q_delta(1, fctx).0,
12593 plane_q_delta(1, fctx).1,
12594 u_tx_type,
12595 );
12596 // lane-t900 r34: the UV-palette prediction override, exactly as the
12597 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
12598 // set-then-take, so it must be filled again right before each plane's
12599 // own reconstruct; leaving this out of the non-skip arm predicted a
12600 // palette block's chroma off its block edges (measured: testsrc2
12601 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
12602 // luma exact, both chroma planes wrong over its whole 16x32).
12603 if let Some((ub, _)) = &palette_uv_bufs {
12604 set_palette_pred(ub.clone(), fctx);
12605 }
12606 push_intra_rect(1,
12607 cpx,
12608 cpy,
12609 chroma_w,
12610 chroma_h,
12611 uv_predict_mode,
12612 angle_delta_uv,
12613 reach,
12614 &u_residual,
12615 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12616 None,
12617 smooth_neighbor_uv, fctx,
12618 );
12619 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12620 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12621 if coeff_trace_on() {
12622 let (rng, _) = dec.debug_state();
12623 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12624 }
12625 let (v_levels, v_tx_type) = read_coeffs_rect(
12626 dec,
12627 &mut v_coding,
12628 chroma_scan,
12629 chroma_w,
12630 chroma_h,
12631 v_skip_ctx,
12632 dc_sign_ctx(around[2].2),
12633 TxType::DctDct,
12634 )?;
12635 if coeff_trace_on() {
12636 let (rng, _) = dec.debug_state();
12637 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
12638 }
12639 {
12640 let cur = block_q_idx(fctx);
12641 if cur != i32::from(base_q_idx) {
12642 hit!(RECT64_QIDX_DRIFT_HITS);
12643 }
12644 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12645 eprintln!(
12646 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
12647 );
12648 }
12649 }
12650 let v_residual = dequant_and_inverse_typed_wh(
12651 &v_levels,
12652 chroma_w,
12653 chroma_h,
12654 crate::decode::bit_depth(fctx),
12655 block_q_idx(fctx),
12656 plane_q_delta(2, fctx).0,
12657 plane_q_delta(2, fctx).1,
12658 v_tx_type,
12659 );
12660 if let Some((_, vb)) = &palette_uv_bufs {
12661 set_palette_pred(vb.clone(), fctx);
12662 }
12663 push_intra_rect(2,
12664 cpx,
12665 cpy,
12666 chroma_w,
12667 chroma_h,
12668 uv_predict_mode,
12669 angle_delta_uv,
12670 reach,
12671 &v_residual,
12672 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12673 None,
12674 smooth_neighbor_uv, fctx,
12675 );
12676 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12677 hit!(RECT_COEFF_HITS);
12678 }
12679 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12680 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12681 let (puv_size, puv_colors) =
12682 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12683 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12684 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12685 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12686 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12687 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12688 // frame): the above row records `tx_size_wide` over the block's width and
12689 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12690 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12691 // and it published neither band -- so the block after a 64x16 strip read
12692 // the row's init value 64 as its left transform height and took
12693 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12694 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12695 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12696 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12697 hit!(SB_RECT_HITS);
12698 match (bw, bh) {
12699 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
12700 (16, 64) => hit!(SB_RECT4_VERT_HITS),
12701 _ => {}
12702 }
12703 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12704 let (rng, _) = dec.debug_state();
12705 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
12706 }
12707 Ok(())
12708}
12709
12710/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
12711/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
12712/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
12713/// it lands away from zero, for gate tests to prove a real stream fired one.
12714fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
12715 let symbol = dec.symbol(cdf);
12716 if symbol != ANGLE_DELTA_ZERO {
12717 hit!(ANGLE_DELTA_HITS);
12718 }
12719 symbol as i32 - ANGLE_DELTA_ZERO as i32
12720}
12721
12722#[allow(clippy::too_many_arguments)]
12723fn read_intra_mode(
12724 dec: &mut SymbolDecoder,
12725 cdfs: &mut Cdfs,
12726 above_mode: usize,
12727 left_mode: usize,
12728 cfl: bool,
12729 side: usize,
12730 enable_filter_intra: bool,
12731 skip_ctx: usize,
12732 allow_screen_content_tools: bool,
12733 allow_intrabc: bool,
12734 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
12735 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
12736 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
12737 // `None` at the excluded call sites (the 8x8-leaf path), which still read
12738 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
12739 // decoder reads either way -- but refuse by name the moment it fires,
12740 // exactly the old behaviour.
12741 palette: Option<(usize, &[u16])>,
12742 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
12743 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
12744 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
12745 // `use_palette_y`, not a neighbour lookup).
12746 palette_uv_cache: &[u16],
12747 mi_r: usize,
12748 mi_c: usize, fctx: &crate::decode::FrameCtx,
12749) -> Result<(
12750 bool,
12751 usize,
12752 i32,
12753 usize,
12754 i32,
12755 Option<(i32, i32)>,
12756 Option<usize>,
12757 Option<PaletteY>,
12758 Option<PaletteUv>,
12759)> {
12760 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
12761 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
12762 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
12763 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
12764 // line against the instrumented aomdec, not just `tell()`.
12765 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
12766 if ec_istep {
12767 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
12768 // (decodemv.c:818), printed at the same point: before the first
12769 // mode-info symbol of the block, so a cross-decoder range ladder can
12770 // be keyed on the BLOCK, not just on the symbol sequence.
12771 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
12772 }
12773 macro_rules! istep {
12774 ($name:literal, $val:expr) => {
12775 if ec_istep {
12776 let (rng, _) = dec.debug_state();
12777 eprintln!(
12778 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
12779 $name, $val
12780 );
12781 }
12782 };
12783 }
12784 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
12785 // point every square caller routes through (see `read_intra_mode_rect`).
12786 let cfl = if cfl && side > 32 {
12787 hit!(NOCFL_UV_MODE_HITS);
12788 false
12789 } else {
12790 cfl
12791 };
12792 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
12793 // `skip` when `SegIdPreSkip`, and after it otherwise.
12794 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
12795 if seg_id_pre_skip(fctx) {
12796 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
12797 }
12798 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
12799 if trace {
12800 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
12801 }
12802 istep!("skip", skip as i32);
12803 if !seg_id_pre_skip(fctx) {
12804 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
12805 }
12806 // spec order (see the comment below on `read_intrabc_info`): `skip`,
12807 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
12808 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
12809 istep!("cdef", 0);
12810 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
12811 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
12812 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
12813 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
12814 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12815 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12816 istep!("dq", 0);
12817 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
12818 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
12819 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
12820 // intra frame whose header set `allow_intrabc`. Actual intra block copy
12821 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
12822 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
12823 // draws the line at consuming this one flag symbol and refusing by name
12824 // when it fires, so the arithmetic decoder still resyncs for a stream
12825 // that merely allows (but never uses) intrabc.
12826 if allow_intrabc {
12827 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
12828 if trace {
12829 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
12830 }
12831 if use_intrabc {
12832 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
12833 if trace {
12834 eprintln!("TRACE intrabc dv={dv:?}");
12835 }
12836 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
12837 hit!(INTRABC_HITS);
12838 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
12839 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
12840 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
12841 // `DC_PRED` (which is also what the neighbour mode contexts and
12842 // the loop filter then see).
12843 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
12844 }
12845 }
12846 let above_ctx = INTRA_MODE_CTX[above_mode];
12847 let left_ctx = INTRA_MODE_CTX[left_mode];
12848 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
12849 if trace {
12850 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
12851 }
12852 istep!("mode", mode as i32);
12853 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
12854 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
12855 if trace {
12856 eprintln!(
12857 "TRACE angle_delta value={}",
12858 delta + ANGLE_DELTA_ZERO as i32
12859 );
12860 }
12861 delta
12862 } else {
12863 0
12864 };
12865 istep!("angle_y", angle_delta_y);
12866 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
12867 // here so every `decode_block` caller (64x64 and 128x128 roots included)
12868 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
12869 let cfl = cfl && side <= 32;
12870 let uv_mode = if cfl {
12871 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
12872 } else {
12873 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
12874 };
12875 if trace {
12876 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
12877 }
12878 istep!("uv_mode", uv_mode as i32);
12879 let alpha = if cfl && uv_mode == UV_CFL_PRED {
12880 Some(read_cfl_alphas(dec, cdfs))
12881 } else {
12882 None
12883 };
12884 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
12885 // from this lane's directional chroma: a corner block with neither
12886 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
12887 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
12888 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
12889 // bug in that fallback this lane's own scope does not cover. Keep it
12890 // refused here rather than ship a silently-wrong decode.
12891 if (9..=12).contains(&uv_mode) {
12892 hit!(SMOOTH_UV_HITS);
12893 }
12894 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
12895 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
12896 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
12897 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
12898 // the `else` branch below and never reads one either way.
12899 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
12900 hit!(DIRECTIONAL_UV_HITS);
12901 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
12902 } else {
12903 0
12904 };
12905 istep!("angle_uv", angle_delta_uv);
12906 if angle_delta_uv != 0 {
12907 hit!(UV_ANGLE_DELTA_HITS);
12908 }
12909 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
12910 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
12911 // gated by `av1_allow_palette` (blockd.h -- size bound only,
12912 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
12913 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
12914 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
12915 // read the same CDF row whenever every neighbour really is non-palette).
12916 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
12917 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
12918 // neighbour lookup at all), so it is exact even at the excluded call
12919 // sites once Y decodes real syntax there too.
12920 //
12921 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
12922 // inline from `read_palette_mode_info` -- it runs later, from
12923 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
12924 // after the WHOLE mode-info read for the block, including UV palette
12925 // mode_info (`read_palette_mode_info`'s own second half, right below)
12926 // and `read_filter_intra_mode_info`. So this branch now only reads
12927 // mode/size/colours for both planes (deferring the two colour-index-map
12928 // decodes to after `filter_intra`, below) -- r6's range trace pinned
12929 // this exact ordering bug (`compare-range-not-tell`: ranges matched
12930 // bit-for-bit through the Y colours, diverged only at the old inline
12931 // `decode_color_index_map` call).
12932 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
12933 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
12934 if allow_screen_content_tools
12935 && let Some(bsize_ctx) = palette_bsize_ctx(side)
12936 {
12937 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
12938 if mode == DC_PRED {
12939 if trace {
12940 let (rng, _) = dec.debug_state();
12941 eprintln!(
12942 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
12943 );
12944 }
12945 }
12946 let use_palette_y =
12947 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
12948 if mode == DC_PRED && trace {
12949 let (rng, _) = dec.debug_state();
12950 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
12951 }
12952 if use_palette_y {
12953 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
12954 if trace {
12955 let (rng, _) = dec.debug_state();
12956 eprintln!("TRACE palette_y_size n={n} rng={rng}");
12957 }
12958 let colors = read_palette_colors_y(dec, n, cache, fctx);
12959 if trace {
12960 let (rng, _) = dec.debug_state();
12961 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
12962 }
12963 palette_y_pending = Some((n, colors));
12964 }
12965 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
12966 // unconditionally at this bit position whenever `uv_mode ==
12967 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
12968 // scope always reconstructs chroma alongside luma (`decode_block`
12969 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
12970 // is always true here and does not need threading in.
12971 let palette_uv_mode_ctx = usize::from(use_palette_y);
12972 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
12973 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
12974 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
12975 palette_uv_pending = Some((n, u_colors, v_colors));
12976 }
12977 }
12978 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
12979 // `use_filter_intra` symbol this decoder never read at all until
12980 // lane-av1real r10 -- silently skipping it left every bit past a
12981 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
12982 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
12983 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
12984 // symbol's bits were never consumed).
12985 let mut filter_intra = None;
12986 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
12987 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
12988 // `use_filter_intra` symbol for a Y-palette block, and reading one here
12989 // desynced every screen-content stream from the first palette block on
12990 // (it surfaced as a bogus "partition below 8x8" refusal further down the
12991 // tile).
12992 if mode == DC_PRED
12993 && enable_filter_intra
12994 && palette_y_pending.is_none()
12995 && let Some(class) = filter_intra_size_class(side)
12996 {
12997 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
12998 if trace {
12999 eprintln!(
13000 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
13001 use_filter_intra as i32
13002 );
13003 }
13004 istep!("use_filter_intra", use_filter_intra as i32);
13005 if use_filter_intra {
13006 hit!(FILTER_INTRA_HITS);
13007 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13008 if trace {
13009 eprintln!("TRACE filter_intra_mode value={fi_mode}");
13010 }
13011 istep!("filter_intra_mode", fi_mode as i32);
13012 filter_intra = Some(fi_mode);
13013 }
13014 }
13015 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
13016 // shared U/V map) -- the same order libaom's own loop visits them in.
13017 let palette_y = palette_y_pending.map(|(n, colors)| {
13018 let map = decode_color_index_map(dec, cdfs, n, side, false);
13019 hit!(PALETTE_HITS);
13020 if trace {
13021 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
13022 }
13023 PaletteY { size: n, colors, map }
13024 });
13025 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13026 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
13027 hit!(PALETTE_UV_HITS);
13028 if trace {
13029 eprintln!(
13030 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
13031 &u_colors[..n],
13032 &v_colors[..n]
13033 );
13034 }
13035 PaletteUv { size: n, u_colors, v_colors, map }
13036 });
13037 Ok((
13038 skip,
13039 mode,
13040 angle_delta_y,
13041 uv_mode,
13042 angle_delta_uv,
13043 alpha,
13044 filter_intra,
13045 palette_y,
13046 palette_uv,
13047 ))
13048}
13049
13050/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
13051/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
13052/// intra modes.
13053const UV_CFL_PRED: usize = 13;
13054
13055/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
13056/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
13057/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
13058/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
13059/// joint sign the same way. Returns each plane's final signed `alpha_q3`
13060/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
13061fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
13062 hit!(CFL_BLOCK_HITS);
13063 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
13064 let sign_u = ((joint_sign + 1) * 11) >> 5;
13065 let sign_v = (joint_sign + 1) - 3 * sign_u;
13066 let alpha_u = if sign_u == 0 {
13067 0
13068 } else {
13069 let ctx_u = (joint_sign + 1 - 3) as usize;
13070 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
13071 if sign_u == 2 { mag } else { -mag }
13072 };
13073 let alpha_v = if sign_v == 0 {
13074 0
13075 } else {
13076 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
13077 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
13078 if sign_v == 2 { mag } else { -mag }
13079 };
13080 (alpha_u, alpha_v)
13081}
13082
13083/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
13084/// the reconstructed luma samples under a `side`-square block, subsampled
13085/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
13086/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13087/// to give the AC values [`cfl_scaled`] scales by alpha.
13088fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13089 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13090}
13091
13092/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
13093/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
13094/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
13095/// reconstruction through THIS function rather than a second transcription of
13096/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
13097pub(crate) fn cfl_ac_q3_at(
13098 px: usize,
13099 py: usize,
13100 bw: usize,
13101 bh: usize,
13102 sample: impl Fn(usize, usize) -> i32,
13103) -> Vec<i32> {
13104 let (cw, ch) = (bw / 2, bh / 2);
13105 let mut ac = vec![0i32; cw * ch];
13106 let mut sum = 0i32;
13107 for cy in 0..ch {
13108 for cx in 0..cw {
13109 let (lx, ly) = (px + cx * 2, py + cy * 2);
13110 let q3 = (sample(lx, ly)
13111 + sample(lx + 1, ly)
13112 + sample(lx, ly + 1)
13113 + sample(lx + 1, ly + 1))
13114 << 1;
13115 ac[cy * cw + cx] = q3;
13116 sum += q3;
13117 }
13118 }
13119 let num_pel = (cw * ch) as i32;
13120 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13121 ac.iter_mut().for_each(|v| *v -= avg);
13122 ac
13123}
13124
13125/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13126/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13127/// ties away from zero on the shifted-out sign).
13128pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13129 let v = alpha_q3 * ac_q3;
13130 if v >= 0 {
13131 (v + 32) >> 6
13132 } else {
13133 -((-v + 32) >> 6)
13134 }
13135}
13136
13137/// One plane's reconstruction buffer, `width * height` samples, and the
13138/// prediction/residual reads and writes into it — the decode-side twin of
13139/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
13140/// (own-edge and reach clamps both), passing what it gathers straight to
13141/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
13142/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
13143/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
13144/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
13145/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
13146/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
13147/// lane-mc64 r1: the decode-order index the stage dumps below key their file
13148/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
13149/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
13150/// without this every frame overwrote `.f0` and a per-frame bisection silently
13151/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
13152#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
13153fn stage_dump_idx() -> usize {
13154 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
13155}
13156
13157fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
13158 use std::io::Write;
13159 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
13160 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
13161 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
13162 // not be read out at all.
13163 if let Ok(path) = crate::envflags::var(var)
13164 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13165 {
13166 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))] {
13167 for row in 0..h {
13168 let mut bytes = Vec::with_capacity(w * 2);
13169 for &s in &p.data[row * p.width..][..w] {
13170 bytes.extend_from_slice(&s.to_le_bytes());
13171 }
13172 let _ = f.write_all(&bytes);
13173 }
13174 }
13175 }
13176}
13177
13178/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
13179/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
13180/// every frame overwrote the previous one and only the LAST frame survived,
13181/// which silently defeats any per-frame filter-stage bisection.
13182fn dump_stage_idx(var: &str) -> usize {
13183 use std::collections::HashMap;
13184 use std::sync::{Mutex, OnceLock};
13185 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
13186 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
13187 let e = m.entry(var.to_string()).or_insert(0);
13188 let i = *e;
13189 *e += 1;
13190 i
13191}
13192
13193fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
13194 use std::io::Write;
13195 if let Ok(path) = crate::envflags::var(var)
13196 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13197 {
13198 for p in [y, u, v] {
13199 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
13200 let _ = f.write_all(&narrow);
13201 }
13202 }
13203}
13204
13205/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
13206/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
13207/// at most 4095), so a decode that hashes identically under the flag proves
13208/// the output does not depend on the plane buffer's initial content.
13209const PLANE_SENTINEL: u16 = 0xDEAD;
13210
13211/// A frame plane's own backing store, `n` samples, UNINITIALISED.
13212///
13213/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
13214/// by the tile walk's reconstruction before anything reads it, so the
13215/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
13216/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
13217/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
13218/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
13219/// ways (see the lane report) and the two agree, which is the proof that no
13220/// unwritten sample reaches the output.
13221fn fresh_plane(n: usize) -> Vec<u16> {
13222 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
13223 return vec![PLANE_SENTINEL; n];
13224 }
13225 let mut v: Vec<u16> = Vec::with_capacity(n);
13226 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
13227 // capacity was just reserved, so the vector owns `n` initialised-or-not
13228 // `u16` slots. Every one is written by reconstruction before it is read
13229 // (proven by the sentinel gate above).
13230 #[allow(unsafe_code)]
13231 unsafe {
13232 v.set_len(n);
13233 }
13234 v
13235}
13236
13237#[derive(Clone)]
13238struct PlaneBuf<'a> {
13239 data: std::borrow::Cow<'a, [u16]>,
13240 width: usize,
13241 height: usize,
13242 /// The frame's true, decodable extent in this plane's own units — past
13243 /// this, samples are the padded coding surface's invented tail, never a
13244 /// real decoder's edge or reach reads.
13245 true_width: usize,
13246 true_height: usize,
13247 /// This plane's own tile's top-left pixel origin (spec: intra prediction
13248 /// never reaches across a tile boundary even though an earlier-decoded
13249 /// tile's real pixels sit right there in the shared buffer) — set via
13250 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
13251 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
13252 /// is threaded (the two-tile column-split stage 1 fixture's tile always
13253 /// ends at the frame's own right/bottom edge); a non-last tile's own
13254 /// right/bottom reach bound is still open, tracked in the report.
13255 tile_x0: usize,
13256 tile_y0: usize,
13257 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
13258 /// (exclusive) -- a non-last tile column/row's own reach must stop at
13259 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
13260 /// full padded extent) for the single-tile/last-tile case, matching the
13261 /// old unclipped behaviour exactly.
13262 tile_x1: usize,
13263 tile_y1: usize,
13264}
13265
13266/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
13267/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
13268/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
13269/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13270/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13271/// `ALTREF2`/`ALTREF`).
13272
13273impl PlaneBuf<'_> {
13274 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
13275 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
13276 /// are already in this plane's own units (luma pixels for `y`, chroma
13277 /// pixels — halved — for `u`/`v`).
13278 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
13279 self.tile_x0 = x0;
13280 self.tile_y0 = y0;
13281 self.tile_x1 = x1;
13282 self.tile_y1 = y1;
13283 }
13284
13285 fn edges(
13286 &self,
13287 x: usize,
13288 y: usize,
13289 side: usize,
13290 reach: Reach,
13291 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13292 let own_across = x + side.min(self.true_width.saturating_sub(x));
13293 let across = if reach.above_right {
13294 own_across + side.min(self.true_width.saturating_sub(own_across))
13295 } else {
13296 own_across
13297 }
13298 .min(self.width)
13299 .min(self.tile_x1);
13300 let own_down = y + side.min(self.true_height.saturating_sub(y));
13301 let down = if reach.below_left {
13302 own_down + side.min(self.true_height.saturating_sub(own_down))
13303 } else {
13304 own_down
13305 }
13306 .min(self.height)
13307 .min(self.tile_y1);
13308 let above = (y > self.tile_y0 && across > x)
13309 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13310 let left = (x > self.tile_x0 && down > y).then(|| {
13311 (y..down)
13312 .map(|row| self.data[row * self.width + x - 1])
13313 .collect::<Vec<_>>()
13314 });
13315 let corner =
13316 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13317 (above, left, corner)
13318 }
13319
13320 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
13321 /// the above/left reach each extend by their OWN axis (`bw` across,
13322 /// `bh` down), not one shared `side`.
13323 fn edges_rect(
13324 &self,
13325 x: usize,
13326 y: usize,
13327 bw: usize,
13328 bh: usize,
13329 reach: Reach,
13330 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13331 let own_across = x + bw.min(self.true_width.saturating_sub(x));
13332 let across = if reach.above_right {
13333 own_across + bw.min(self.true_width.saturating_sub(own_across))
13334 } else {
13335 own_across
13336 }
13337 .min(self.width)
13338 .min(self.tile_x1);
13339 let own_down = y + bh.min(self.true_height.saturating_sub(y));
13340 let down = if reach.below_left {
13341 own_down + bh.min(self.true_height.saturating_sub(own_down))
13342 } else {
13343 own_down
13344 }
13345 .min(self.height)
13346 .min(self.tile_y1);
13347 let above = (y > self.tile_y0 && across > x)
13348 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13349 let left = (x > self.tile_x0 && down > y).then(|| {
13350 (y..down)
13351 .map(|row| self.data[row * self.width + x - 1])
13352 .collect::<Vec<_>>()
13353 });
13354 let corner =
13355 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13356 if matches!((bw, bh), (16, 8) | (8, 16)) {
13357 hit!(RECT_STRIP_PRED_HITS);
13358 if across > own_across || down > own_down {
13359 hit!(RECT_STRIP_REACH_HITS);
13360 }
13361 }
13362 (above, left, corner)
13363 }
13364
13365 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
13366 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
13367 /// already-rect-capable `(bw, bh)` pair.
13368 #[allow(clippy::too_many_arguments)]
13369 #[track_caller]
13370 fn reconstruct_rect(
13371 &mut self,
13372 x: usize,
13373 y: usize,
13374 bw: usize,
13375 bh: usize,
13376 mode: usize,
13377 angle_delta: i32,
13378 reach: Reach,
13379 residual: &[i32],
13380 cfl: Option<(i32, &[i32])>,
13381 filter_intra: Option<usize>,
13382 smooth_neighbor: bool,
13383 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13384 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13385 // than by this replay.
13386 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13387 ) {
13388 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
13389 // (lane-palette2 r4): a palette block's prediction is the
13390 // reconstructed colour-index map, needing no edge pixels at all.
13391 let prediction = if let Some(buf) = pred {
13392 buf
13393 } else {
13394 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
13395 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
13396 eprintln!(
13397 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
13398 above.as_ref().map(|a| (a.len(), a[0])),
13399 left.as_ref().map(|l| l.len()),
13400 left.as_ref().map(|l| l[0]),
13401 self.tile_x0, self.tile_y0, self.true_width, self.true_height
13402 );
13403 }
13404 let mut prediction = vec![0u16; bw * bh];
13405 if let Some(fi_mode) = filter_intra {
13406 crate::intra::predict_filter_intra(
13407 fi_mode,
13408 above.as_deref(),
13409 left.as_deref(),
13410 corner,
13411 bw,
13412 bh,
13413 &mut prediction, fctx,
13414 );
13415 } else {
13416 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13417 predict(
13418 mode as u8,
13419 angle_delta,
13420 above.as_deref(),
13421 left.as_deref(),
13422 corner,
13423 bw,
13424 bh,
13425 enable_edge_filter,
13426 smooth_neighbor,
13427 &mut prediction, fctx,
13428 );
13429 }
13430 prediction
13431 };
13432 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13433 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13434 if crate::envflags::env_flag!("EC_PRED") {
13435 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13436 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
13437 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
13438 eprintln!(
13439 "@{} 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)
13440 );
13441 }
13442 let residual = dense_residual(residual, bw * bh);
13443 for row in 0..bh {
13444 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
13445 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
13446 // whose padded width is not superblock aligned hangs past it.
13447 if y + row >= self.height {
13448 break;
13449 }
13450 for col in 0..bw {
13451 if x + col >= self.width {
13452 break;
13453 }
13454 let idx = row * bw + col;
13455 let mut base = i32::from(prediction[idx]);
13456 if let Some((alpha_q3, ac_q3)) = cfl {
13457 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13458 }
13459 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13460 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13461 }
13462 }
13463 }
13464
13465 /// Predicts under `mode` then adds `residual` (side*side, raster),
13466 /// writing the clamped reconstruction back into the plane at `(x, y)`.
13467 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
13468 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
13469 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
13470 /// order (cfl.c).
13471 #[track_caller]
13472 fn reconstruct(
13473 &mut self,
13474 x: usize,
13475 y: usize,
13476 side: usize,
13477 mode: usize,
13478 angle_delta: i32,
13479 reach: Reach,
13480 residual: &[i32],
13481 cfl: Option<(i32, &[i32])>,
13482 filter_intra: Option<usize>,
13483 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
13484 // libaom `get_filt_type`): true when the block's above OR left
13485 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
13486 // Callers pass their own plane's neighbour-mode check
13487 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
13488 // callers until a smooth/paeth `uv_mode` can reach this call at all
13489 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
13490 // keeps `false` exact for chroma without this fn needing to know why.
13491 smooth_neighbor: bool,
13492 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13493 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13494 // than by this replay.
13495 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13496 ) {
13497 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
13498 // takes priority over `predict()`/`predict_filter_intra` entirely --
13499 // palette prediction needs no edge pixels at all.
13500 let prediction = if let Some(buf) = pred {
13501 buf
13502 } else {
13503 let (above, left, corner) = self.edges(x, y, side, reach);
13504 let mut prediction = vec![0u16; side * side];
13505 if let Some(fi_mode) = filter_intra {
13506 crate::intra::predict_filter_intra(
13507 fi_mode,
13508 above.as_deref(),
13509 left.as_deref(),
13510 corner,
13511 side,
13512 side,
13513 &mut prediction, fctx,
13514 );
13515 } else {
13516 // `enable_intra_edge_filter` is the sequence header's own flag
13517 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
13518 // call, never per-block) -- threading it through every
13519 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
13520 // dozen sites for a value that never changes mid-decode, so it
13521 // rides a thread-local instead (this decoder is single-threaded
13522 // per stream).
13523 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13524 predict(
13525 mode as u8,
13526 angle_delta,
13527 above.as_deref(),
13528 left.as_deref(),
13529 corner,
13530 side,
13531 side,
13532 enable_edge_filter,
13533 smooth_neighbor,
13534 &mut prediction, fctx,
13535 );
13536 }
13537 prediction
13538 };
13539 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13540 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13541 if crate::envflags::env_flag!("EC_PRED") {
13542 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13543 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
13544 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
13545 eprintln!(
13546 "@{} 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)
13547 );
13548 }
13549 let residual = dense_residual(residual, side * side);
13550 for row in 0..side {
13551 // lane-sb128c r8: libaom's frame buffer is superblock
13552 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
13553 // transform unit of a 128x64 block at the BOTTOM frame edge
13554 // can hang past the last padded row (1920x792: a unit at
13555 // y=768 wants 832 rows of an 800-row buffer, which panicked
13556 // the film's key frames). Those samples are outside the
13557 // frame: never output, and no block below ever references
13558 // them.
13559 if y + row >= self.height {
13560 break;
13561 }
13562 for col in 0..side {
13563 if x + col >= self.width {
13564 break;
13565 }
13566 let idx = row * side + col;
13567 let mut base = i32::from(prediction[idx]);
13568 if let Some((alpha_q3, ac_q3)) = cfl {
13569 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13570 }
13571 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13572 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13573 }
13574 }
13575 }
13576}
13577
13578/// Reads one plane's transform block, reconstructs it into `plane` at
13579/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
13580#[allow(clippy::too_many_arguments)]
13581fn read_plane(
13582 dec: &mut SymbolDecoder,
13583 cdfs: &mut Cdfs,
13584 set: TxbSet,
13585 scan: &[u16],
13586 plane_idx: usize,
13587 around: (bool, bool, i32),
13588 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
13589 // it for every plane's `txb` lookup (it is what an intra transform type's
13590 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
13591 tx_mode: usize,
13592 predict_mode: usize,
13593 angle_delta: i32,
13594 reach: Reach,
13595 // lane-wave1 step (i): unread -- this reader records its write
13596 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
13597 // stays in the signature so every call site still proves the plane is
13598 // exclusively held while its coefficients are parsed.
13599 _plane: &mut PlaneBuf<'static>,
13600 x: usize,
13601 y: usize,
13602 side: usize,
13603 tx_side: usize,
13604 base_q_idx: u8,
13605 cfl: Option<(i32, CflSrc)>,
13606 filter_intra: Option<usize>,
13607 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
13608 // smaller than its own block (spec `get_txb_ctx_general`'s
13609 // `plane_bsize != tx_size` branch), carrying the already-looked-up
13610 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
13611 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
13612 // formula below.
13613 luma_skip_ctx: Option<usize>,
13614 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
13615 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
13616) -> Result<Grid> {
13617 let skip_ctx = if plane_idx == 0 {
13618 luma_skip_ctx.unwrap_or(0)
13619 } else {
13620 // libaom `get_txb_ctx`: a chroma unit's context is
13621 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
13622 // plane block is bigger than the transform. Our chroma tables hold the
13623 // offset-7 rows first, so the caller adds 3 for the bigger-block case
13624 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
13625 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
13626 };
13627 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
13628 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
13629 // not by the block's ordinary `mode` (which is always DC_PRED whenever
13630 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
13631 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
13632 // filter-intra in AV1).
13633 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
13634 let mut coding = cdfs.txb(set, tx_mode);
13635 // Luma's `default_tx_type` is only a fallback for the sizes whose
13636 // `TxbSet` carries no symbol at all (32-point and up), which the spec
13637 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
13638 // *never* its own coded symbol (`coding.tx_type` is always `None` for
13639 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
13640 // the plane's own predicted mode (`default_intra_tx_type`) -- except
13641 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
13642 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
13643 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
13644 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
13645 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
13646 // narrows there — only `Chroma32` and up do).
13647 let default_tx_type = if plane_idx == 0 || side >= 32 {
13648 TxType::DctDct
13649 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
13650 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
13651 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
13652 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
13653 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
13654 // [`read_inter_plane`]'s own `side < 32` guard).
13655 inherited
13656 } else {
13657 default_intra_tx_type(predict_mode as u8)
13658 };
13659 let (grid, tx_type) = read_coeffs(
13660 dec,
13661 &mut coding,
13662 scan,
13663 skip_ctx,
13664 dc_sign_ctx(around.2),
13665 default_tx_type,
13666 None,
13667 )?;
13668 note_chroma_class1(plane_idx, tx_type);
13669 if plane_idx == 0 {
13670 fctx.luma_tx_type.with(|c| c.set(tx_type));
13671 }
13672 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
13673 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
13674 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
13675 // guard also assumes.
13676 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
13677 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
13678 // keyed by that true size, not the coded corner's -- so the corner
13679 // goes into the top-left of a `side`-sized grid, not the reverse.
13680 let levels = extend_corner(grid, tx_side, tx_side, side, side);
13681 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
13682 let tx = TxParams {
13683 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13684 ac_delta, tx_type, stride: 0,
13685 };
13686 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13687 let residual = tx.run(&levels);
13688 eprintln!(
13689 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
13690 );
13691 }
13692 push_intra_tx(
13693 plane_idx,
13694 x,
13695 y,
13696 side,
13697 side,
13698 false,
13699 predict_mode,
13700 angle_delta,
13701 reach,
13702 tx,
13703 &levels,
13704 cfl,
13705 filter_intra,
13706 smooth_neighbor, fctx,
13707 );
13708 // `record`'s neighbour state only reads whether *the coded grid* (not the
13709 // residual) has nonzero entries, so the levels this function already
13710 // built are what it wants back -- both arms of the old `tx_side == side`
13711 // branch returned exactly that, one of them through a full `to_vec` copy
13712 // of the grid per intra transform unit (lane-coefbuf).
13713 Ok(levels)
13714}
13715
13716/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
13717/// three planes, reconstructing them into `y`/`u`/`v` and updating
13718/// `neighbours`.
13719#[allow(clippy::too_many_arguments)]
13720fn decode_block(
13721 dec: &mut SymbolDecoder,
13722 cdfs: &mut Cdfs,
13723 neighbours: &mut Neighbours,
13724 at: (usize, usize),
13725 side: usize,
13726 luma_set: TxbSet,
13727 chroma_set: TxbSet,
13728 luma_tx: usize,
13729 chroma_tx: usize,
13730 scans: (&[u16], &[u16]),
13731 cfl: bool,
13732 y: &mut PlaneBuf<'static>,
13733 u: &mut PlaneBuf<'static>,
13734 v: &mut PlaneBuf<'static>,
13735 base_q_idx: u8,
13736 enable_filter_intra: bool,
13737 allow_screen_content_tools: bool,
13738 allow_intrabc: bool,
13739 scan32: &[u16],
13740 scan16: &[u16],
13741 scan8: &[u16],
13742 scan4: &[u16],
13743 tx_select: bool,
13744 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13745) -> Result<()> {
13746 let (r, c) = at;
13747 let (px, py) = (c * SUB, r * SUB);
13748 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13749 let palette_uv_cache = neighbours.palette_uv_cache(at);
13750 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13751 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
13752 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
13753 read_intra_mode(
13754 dec,
13755 cdfs,
13756 nb_above_mode,
13757 nb_left_mode,
13758 cfl,
13759 side,
13760 enable_filter_intra,
13761 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
13762 allow_screen_content_tools,
13763 allow_intrabc,
13764 Some((palette_ctx, &palette_cache)),
13765 &palette_uv_cache,
13766 r * (SUB / MI),
13767 c * (SUB / MI), fctx,
13768 )?;
13769 if at_tile_left && palette_y.is_some() {
13770 hit!(PALETTE_TILE_LEFT_HITS);
13771 }
13772 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
13773 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
13774 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
13775 // actual chroma-from-luma correlation, same as this decoder always did.
13776 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13777 DC_PRED
13778 } else {
13779 uv_mode
13780 };
13781 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13782 if smooth_neighbor {
13783 hit!(SMOOTH_LUMA_HITS);
13784 }
13785 let smooth_neighbor_uv =
13786 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
13787 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13788 eprintln!(
13789 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
13790 angle_delta_uv={angle_delta_uv}"
13791 );
13792 }
13793 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13794 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
13795 // block, skipped or not. `logical_tx` is what the loop filter's edge
13796 // lookup and the next block's own `tx_size_context` want (the *nominal*
13797 // transform size -- 64 even for the 64x64 corner-scanned case, spec
13798 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
13799 // which only differs from it at that one corner case.
13800 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
13801 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
13802 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
13803 // intrabc block reads NO tx-size symbol at all -- it takes
13804 // `maxRectTxSize` -- while every ordinary skipped intra block does read
13805 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
13806 // the tile from that block on (class `equal-range-means-unread`).
13807 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
13808 // tree instead (`read_var_tx_size`), the same syntax the inter block path
13809 // has always read -- libaom's `parse_decode_block` dispatches on
13810 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
13811 // intrabc block as inter.
13812 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
13813 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
13814 let intrabc_leaves = if intrabc_vartx {
13815 let max_tx = side.min(64);
13816 // `max_block_wide`/`max_block_high`: the frame's own mi grid
13817 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
13818 // right/bottom edge reads no split symbol for the units outside it.
13819 let mi_cols = 2 * y.true_width.div_ceil(8);
13820 let mi_rows = 2 * y.true_height.div_ceil(8);
13821 let side_mi = side / MI;
13822 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
13823 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
13824 let mut leaves = Vec::new();
13825 for row in (0..side_mi).step_by(max_tx / MI) {
13826 for col in (0..side_mi).step_by(max_tx / MI) {
13827 read_var_tx_size(
13828 dec, cdfs, neighbours, (mi_r, mi_c), side,
13829 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
13830 );
13831 }
13832 }
13833 hit!(INTRABC_VARTX_HITS);
13834 // The luma reconstruct loop below is a UNIFORM grid of one square
13835 // transform (the intra `tx_depth` shape), so a tree that resolved to
13836 // mixed leaf sizes is refused by name rather than reconstructed at the
13837 // wrong stride.
13838 let uniform = leaves
13839 .first()
13840 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
13841 if !uniform {
13842 return Err(unsupported(
13843 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
13844 ));
13845 }
13846 Some(leaves[0].2)
13847 } else {
13848 None
13849 };
13850 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
13851 (tx, if tx == 64 { 32 } else { tx })
13852 } else if tx_select && !intrabc_skip_tx {
13853 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
13854 (resolved, if resolved == 64 { 32 } else { resolved })
13855 } else {
13856 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
13857 // TX_64X64, so a 128x128 block is always FOUR luma transform units
13858 // even with `tx_select` off -- the TU loop below, never the
13859 // single-unit path.
13860 (side.min(64), luma_tx)
13861 };
13862 if tx_select && logical_tx < side && uv_mode != DC_PRED {
13863 hit!(SQ_CHROMA_TX_HITS);
13864 }
13865 let luma_set = if tx_select {
13866 txbset_for(logical_tx, reduced_tx_set)
13867 } else {
13868 luma_set
13869 };
13870 let luma_set = if intrabc_dv.is_some() {
13871 txbset_for_inter(logical_tx, reduced_tx_set)
13872 } else {
13873 luma_set
13874 };
13875 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
13876 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
13877 let (cpx, cpy) = (px / 2, py / 2);
13878 let chroma_side = side / 2;
13879 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
13880 // frame's own pre-loop-filter reconstruction (all loop filters are off
13881 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
13882 // block vector, with the BILINEAR kernel libaom forces for intrabc --
13883 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
13884 // odd, which is exactly what the bilinear taps then interpolate.
13885 flush_recon(fctx, y, u, v);
13886 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
13887 let mut yb = vec![0u16; side * side];
13888 mc::predict_with_filter(
13889 &y.data, y.width, y.true_width, y.true_height,
13890 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
13891 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
13892 );
13893 let mut ub = vec![0u16; chroma_side * chroma_side];
13894 mc::predict_with_filter(
13895 &u.data, u.width, u.true_width, u.true_height,
13896 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13897 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
13898 );
13899 let mut vb = vec![0u16; chroma_side * chroma_side];
13900 mc::predict_with_filter(
13901 &v.data, v.width, v.true_width, v.true_height,
13902 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13903 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
13904 );
13905 (yb, ub, vb)
13906 });
13907 // A palette-Y block's own prediction is the reconstructed colour-index
13908 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
13909 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
13910 // parameter through this function's dozen `y.reconstruct`/`read_plane`
13911 // sites. A split luma transform (`tx_select && logical_tx != side`)
13912 // would need the map sliced per-TU -- untested against a real
13913 // `--enable-palette=1` stream this round, so refuse by name rather than
13914 // guess at the slicing (charter's own named-acceptable fallback).
13915 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
13916 py.map
13917 .iter()
13918 .map(|&idx| py.colors[idx as usize])
13919 .collect()
13920 });
13921 // lane-t900 r32: the intrabc luma prediction rides the very same
13922 // whole-block override slot, so the multi-TU loop below windows it per
13923 // transform unit exactly like a palette map -- setting it once up front
13924 // handed the whole `side`x`side` buffer to the FIRST unit and left every
13925 // later one predicting off block edges (the var-tx tree above is what
13926 // first makes `logical_tx < side` reachable for an intrabc block).
13927 let palette_y_buf = match &intrabc_bufs {
13928 Some((yb, _, _)) => Some(yb.clone()),
13929 None => palette_y_buf,
13930 };
13931 // With one luma transform unit the whole `side`x`side` map is the
13932 // prediction; with several (`logical_tx != side`) each unit takes its own
13933 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
13934 // below (lane-palette2 r7) -- setting the full-block buffer here would be
13935 // taken by the FIRST unit and indexed at the wrong stride.
13936 if let Some(buf) = &palette_y_buf
13937 && logical_tx == side
13938 {
13939 set_palette_pred(buf.clone(), fctx);
13940 }
13941 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
13942 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
13943 // plane's own `reconstruct`/`read_plane` call below (never both planes at
13944 // once), since Y's own set-then-take already emptied the slot by the time
13945 // either of these run.
13946 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
13947 (
13948 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
13949 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
13950 )
13951 });
13952 // The chroma half of the intrabc prediction rides the same per-plane
13953 // override slot the UV-palette buffers do (set fresh before each plane's
13954 // own `reconstruct`/`read_plane` call below).
13955 let palette_uv_bufs = match &intrabc_bufs {
13956 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
13957 None => palette_uv_bufs,
13958 };
13959 if skip {
13960 // A skipped block codes no residual syntax at all (spec 5.11.34):
13961 // straight prediction, on every plane.
13962 //
13963 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
13964 // is skipped (only an INTER skip forces the largest transform), and
13965 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
13966 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
13967 // already written left/above of it inside this same block. Predicting
13968 // the whole `side`x`side` at once gives a different (uniformly off by
13969 // ~1) answer, which is exactly the residue this lane was chasing.
13970 // The palette/intrabc override path keeps the single-call shape (its
13971 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
13972 // untested for skip and unreachable in these streams).
13973 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
13974 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
13975 // per-unit prediction is keyed on the transform being smaller than
13976 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
13977 // narrower meaning (a READ split tx depth).
13978 let split_tx_skip =
13979 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
13980 if split_tx_skip {
13981 if tx_select {
13982 hit!(SKIP_SPLIT_TX_HITS);
13983 }
13984 let n_axis = side / logical_tx;
13985 for tu_row in 0..n_axis {
13986 for tu_col in 0..n_axis {
13987 let tu_px = px + tu_col * logical_tx;
13988 let tu_py = py + tu_row * logical_tx;
13989 if tu_px >= y.true_width || tu_py >= y.true_height {
13990 continue;
13991 }
13992 let tu_reach = tu_reach(
13993 side,
13994 side,
13995 tu_col * logical_tx,
13996 tu_row * logical_tx,
13997 logical_tx,
13998 reach,
13999 px,
14000 py,
14001 y.width,
14002 y.height, fctx,
14003 );
14004 push_intra(0,
14005 tu_px,
14006 tu_py,
14007 logical_tx,
14008 mode,
14009 angle_delta_y,
14010 tu_reach,
14011 &ZERO_RESIDUAL[..logical_tx * logical_tx],
14012 None,
14013 filter_intra,
14014 smooth_neighbor, fctx,
14015 );
14016 }
14017 }
14018 } else {
14019 push_intra(0,
14020 px,
14021 py,
14022 side,
14023 mode,
14024 angle_delta_y,
14025 reach,
14026 &ZERO_RESIDUAL[..side * side],
14027 None,
14028 filter_intra,
14029 smooth_neighbor, fctx,
14030 );
14031 }
14032 let ac = alpha.map(|_| cfl_src(px, py, side));
14033 let cn = (chroma_side / chroma_tx).max(1);
14034 for cu_row in 0..cn {
14035 for cu_col in 0..cn {
14036 let luma_span = chroma_tx * 2;
14037 let cu_r = if cn == 1 {
14038 reach
14039 } else {
14040 tu_reach(
14041 side, side,
14042 cu_col * luma_span, cu_row * luma_span, luma_span,
14043 reach, px, py, y.width, y.height, fctx,
14044 )
14045 };
14046 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14047 if let Some((ub, _)) = &palette_uv_bufs {
14048 set_palette_pred(ub.clone(), fctx);
14049 }
14050 push_intra(1,
14051 cu_x,
14052 cu_y,
14053 chroma_tx,
14054 uv_predict_mode,
14055 angle_delta_uv,
14056 cu_r,
14057 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14058 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14059 None,
14060 smooth_neighbor_uv, fctx,
14061 );
14062 if let Some((_, vb)) = &palette_uv_bufs {
14063 set_palette_pred(vb.clone(), fctx);
14064 }
14065 push_intra(2,
14066 cu_x,
14067 cu_y,
14068 chroma_tx,
14069 uv_predict_mode,
14070 angle_delta_uv,
14071 cu_r,
14072 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14073 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14074 None,
14075 smooth_neighbor_uv, fctx,
14076 );
14077 }
14078 }
14079 let luma_grid = vec![0i32; side * side];
14080 let u_grid = vec![0i32; chroma_side * chroma_side];
14081 let v_grid = vec![0i32; chroma_side * chroma_side];
14082 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14083 } else if logical_tx == side {
14084 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
14085 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
14086 // that arm was redundant -- and wrong at 128, where
14087 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
14088 // block is four units whether or not `tx_select` is on.
14089 // A single luma transform unit -- the old path, unchanged (including
14090 // the 64x64 corner case, `logical_tx == side == 64` with
14091 // `coeff_tx_side == 32`).
14092 let around = neighbours.around(at, side);
14093 let luma_grid = read_plane(
14094 dec,
14095 cdfs,
14096 luma_set,
14097 luma_scan,
14098 0,
14099 around[0],
14100 mode,
14101 mode,
14102 angle_delta_y,
14103 reach,
14104 y,
14105 px,
14106 py,
14107 side,
14108 coeff_tx_side,
14109 base_q_idx,
14110 None,
14111 filter_intra,
14112 None,
14113 smooth_neighbor, fctx,
14114 )?;
14115 let ac = alpha.map(|_| cfl_src(px, py, side));
14116 // Armed for exactly this block's two chroma reads (see
14117 // [`INTRABC_CHROMA_TX`]); the luma call above just set
14118 // [`LUMA_TX_TYPE`] to the type it coded.
14119 if intrabc_dv.is_some() {
14120 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14121 }
14122 if let Some((ub, _)) = &palette_uv_bufs {
14123 set_palette_pred(ub.clone(), fctx);
14124 }
14125 let u_grid = read_plane(
14126 dec,
14127 cdfs,
14128 chroma_set,
14129 scans.1,
14130 1,
14131 around[1],
14132 mode,
14133 uv_predict_mode,
14134 angle_delta_uv,
14135 reach,
14136 u,
14137 cpx,
14138 cpy,
14139 chroma_side,
14140 chroma_tx,
14141 base_q_idx,
14142 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14143 None,
14144 None,
14145 smooth_neighbor_uv, fctx,
14146 )?;
14147 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14148 eprintln!(
14149 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
14150 &u.data[cpy * u.width + cpx..][..chroma_side]
14151 );
14152 }
14153 if let Some((_, vb)) = &palette_uv_bufs {
14154 set_palette_pred(vb.clone(), fctx);
14155 }
14156 let v_grid = read_plane(
14157 dec,
14158 cdfs,
14159 chroma_set,
14160 scans.1,
14161 2,
14162 around[2],
14163 mode,
14164 uv_predict_mode,
14165 angle_delta_uv,
14166 reach,
14167 v,
14168 cpx,
14169 cpy,
14170 chroma_side,
14171 chroma_tx,
14172 base_q_idx,
14173 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14174 None,
14175 None,
14176 smooth_neighbor_uv, fctx,
14177 )?;
14178 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14179 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14180 } else {
14181 // Several luma transform units, raster order (spec
14182 // `transform_block`'s loop): the block's resolved transform is
14183 // genuinely smaller than its own side, so each tile of it predicts
14184 // and codes independently, its own context read fresh off whatever
14185 // the earlier tiles in this same block already wrote -- the same
14186 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
14187 let n_axis = side / logical_tx;
14188 let cn = (chroma_side / chroma_tx).max(1);
14189 // libaom's transform-block loop is over 64x64 luma "mu" chunks
14190 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
14191 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
14192 // before moving to the next one. Below 128 a block is a single chunk,
14193 // so this is byte-for-byte the all-luma-then-all-chroma order that has
14194 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
14195 // and reading all four luma units first desyncs the tile at the second
14196 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
14197 let nchunk = (side / 64).max(1);
14198 // `cn > 1` means the uv plane block is larger than the uv transform,
14199 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
14200 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
14201 let tpc = (n_axis / nchunk).max(1);
14202 let cpc = (cn / nchunk).max(1);
14203 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14204 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
14205 for ch_row in 0..nchunk {
14206 for ch_col in 0..nchunk {
14207 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14208 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14209 let tu_mi = (
14210 mi_r + tu_row * (logical_tx / MI),
14211 mi_c + tu_col * (logical_tx / MI),
14212 );
14213 let tu_px = px + tu_col * logical_tx;
14214 let tu_py = py + tu_row * logical_tx;
14215 // Same libaom clip as `decode_rect_split`'s loop above; a
14216 // square block only hangs off the frame when the frame's mi
14217 // dimensions are odd at the block's own level.
14218 if tu_px >= y.true_width || tu_py >= y.true_height {
14219 continue;
14220 }
14221 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14222 // A transform unit inside a block is NOT a block at that
14223 // position (lane-palette2 r12): `Reach::of` granted the
14224 // top-right 8x8 unit of a 16x16 D203 block bottom-left
14225 // pixels libaom refuses outright (`col_off > 0`), which is
14226 // the diagonal wedge seed 46 reconstructed wrong.
14227 let tu_reach = tu_reach(
14228 side,
14229 side,
14230 tu_col * logical_tx,
14231 tu_row * logical_tx,
14232 logical_tx,
14233 reach,
14234 px,
14235 py,
14236 y.width,
14237 y.height, fctx,
14238 );
14239 // This transform unit's own bsize (`logical_tx`) is smaller
14240 // than the block it sits in (`side`), so `txb_skip_ctx` is
14241 // the neighbour-magnitude table, not the lone-TU 0 (spec
14242 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
14243 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14244 if let Some(buf) = &palette_y_buf {
14245 hit!(PALETTE_SPLIT_TX_HITS);
14246 let mut window = vec![0u16; logical_tx * logical_tx];
14247 for row in 0..logical_tx {
14248 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
14249 window[row * logical_tx..][..logical_tx]
14250 .copy_from_slice(&buf[src..][..logical_tx]);
14251 }
14252 set_palette_pred(window, fctx);
14253 }
14254 let tu_grid = read_plane(
14255 dec,
14256 cdfs,
14257 luma_set,
14258 luma_scan,
14259 0,
14260 tu_around,
14261 mode,
14262 mode,
14263 angle_delta_y,
14264 tu_reach,
14265 y,
14266 tu_px,
14267 tu_py,
14268 logical_tx,
14269 // The unit's own COEFFICIENT grid, half its side at
14270 // TX_64X64 (a 64-point transform codes nothing past 32);
14271 // identical to `logical_tx` at every smaller size
14272 // (lane-sb128b r1).
14273 coeff_tx_side,
14274 base_q_idx,
14275 None,
14276 filter_intra,
14277 Some(tu_skip_ctx),
14278 smooth_neighbor, fctx,
14279 )?;
14280 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14281 eprintln!(
14282 "TRACE tu_bitpos mi=({},{}) tell={}",
14283 tu_mi.0,
14284 tu_mi.1,
14285 dec.debug_bitpos()
14286 );
14287 }
14288 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14289 }
14290 }
14291 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
14292 // this still runs after every luma unit of the block.
14293 let ac = alpha.map(|_| cfl_src(px, py, side));
14294 // The block's uv plane block is `chroma_side` across but its uv
14295 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
14296 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
14297 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
14298 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
14299 // FOUR units (lane-sb128b r2) -- one per mu chunk.
14300 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
14301 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
14302 // The chroma context arrays are indexed in LUMA mi, so this
14303 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
14304 // pixels span `2 * chroma_tx` luma ones.
14305 let luma_span = chroma_tx * 2;
14306 let cu_mi = (
14307 mi_r + cu_row * (luma_span / MI),
14308 mi_c + cu_col * (luma_span / MI),
14309 );
14310 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14311 let cu_reach = if cn == 1 {
14312 reach
14313 } else {
14314 tu_reach(
14315 side, side,
14316 cu_col * luma_span, cu_row * luma_span, luma_span,
14317 reach, px, py, y.width, y.height, fctx,
14318 )
14319 };
14320 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14321 if let Some((ub, _)) = &palette_uv_bufs {
14322 set_palette_pred(ub.clone(), fctx);
14323 }
14324 let u_grid = read_plane(
14325 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
14326 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
14327 chroma_tx, chroma_tx, base_q_idx,
14328 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14329 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14330 )?;
14331 if let Some((_, vb)) = &palette_uv_bufs {
14332 set_palette_pred(vb.clone(), fctx);
14333 }
14334 let v_grid = read_plane(
14335 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
14336 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
14337 chroma_tx, chroma_tx, base_q_idx,
14338 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14339 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14340 )?;
14341 if cn > 1 {
14342 hit!(CHROMA_SPLIT_TX_HITS);
14343 // Immediately, so the NEXT unit of this same block reads
14344 // this one's coefficient context (libaom's chroma
14345 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
14346 // 1 from this left neighbour -- measured against aomdec).
14347 // The same writes are replayed after `record_split_luma`
14348 // below, which would otherwise clobber them whole-block.
14349 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14350 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14351 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
14352 }
14353 last_grids = [u_grid, v_grid];
14354 }
14355 }
14356 }
14357 }
14358 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
14359 // context write; at `cn > 1` the per-unit writes above are what the
14360 // next block reads, so they run after this (last writer wins).
14361 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
14362 for (cu_mi, luma_span, u_grid, v_grid) in &units {
14363 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
14364 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
14365 }
14366 }
14367 // Unconditional, `size == 0` for a non-palette block: clears any stale
14368 // neighbour palette state the same way [`Neighbours::record`] always
14369 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
14370 // (the split-luma-TU branch above always refuses before reaching here
14371 // when `palette_y` is `Some`, so it is never live for that branch).
14372 let (py_size, py_colors) = palette_y
14373 .as_ref()
14374 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14375 neighbours.record_palette_y(at, side, py_size, py_colors);
14376 let (puv_size, puv_colors) = palette_uv
14377 .as_ref()
14378 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14379 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
14380 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
14381 neighbours.fill_lf_grid(
14382 (r * (SUB / MI), c * (SUB / MI)),
14383 side / MI,
14384 logical_tx as u8,
14385 0, fctx,
14386 );
14387 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
14388 // `decode_block`, key frames included, and the intrabc var-tx read above
14389 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
14390 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
14391 // row. Armed by the frame's own `allow_intrabc` so every other key frame
14392 // (whose readers use the deblock-grid approximation) is untouched.
14393 if allow_intrabc {
14394 set_txfm_ctxs(
14395 neighbours,
14396 (mi_r, mi_c),
14397 logical_tx,
14398 side / MI,
14399 side / MI,
14400 skip && intrabc_dv.is_some(),
14401 );
14402 }
14403 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
14404 Ok(())
14405}
14406
14407thread_local! {
14408 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
14409 /// root's HORZ arm, and 64x128 ones at its VERT arm.
14410 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14411 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14412 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
14413 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
14414 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
14415 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
14416 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
14417 /// inter frame) -- (128x64, 64x128).
14418 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
14419 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
14420 /// handed back var-tx leaves, so the per-transform-unit luma publication
14421 /// loop never ran and the block has to clear its own luma coefficient
14422 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
14423 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
14424 /// non-vacuous.
14425 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14426}
14427
14428/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
14429pub fn skip_vartx_luma_reset_hits() -> usize {
14430 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
14431}
14432
14433/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
14434pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
14435 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
14436}
14437
14438/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
14439/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
14440pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
14441 (
14442 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
14443 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
14444 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
14445 )
14446}
14447
14448/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
14449/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
14450/// `decode_inter_block`'s own rect path).
14451///
14452/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
14453/// transform unit, with the 128-specific geometry:
14454/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
14455/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
14456/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
14457/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
14458/// same CDF a 64x64 square block reads).
14459/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
14460/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
14461/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
14462/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
14463/// a chunk before moving to the next (the interleave lane-sb128b r3
14464/// measured at the 128x128 NONE root).
14465/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
14466/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
14467/// No CfL, no filter intra (both cap at 32x32) and no palette
14468/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
14469/// reader's own size gates already say so, and the guard below is defensive.
14470#[allow(clippy::too_many_arguments)]
14471fn decode_block_128rect(
14472 dec: &mut SymbolDecoder,
14473 cdfs: &mut Cdfs,
14474 neighbours: &mut Neighbours,
14475 at: (usize, usize),
14476 bw: usize,
14477 bh: usize,
14478 y: &mut PlaneBuf<'static>,
14479 u: &mut PlaneBuf<'static>,
14480 v: &mut PlaneBuf<'static>,
14481 base_q_idx: u8,
14482 enable_filter_intra: bool,
14483 allow_screen_content_tools: bool,
14484 tx_select: bool,
14485 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14486) -> Result<()> {
14487 let (r, c) = at;
14488 let (px, py) = (c * SUB, r * SUB);
14489 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14490 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14491 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14492 let palette_uv_cache = neighbours.palette_uv_cache(at);
14493 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14494 read_intra_mode_rect(
14495 dec,
14496 cdfs,
14497 nb_above_mode,
14498 nb_left_mode,
14499 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
14500 // 13-symbol no-CFL CDF here, never the 14-symbol one.
14501 false,
14502 true,
14503 bw,
14504 bh,
14505 enable_filter_intra,
14506 neighbours.skip_txfm_ctx(mi_r, mi_c),
14507 allow_screen_content_tools,
14508 Some((palette_ctx, &palette_cache)),
14509 &palette_uv_cache,
14510 mi_r,
14511 mi_c, fctx,
14512 )?;
14513 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
14514 return Err(unsupported(
14515 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
14516 their size gates caps at 64x64 or below, so none of these symbols exists there)",
14517 ));
14518 }
14519 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14520 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14521 if smooth_neighbor {
14522 hit!(SMOOTH_LUMA_HITS);
14523 }
14524 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
14525 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
14526 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
14527 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
14528 let depth = if tx_select {
14529 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
14530 // the real `TXFM_CONTEXT` bands, and compares them against
14531 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
14532 // every 128-axis block, hence the `min(64)`.
14533 let ctx = if in_inter {
14534 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
14535 } else {
14536 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
14537 };
14538 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14539 } else {
14540 0
14541 };
14542 if depth != 0 {
14543 hit!(TX_DEPTH_HITS);
14544 }
14545 hit_do! {
14546 INTRA_SB128_DEPTH_HITS.with(|c| {
14547 let mut h = c.get();
14548 h[depth.min(2)] += 1;
14549 c.set(h);
14550 });
14551 }
14552 let logical_tx = 64 >> depth;
14553 // A 64-point transform codes nothing past its low 32 coefficients.
14554 let coeff_tx_side = logical_tx.min(32);
14555 let luma_set = txbset_for(logical_tx, reduced_tx_set);
14556 let luma_scan = default_scan(coeff_tx_side);
14557 let chroma_tx = 32;
14558 let chroma_scan = default_scan(chroma_tx);
14559 let (cpx, cpy) = (px / 2, py / 2);
14560 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
14561 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14562 let (nch_x, nch_y) = (bw / 64, bh / 64);
14563 // One 32x32 chroma unit per mu chunk, per plane.
14564 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
14565 let tpc = 64 / logical_tx;
14566 let zero_tu = vec![0i32; logical_tx * logical_tx];
14567 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
14568 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14569 let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new();
14570 for ch_row in 0..nch_y {
14571 for ch_col in 0..nch_x {
14572 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14573 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14574 let tu_mi = (
14575 mi_r + tu_row * (logical_tx / MI),
14576 mi_c + tu_col * (logical_tx / MI),
14577 );
14578 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
14579 // libaom clips the transform loop to
14580 // `max_blocks_wide/high`: a unit whose top-left sample is
14581 // outside the frame is never coded.
14582 if tu_px >= y.true_width || tu_py >= y.true_height {
14583 continue;
14584 }
14585 // Edge availability of a unit INSIDE a block, with the
14586 // 128 geometry -- `has_top_right` is false for a block
14587 // whose largest side is > 64, which [`Reach::of_rect`]
14588 // already answered for the block and [`tu_reach`] carries
14589 // down to the units on its own top row.
14590 let tu_r = tu_reach(
14591 bw,
14592 bh,
14593 tu_col * logical_tx,
14594 tu_row * logical_tx,
14595 logical_tx,
14596 reach,
14597 px,
14598 py,
14599 y.width,
14600 y.height, fctx,
14601 );
14602 if skip {
14603 push_intra(0,
14604 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
14605 None, smooth_neighbor, fctx,
14606 );
14607 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
14608 continue;
14609 }
14610 // The unit is smaller than its block, so `txb_skip_ctx`
14611 // is the neighbour-magnitude table, never the lone-TU 0.
14612 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14613 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14614 let tu_grid = read_plane(
14615 dec,
14616 cdfs,
14617 luma_set,
14618 &luma_scan,
14619 0,
14620 tu_around,
14621 mode,
14622 mode,
14623 angle_delta_y,
14624 tu_r,
14625 y,
14626 tu_px,
14627 tu_py,
14628 logical_tx,
14629 coeff_tx_side,
14630 base_q_idx,
14631 None,
14632 None,
14633 Some(tu_skip_ctx),
14634 smooth_neighbor, fctx,
14635 )?;
14636 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14637 }
14638 }
14639 // The chroma context arrays are indexed in LUMA mi, so this
14640 // unit's anchor is its own 64x64 mu chunk.
14641 let luma_span = chroma_tx * 2;
14642 let cu_mi = (
14643 mi_r + ch_row * (luma_span / MI),
14644 mi_c + ch_col * (luma_span / MI),
14645 );
14646 let cu_r = tu_reach(
14647 bw,
14648 bh,
14649 ch_col * luma_span,
14650 ch_row * luma_span,
14651 luma_span,
14652 reach,
14653 px,
14654 py,
14655 y.width,
14656 y.height, fctx,
14657 );
14658 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
14659 if skip {
14660 push_intra(1,
14661 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14662 None, smooth_neighbor_uv, fctx,
14663 );
14664 push_intra(2,
14665 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14666 None, smooth_neighbor_uv, fctx,
14667 );
14668 continue;
14669 }
14670 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14671 let u_grid = read_plane(
14672 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
14673 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14674 Some(3), smooth_neighbor_uv, fctx,
14675 )?;
14676 let v_grid = read_plane(
14677 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
14678 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14679 Some(3), smooth_neighbor_uv, fctx,
14680 )?;
14681 hit!(CHROMA_SPLIT_TX_HITS);
14682 // Immediately, so the NEXT unit of this same block reads this
14683 // one's coefficient context; replayed after `record_split_luma_rect`
14684 // below, which would otherwise clobber them whole-block.
14685 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14686 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14687 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
14688 last_grids = [u_grid, v_grid];
14689 }
14690 }
14691 if skip {
14692 neighbours.record_rect(
14693 at,
14694 bw,
14695 bh,
14696 mode,
14697 uv_predict_mode,
14698 &[
14699 &ZERO_RESIDUAL[..bw * bh],
14700 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14701 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14702 ],
14703 );
14704 } else {
14705 neighbours.record_split_luma_rect(
14706 at,
14707 bw,
14708 bh,
14709 mode,
14710 uv_predict_mode,
14711 [&last_grids[0], &last_grids[1]],
14712 );
14713 for (cu_mi, u_grid, v_grid) in &units {
14714 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
14715 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
14716 }
14717 }
14718 // No palette exists at this size; the unconditional stamp clears any
14719 // stale neighbour palette state, as every other block path does.
14720 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
14721 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
14722 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14723 neighbours.fill_lf_grid_rect(
14724 (mi_r, mi_c),
14725 bw / MI,
14726 bh / MI,
14727 logical_tx as u8,
14728 logical_tx as u8,
14729 0, fctx,
14730 );
14731 if in_inter {
14732 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
14733 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
14734 // inter frame, intra ones included: an intra block stamps its
14735 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
14736 // A key frame has no var-tx tree and its readers use the deblock grid,
14737 // so this is the inter path's alone.
14738 txfm_partition_update_rect(
14739 neighbours,
14740 (mi_r, mi_c),
14741 (logical_tx, logical_tx),
14742 (bw, bh),
14743 );
14744 hit_do! {
14745 INTRA128_IN_INTER_HITS.with(|c| {
14746 let mut h = c.get();
14747 h[usize::from(bw < bh)] += 1;
14748 c.set(h);
14749 });
14750 }
14751 } else if bw > bh {
14752 hit!(INTRA_SB128_HORZ_HITS);
14753 } else {
14754 hit!(INTRA_SB128_VERT_HITS);
14755 }
14756 Ok(())
14757}
14758
14759
14760/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
14761/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
14762/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
14763/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
14764/// just-decoded mode, not the enclosing slot's stale one, is the true
14765/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
14766/// units, which is what its coefficient context (finer than [`SUB`]) is read
14767/// at. Returns the mode this leaf decoded, for the caller's own
14768/// `prev_leaf`/final mode-writeback bookkeeping.
14769#[allow(clippy::too_many_arguments)]
14770/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
14771/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
14772/// `above_mode[col]`, and its true above neighbour is the mi directly above
14773/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
14774/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
14775/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
14776/// (bottom-right) into both, as this path did, is right only when all four
14777/// leaves happen to share a mode. `done` may be short at the true frame edge
14778/// (the straddle caller filters positions off the frame), so each side falls
14779/// back to the last leaf actually decoded.
14780fn write_back_split_modes(
14781 neighbours: &mut Neighbours,
14782 done: &[((usize, usize), usize)],
14783 parent_mi: (usize, usize),
14784 slot: (usize, usize),
14785) {
14786 let (sr, sc) = slot;
14787 let Some(&(_, last)) = done.last() else {
14788 return;
14789 };
14790 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
14791 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
14792 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
14793}
14794
14795fn decode_leaf8(
14796 dec: &mut SymbolDecoder,
14797 cdfs: &mut Cdfs,
14798 neighbours: &mut Neighbours,
14799 outer_at: (usize, usize),
14800 leaf_mi: (usize, usize),
14801 scans: (&[u16], &[u16]),
14802 prev_leaf: Option<((usize, usize), usize)>,
14803 y: &mut PlaneBuf<'static>,
14804 u: &mut PlaneBuf<'static>,
14805 v: &mut PlaneBuf<'static>,
14806 base_q_idx: u8,
14807 enable_filter_intra: bool,
14808 allow_screen_content_tools: bool,
14809 allow_intrabc: bool,
14810 tx_select: bool,
14811 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14812) -> Result<usize> {
14813 let (r, c) = outer_at;
14814 // lane-modectx r1: the group's own availability-correct fallback pair, not
14815 // the raw coarse bands (which leak across a tile edge -- see
14816 // `modes_above_left`).
14817 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
14818 if let Some(((pr, pc), pmode)) = prev_leaf {
14819 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
14820 above_mode = pmode;
14821 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
14822 left_mode = pmode;
14823 }
14824 }
14825 // The mi-exact neighbour wins over both the coarse 16x16 slot and
14826 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
14827 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
14828 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
14829 // lane-rectsplitx r2 swept this arm into
14830 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
14831 // "no neighbour" at a tile edge, where the coarse cell holds the block
14832 // above/left of it inside the same 16x16.
14833 let (above_mode, left_mode) =
14834 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
14835 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
14836 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
14837 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
14838 // this leaf's `smooth_neighbor` is built from -- passing `false` here
14839 // filtered a directional chroma block's edge at the wrong strength
14840 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
14841 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
14842 // with the coarse [`SUB`] slot as the fallback when no block recorded
14843 // that exact mi cell.
14844 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
14845 if smooth_neighbor {
14846 hit!(SMOOTH_LUMA_HITS);
14847 }
14848 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
14849 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
14850 // `decode_block` caller at 16x16 and up.
14851 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
14852 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
14853 // `read_palette_mode_info`), at its REAL mi position -- passing
14854 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
14855 // moment a real 8x8 palette block fired, which is where every 8-bit
14856 // `--tune-content=screen --min-partition-size=8` stream stopped.
14857 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
14858 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
14859 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14860 read_intra_mode(
14861 dec,
14862 cdfs,
14863 above_mode,
14864 left_mode,
14865 true,
14866 8,
14867 enable_filter_intra,
14868 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
14869 allow_screen_content_tools,
14870 allow_intrabc,
14871 Some((palette_ctx, &palette_cache)),
14872 &palette_uv_cache,
14873 leaf_mi.0,
14874 leaf_mi.1, fctx,
14875 )?;
14876 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
14877 // `read_intra_mode` and then decoded the block as if it were ordinary
14878 // intra. libaom's `is_inter_block` counts an intrabc block
14879 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
14880 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
14881 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
14882 // same value with a different interval, so the tile desynced at the very
14883 // next symbol (class `wrong-alphabet-same-value`). Everything below
14884 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
14885 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
14886 if intrabc_dv.is_some() {
14887 hit!(LEAF8_INTRABC_HITS);
14888 }
14889 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
14890 // index map, mapped through the base colours, IS the block's prediction --
14891 // carried to the next `reconstruct`/`read_plane` through the same
14892 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
14893 let palette_y_buf: Option<Vec<u16>> = palette_y
14894 .as_ref()
14895 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
14896 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
14897 (
14898 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14899 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14900 )
14901 });
14902 let (pal_y_size, pal_y_colors) =
14903 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14904 let (pal_uv_size, pal_uv_colors) =
14905 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14906 if palette_y.is_some() || palette_uv.is_some() {
14907 hit!(PALETTE_LEAF8_HITS);
14908 }
14909 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14910 DC_PRED
14911 } else {
14912 uv_mode
14913 };
14914 neighbours.above_uv_mode[c] = uv_predict_mode;
14915 neighbours.left_uv_mode[r] = uv_predict_mode;
14916 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
14917 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
14918 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
14919 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
14920 // transform units, same raster-order per-TU pattern `decode_block`'s
14921 // multi-TU branch runs).
14922 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
14923 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
14924 // intrabc block, so a SKIPPED one takes the largest transform and an
14925 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
14926 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
14927 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
14928 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
14929 let mut leaves = Vec::new();
14930 let mi_cols = 2 * y.true_width.div_ceil(8);
14931 let mi_rows = 2 * y.true_height.div_ceil(8);
14932 read_var_tx_size(
14933 dec,
14934 cdfs,
14935 neighbours,
14936 leaf_mi,
14937 8,
14938 (
14939 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
14940 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
14941 ),
14942 (8, 8),
14943 0,
14944 0,
14945 0,
14946 &mut leaves,
14947 );
14948 hit!(INTRABC_VARTX_HITS);
14949 leaves.first().map_or(8, |l| l.2)
14950 } else if tx_select && intrabc_dv.is_none() {
14951 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
14952 } else {
14953 8
14954 };
14955 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
14956 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
14957 let (cpx, cpy) = (px / 2, py / 2);
14958 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
14959 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
14960 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
14961 // the full-pel block vector, with the BILINEAR kernel libaom forces.
14962 flush_recon(fctx, y, u, v);
14963 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14964 let mut yb = vec![0u16; 8 * 8];
14965 mc::predict_with_filter(
14966 &y.data, y.width, y.true_width, y.true_height,
14967 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14968 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14969 );
14970 let mut ub = vec![0u16; 4 * 4];
14971 mc::predict_with_filter(
14972 &u.data, u.width, u.true_width, u.true_height,
14973 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14974 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14975 );
14976 let mut vb = vec![0u16; 4 * 4];
14977 mc::predict_with_filter(
14978 &v.data, v.width, v.true_width, v.true_height,
14979 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14980 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14981 );
14982 (yb, ub, vb)
14983 });
14984 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
14985 // `decode_block` uses: set fresh right before each plane's own
14986 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
14987 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
14988 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
14989 // first shape that reaches that loop with an override set).
14990 let palette_y_buf = match &intrabc_bufs {
14991 Some((yb, _, _)) => Some(yb.clone()),
14992 None => palette_y_buf,
14993 };
14994 let (luma_grid, u_grid, v_grid);
14995 if skip {
14996 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
14997 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
14998 // transform units, each off the units already written left/above of
14999 // it inside this same leaf -- an intra block's transform size is read
15000 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
15001 // A palette block's prediction is the whole-block index map, never
15002 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
15003 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
15004 // even when `tx_depth` resolved to TX_4X4.
15005 if resolved == 4 && palette_y_buf.is_none() {
15006 hit!(SKIP_SPLIT_TX_HITS);
15007 for tu_row in 0..2 {
15008 for tu_col in 0..2 {
15009 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
15010 if tu_px >= y.true_width || tu_py >= y.true_height {
15011 continue;
15012 }
15013 let tu_reach = tu_reach(
15014 8,
15015 8,
15016 tu_col * 4,
15017 tu_row * 4,
15018 4,
15019 reach,
15020 px,
15021 py,
15022 y.width,
15023 y.height, fctx,
15024 );
15025 push_intra(0,
15026 tu_px,
15027 tu_py,
15028 4,
15029 mode,
15030 angle_delta_y,
15031 tu_reach,
15032 &ZERO_RESIDUAL[..16],
15033 None,
15034 filter_intra,
15035 smooth_neighbor, fctx,
15036 );
15037 }
15038 }
15039 } else {
15040 if let Some(buf) = &palette_y_buf {
15041 set_palette_pred(buf.clone(), fctx);
15042 }
15043 push_intra(0,
15044 px,
15045 py,
15046 8,
15047 mode,
15048 angle_delta_y,
15049 reach,
15050 &ZERO_RESIDUAL[..64],
15051 None,
15052 filter_intra,
15053 smooth_neighbor, fctx,
15054 );
15055 }
15056 let ac = alpha.map(|_| cfl_src(px, py, 8));
15057 if let Some((_, ub, _)) = &intrabc_bufs {
15058 set_palette_pred(ub.clone(), fctx);
15059 } else if let Some((ub, _)) = &palette_uv_bufs {
15060 set_palette_pred(ub.clone(), fctx);
15061 }
15062 push_intra(1,
15063 cpx,
15064 cpy,
15065 4,
15066 uv_predict_mode,
15067 angle_delta_uv,
15068 reach,
15069 &ZERO_RESIDUAL[..16],
15070 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15071 None,
15072 smooth_neighbor_uv, fctx,
15073 );
15074 if let Some((_, _, vb)) = &intrabc_bufs {
15075 set_palette_pred(vb.clone(), fctx);
15076 } else if let Some((_, vb)) = &palette_uv_bufs {
15077 set_palette_pred(vb.clone(), fctx);
15078 }
15079 push_intra(2,
15080 cpx,
15081 cpy,
15082 4,
15083 uv_predict_mode,
15084 angle_delta_uv,
15085 reach,
15086 &ZERO_RESIDUAL[..16],
15087 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15088 None,
15089 smooth_neighbor_uv, fctx,
15090 );
15091 luma_grid = Grid::Zero(64);
15092 u_grid = Grid::Zero(16);
15093 v_grid = Grid::Zero(16);
15094 } else if resolved != 4 {
15095 let around = neighbours.around_mi(leaf_mi, 8);
15096 if let Some(buf) = &palette_y_buf {
15097 set_palette_pred(buf.clone(), fctx);
15098 }
15099 luma_grid = read_plane(
15100 dec,
15101 cdfs,
15102 if intrabc_dv.is_some() {
15103 txbset_for_inter(8, reduced_tx_set)
15104 } else if reduced_tx_set {
15105 TxbSet::Luma8
15106 } else {
15107 TxbSet::Luma8Set1
15108 },
15109 scans.0,
15110 0,
15111 around[0],
15112 mode,
15113 mode,
15114 angle_delta_y,
15115 reach,
15116 y,
15117 px,
15118 py,
15119 8,
15120 TX8,
15121 base_q_idx,
15122 None,
15123 filter_intra,
15124 None,
15125 smooth_neighbor, fctx,
15126 )?;
15127 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
15128 // an intrabc block's chroma tx_type is the colocated LUMA transform's
15129 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
15130 if intrabc_dv.is_some() {
15131 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15132 }
15133 let ac = alpha.map(|_| cfl_src(px, py, 8));
15134 if let Some((_, ub, _)) = &intrabc_bufs {
15135 set_palette_pred(ub.clone(), fctx);
15136 } else if let Some((ub, _)) = &palette_uv_bufs {
15137 set_palette_pred(ub.clone(), fctx);
15138 }
15139 u_grid = read_plane(
15140 dec,
15141 cdfs,
15142 TxbSet::Chroma4,
15143 scans.1,
15144 1,
15145 around[1],
15146 mode,
15147 uv_predict_mode,
15148 angle_delta_uv,
15149 reach,
15150 u,
15151 cpx,
15152 cpy,
15153 4,
15154 TX4,
15155 base_q_idx,
15156 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15157 None,
15158 None,
15159 smooth_neighbor_uv, fctx,
15160 )?;
15161 if let Some((_, _, vb)) = &intrabc_bufs {
15162 set_palette_pred(vb.clone(), fctx);
15163 } else if let Some((_, vb)) = &palette_uv_bufs {
15164 set_palette_pred(vb.clone(), fctx);
15165 }
15166 v_grid = read_plane(
15167 dec,
15168 cdfs,
15169 TxbSet::Chroma4,
15170 scans.1,
15171 2,
15172 around[2],
15173 mode,
15174 uv_predict_mode,
15175 angle_delta_uv,
15176 reach,
15177 v,
15178 cpx,
15179 cpy,
15180 4,
15181 TX4,
15182 base_q_idx,
15183 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15184 None,
15185 None,
15186 smooth_neighbor_uv, fctx,
15187 )?;
15188 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
15189 // two chroma reads (`decode_block`'s own tail does the same) -- left
15190 // set, every later chroma block would inherit this luma tx_type,
15191 // which picks the scan and the inverse transform.
15192 fctx.intrabc_chroma_tx.with(|c| c.set(None));
15193 } else {
15194 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
15195 // grid of 4x4 transform units, each predicted from the leaf's own
15196 // 8x8 `mode` and reading its own fresh context off the earlier
15197 // units in this same leaf (the same per-TU pattern `decode_block`'s
15198 // multi-TU branch runs at bigger blocks).
15199 for tu_row in 0..2 {
15200 for tu_col in 0..2 {
15201 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15202 let tu_px = px + tu_col * 4;
15203 let tu_py = py + tu_row * 4;
15204 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15205 if crate::encode::Reach::in_vert_ab() {
15206 hit!(VERT_AB_TX4_HITS);
15207 }
15208 let tu_reach = tu_reach(
15209 8,
15210 8,
15211 tu_col * 4,
15212 tu_row * 4,
15213 4,
15214 reach,
15215 px,
15216 py,
15217 y.width,
15218 y.height, fctx,
15219 );
15220 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15221 // Each 4x4 unit predicts from its own window of the block's
15222 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
15223 // 16x16 and up) -- the whole-block buffer would be taken by
15224 // the FIRST unit and indexed at the wrong stride.
15225 if let Some(buf) = &palette_y_buf {
15226 hit!(PALETTE_SPLIT_TX_HITS);
15227 let mut window = vec![0u16; 16];
15228 for row in 0..4 {
15229 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
15230 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
15231 }
15232 set_palette_pred(window, fctx);
15233 }
15234 let tu_grid = read_plane(
15235 dec,
15236 cdfs,
15237 if intrabc_dv.is_some() {
15238 txbset_for_inter(4, reduced_tx_set)
15239 } else if reduced_tx_set {
15240 TxbSet::Luma4
15241 } else {
15242 TxbSet::Luma4Set1
15243 },
15244 scans.1,
15245 0,
15246 tu_around,
15247 mode,
15248 mode,
15249 angle_delta_y,
15250 tu_reach,
15251 y,
15252 tu_px,
15253 tu_py,
15254 4,
15255 4,
15256 base_q_idx,
15257 None,
15258 filter_intra,
15259 Some(tu_skip_ctx),
15260 smooth_neighbor, fctx,
15261 )?;
15262 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15263 eprintln!(
15264 "TRACE tu_bitpos mi=({},{}) tell={}",
15265 tu_mi.0,
15266 tu_mi.1,
15267 dec.debug_bitpos()
15268 );
15269 }
15270 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15271 }
15272 }
15273 let ac = alpha.map(|_| cfl_src(px, py, 8));
15274 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15275 if let Some((ub, _)) = &palette_uv_bufs {
15276 set_palette_pred(ub.clone(), fctx);
15277 }
15278 u_grid = read_plane(
15279 dec,
15280 cdfs,
15281 TxbSet::Chroma4,
15282 scans.1,
15283 1,
15284 chroma_around[1],
15285 mode,
15286 uv_predict_mode,
15287 angle_delta_uv,
15288 reach,
15289 u,
15290 cpx,
15291 cpy,
15292 4,
15293 TX4,
15294 base_q_idx,
15295 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15296 None,
15297 None,
15298 smooth_neighbor_uv, fctx,
15299 )?;
15300 if let Some((_, vb)) = &palette_uv_bufs {
15301 set_palette_pred(vb.clone(), fctx);
15302 }
15303 v_grid = read_plane(
15304 dec,
15305 cdfs,
15306 TxbSet::Chroma4,
15307 scans.1,
15308 2,
15309 chroma_around[2],
15310 mode,
15311 uv_predict_mode,
15312 angle_delta_uv,
15313 reach,
15314 v,
15315 cpx,
15316 cpy,
15317 4,
15318 TX4,
15319 base_q_idx,
15320 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15321 None,
15322 None,
15323 smooth_neighbor_uv, fctx,
15324 )?;
15325 // `record_split_luma` expects a `record`-style `(r, c)` position in
15326 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
15327 // already in mi units, so calling it here double-scaled the
15328 // position. Plane 0 is already correct per-TU from the
15329 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
15330 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
15331 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
15332 // leaf's own 8x8 side over `MI`).
15333 let side_mi = 2;
15334 for cell in 0..side_mi {
15335 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
15336 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
15337 }
15338 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15339 let bound_h = round_up_even(neighbours.mi_rows);
15340 let bound_w = round_up_even(neighbours.mi_cols);
15341 let u_state = neighbour_state(&u_grid);
15342 let v_state = neighbour_state(&v_grid);
15343 for cell in 0..side_mi {
15344 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15345 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15346 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15347 }
15348 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15349 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15350 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15351 }
15352 }
15353 // This leaf's own palette state into the mi-granular above/left bands
15354 // (sizes 0 when it used none, which is what clears a previous block's
15355 // palette out of the next block's ctx and colour cache).
15356 {
15357 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15358 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15359 }
15360 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15361 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
15362 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15363 // own copy; only an intrabc var-tx read consumes these bands on the intra
15364 // path, so the write is armed by `allow_intrabc`.
15365 if allow_intrabc {
15366 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
15367 }
15368 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15369 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15370 return Ok(mode);
15371 }
15372 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15373 // This leaf's own palette state into the mi-granular above/left bands
15374 // (sizes 0 when it used none, which is what clears a previous block's
15375 // palette out of the next block's ctx and colour cache).
15376 {
15377 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15378 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15379 }
15380 hit!(INTER8_SKIP_BAND_HITS);
15381 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15382 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
15383 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
15384 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
15385 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
15386 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
15387 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
15388 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
15389 // wrong CDF row, so the msac range diverged mid-frame with no refusal
15390 // (class `wrong-alphabet-same-value`; the ReelB key frame at
15391 // -ss 900, first bad luma sample row 186 col 1803).
15392 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
15393 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15394 // own copy; only an intrabc var-tx read consumes these bands on the intra
15395 // path, so the write is armed by `allow_intrabc`.
15396 if allow_intrabc {
15397 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
15398 }
15399 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15400 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
15401 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
15402 // publish its own cells exactly like `decode_block` does.
15403 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15404 Ok(mode)
15405}
15406
15407/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
15408/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
15409/// bottom, where no partition symbol is read at all -- `decode_block` runs
15410/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
15411/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
15412/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
15413/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
15414/// of the 2x2 4x4 group carries chroma syntax at all.
15415#[allow(clippy::too_many_arguments)]
15416fn read_intra_mode_sub8(
15417 dec: &mut SymbolDecoder,
15418 cdfs: &mut Cdfs,
15419 above_mode: usize,
15420 left_mode: usize,
15421 has_chroma: bool,
15422 enable_filter_intra: bool,
15423 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
15424 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
15425 // from the wrong row is the same VALUE with a different interval, so it
15426 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
15427 fi_class: usize,
15428 skip_ctx: usize,
15429 allow_intrabc: bool,
15430 mi_r: usize,
15431 mi_c: usize, fctx: &crate::decode::FrameCtx,
15432) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
15433 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15434 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15435 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
15436 }
15437 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15438 if trace {
15439 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
15440 }
15441 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
15442 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15443 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15444 if allow_intrabc {
15445 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15446 if use_intrabc {
15447 return Err(unsupported(
15448 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
15449 ));
15450 }
15451 }
15452 let above_ctx = INTRA_MODE_CTX[above_mode];
15453 let left_ctx = INTRA_MODE_CTX[left_mode];
15454 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15455 if trace {
15456 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15457 }
15458 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
15459 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
15460 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
15461 // symbol. Reading one consumed a symbol the encoder never wrote and
15462 // desynced the tile at the very next element.
15463 let angle_delta_y = 0;
15464 let chroma = if has_chroma {
15465 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15466 if trace {
15467 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
15468 }
15469 if (9..=12).contains(&uv_mode) {
15470 hit!(SMOOTH_UV_HITS);
15471 }
15472 let alpha = if uv_mode == UV_CFL_PRED {
15473 Some(read_cfl_alphas(dec, cdfs))
15474 } else {
15475 None
15476 };
15477 if (V_PRED..=D67_PRED).contains(&uv_mode) {
15478 hit!(DIRECTIONAL_UV_HITS);
15479 }
15480 // See the luma comment above: no angle delta below 8x8.
15481 let angle_delta_uv = 0;
15482 Some((uv_mode, angle_delta_uv, alpha))
15483 } else {
15484 None
15485 };
15486 let mut filter_intra = None;
15487 if mode == DC_PRED && enable_filter_intra {
15488 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
15489 if trace {
15490 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
15491 }
15492 if use_filter_intra {
15493 hit!(FILTER_INTRA_HITS);
15494 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
15495 filter_intra = Some(fi_mode);
15496 }
15497 }
15498 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
15499}
15500
15501/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
15502/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
15503/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
15504/// bookkeeping needs no change. Each leaf reads its own luma mode info,
15505/// neighboured off the *previously decoded leaf in this same group* on
15506/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
15507/// pattern, one level deeper); chroma is read and reconstructed exactly
15508/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
15509/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
15510/// derivation.
15511#[allow(clippy::too_many_arguments)]
15512fn decode_leaf_split4(
15513 dec: &mut SymbolDecoder,
15514 cdfs: &mut Cdfs,
15515 neighbours: &mut Neighbours,
15516 outer_at: (usize, usize),
15517 leaf_mi: (usize, usize),
15518 scan4: &[u16],
15519 prev_leaf: Option<((usize, usize), usize)>,
15520 y: &mut PlaneBuf<'static>,
15521 u: &mut PlaneBuf<'static>,
15522 v: &mut PlaneBuf<'static>,
15523 base_q_idx: u8,
15524 enable_filter_intra: bool,
15525 allow_intrabc: bool,
15526 reduced_tx_set: bool,
15527 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
15528 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
15529 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
15530 fctx: &crate::decode::FrameCtx,
15531) -> Result<(usize, usize)> {
15532 hit!(SUB8_SPLIT_HITS);
15533 let (r, c) = outer_at;
15534 let mut above_mode = neighbours.above_mode[c];
15535 let mut left_mode = neighbours.left_mode[r];
15536 if let Some(((pr, pc), pmode)) = prev_leaf {
15537 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15538 above_mode = pmode;
15539 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15540 left_mode = pmode;
15541 }
15542 }
15543 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
15544 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
15545 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15546 let mut leaf_modes = [0usize; 4];
15547 let mut leaf_skips = [false; 4];
15548 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15549 for i in 0..4usize {
15550 let (dr, dc) = (i / 2, i % 2);
15551 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
15552 // Neighbour modes at real mi granularity: inside the group the
15553 // sibling leaf, outside it the split-leaf map when the adjacent mi
15554 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
15555 // `sub8_mode_col`'s doc).
15556 let leaf_above = if dr == 0 {
15557 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15558 } else {
15559 leaf_modes[i - 2]
15560 };
15561 let leaf_left = if dc == 0 {
15562 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15563 } else {
15564 leaf_modes[i - 1]
15565 };
15566 let has_chroma = i == 3;
15567 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15568 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15569 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15570 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
15571 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15572 )?;
15573 leaf_modes[i] = mode;
15574 leaf_skips[i] = skip;
15575 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
15576 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15577 if smooth_neighbor {
15578 hit!(SMOOTH_LUMA_HITS);
15579 }
15580 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15581 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
15582 if skip {
15583 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
15584 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
15585 } else {
15586 let tu_around = neighbours.around_mi(lmi, 4)[0];
15587 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
15588 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
15589 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
15590 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
15591 // off the wrong CDF on the very first leaf and desynced the tile.
15592 let tu_grid = read_plane(
15593 dec,
15594 cdfs,
15595 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
15596 scan4,
15597 0,
15598 tu_around,
15599 mode,
15600 mode,
15601 angle_delta_y,
15602 reach,
15603 y,
15604 px,
15605 py,
15606 4,
15607 4,
15608 base_q_idx,
15609 None,
15610 filter_intra,
15611 None,
15612 smooth_neighbor, fctx,
15613 )?;
15614 neighbours.record_mi_luma(lmi, 4, &tu_grid);
15615 }
15616 neighbours.fill_skip_grid(lmi, 1, skip);
15617 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
15618 if has_chroma {
15619 last_uv = chroma;
15620 }
15621 }
15622 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15623 let (cpx, cpy) = (gpx / 2, gpy / 2);
15624 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15625 let (uv_mode, angle_delta_uv, alpha) =
15626 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
15627 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15628 neighbours.above_uv_mode[c] = uv_predict_mode;
15629 neighbours.left_uv_mode[r] = uv_predict_mode;
15630 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15631 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
15632 // A skipped chroma block still gets its CfL contribution: libaom's
15633 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15634 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15635 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15636 // added -- `skip_txfm` only drops the residual, never the alpha.
15637 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15638 // merge keeps one fix and feeds both lanes' counters so neither of
15639 // their gates goes vacuous.
15640 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15641 if alpha.is_some() {
15642 hit!(CHROMA_SKIP_CFL_HITS);
15643 hit!(SKIP_CFL_HITS);
15644 }
15645 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);
15646 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);
15647 (Grid::Zero(16), Grid::Zero(16))
15648 } else {
15649 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15650 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15651 let ug = read_plane(
15652 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15653 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15654 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15655 )?;
15656 let vg = read_plane(
15657 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15658 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
15659 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
15660 )?;
15661 (ug, vg)
15662 };
15663 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
15664 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
15665 // rescaling is wrong for an already-mi-unit position, so this inlines
15666 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
15667 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
15668 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
15669 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
15670 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
15671 // bottom). libaom's `update_ext_partition_context` writes
15672 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
15673 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
15674 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
15675 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
15676 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
15677 // round's bug) makes the very next sibling 8x8's `partition_w8` read
15678 // with the wrong context and desync immediately.
15679 let side_mi = 2;
15680 for cell in 0..side_mi {
15681 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
15682 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
15683 }
15684 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15685 let bound_h = round_up_even(neighbours.mi_rows);
15686 let bound_w = round_up_even(neighbours.mi_cols);
15687 let u_state = neighbour_state(&u_grid);
15688 let v_state = neighbour_state(&v_grid);
15689 for cell in 0..side_mi {
15690 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15691 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15692 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15693 }
15694 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15695 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15696 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15697 }
15698 }
15699 Ok((leaf_modes[2], leaf_modes[1]))
15700}
15701
15702/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
15703/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
15704/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
15705/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
15706/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
15707/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
15708/// every sub-block one mi wide or high but the last) -- differing only where
15709/// the shape does:
15710///
15711/// * the transform is a true `TX_4X8`/`TX_8X4`
15712/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
15713/// `av1_inv_txfm_shift_ls` row already cover this size pair);
15714/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
15715/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
15716/// row -- see that variant's doc comment;
15717/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
15718/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
15719/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
15720/// ([`Reach::of_rect`]);
15721/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
15722/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
15723/// `BLOCK_4X4` split writes.
15724///
15725/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
15726/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
15727/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
15728/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
15729/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
15730/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
15731#[allow(clippy::too_many_arguments)]
15732fn decode_leaf_rect8(
15733 dec: &mut SymbolDecoder,
15734 cdfs: &mut Cdfs,
15735 neighbours: &mut Neighbours,
15736 outer_at: (usize, usize),
15737 leaf_mi: (usize, usize),
15738 vert: bool,
15739 scan4: &[u16],
15740 y: &mut PlaneBuf<'static>,
15741 u: &mut PlaneBuf<'static>,
15742 v: &mut PlaneBuf<'static>,
15743 base_q_idx: u8,
15744 enable_filter_intra: bool,
15745 allow_intrabc: bool,
15746 tx_select: bool,
15747 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15748) -> Result<(usize, usize)> {
15749 let (r, c) = outer_at;
15750 // lane-modectx r1: availability-correct fallback pair (see
15751 // `modes_above_left`), not the raw coarse bands.
15752 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
15753 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15754 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
15755 let (w_mi, h_mi) = (bw / MI, bh / MI);
15756 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
15757 let mut leaf_modes = [0usize; 2];
15758 let mut leaf_skips = [false; 2];
15759 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15760 for i in 0..2usize {
15761 let lmi = if vert {
15762 (leaf_mi.0, leaf_mi.1 + i)
15763 } else {
15764 (leaf_mi.0 + i, leaf_mi.1)
15765 };
15766 // Inside the pair the sibling is the neighbour on the split axis;
15767 // outside it the mi-granular map, else the coarse 16x16 slot.
15768 let leaf_above = if !vert && i == 1 {
15769 leaf_modes[0]
15770 } else {
15771 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15772 };
15773 let leaf_left = if vert && i == 1 {
15774 leaf_modes[0]
15775 } else {
15776 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15777 };
15778 let has_chroma = i == 1;
15779 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15780 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15781 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15782 filter_intra_size_class_rect(bw, bh)
15783 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
15784 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15785 )?;
15786 if filter_intra.is_some() {
15787 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
15788 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
15789 // same `reconstruct_rect`/`reconstruct` calls below -- and under
15790 // a split transform, per 4x4 unit with that unit's own edge,
15791 // which is exactly what the depth-1 loop already does.
15792 hit!(FILTER_INTRA_RECT_HITS);
15793 hit!(FILTER_INTRA_RECT_SUB8_HITS);
15794 }
15795 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
15796 // leaf too, and is read for every intra block, skipped or not. Its
15797 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
15798 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
15799 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
15800 // `tx_size_cat2` the 32x16 strips read -- with the rect context
15801 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
15802 // Missing this read consumed one symbol fewer than the encoder wrote
15803 // and desynced the tile at the very first rect leaf (class
15804 // `symbol-consumption-gap`).
15805 let depth = if tx_select {
15806 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
15807 // read every other rect reader now does -- a no-op on a key frame.
15808 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
15809 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
15810 } else {
15811 tx_size_context_rect(neighbours, lmi, bw, bh)
15812 };
15813 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
15814 } else {
15815 0
15816 };
15817 if depth != 0 {
15818 hit!(TX_DEPTH_HITS);
15819 hit!(RECT8_SPLIT_TX_HITS);
15820 }
15821 leaf_modes[i] = mode;
15822 leaf_skips[i] = skip;
15823 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
15824 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15825 if smooth_neighbor {
15826 hit!(SMOOTH_LUMA_HITS);
15827 }
15828 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15829 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15830 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
15831 // two 4x4 transform units along its long axis, each predicted from
15832 // the previous unit's reconstruction and reading its own `txb_skip`
15833 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
15834 // four. The per-TU path writes its own neighbour state, so the
15835 // block-level write below is skipped for it.
15836 let split = depth != 0;
15837 if split {
15838 let mut done = 0usize;
15839 for tu in 0..2usize {
15840 let tu_mi = if vert {
15841 (lmi.0 + tu, lmi.1)
15842 } else {
15843 (lmi.0, lmi.1 + tu)
15844 };
15845 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
15846 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15847 // Same per-TU rule as every other split-transform site
15848 // (lane-palette2 r12): a transform unit inside a block is not
15849 // a block at that position, so its reach comes from the
15850 // block's own row, offset by the unit's position.
15851 let tu_reach = tu_reach(
15852 bw,
15853 bh,
15854 tu_px - px,
15855 tu_py - py,
15856 4,
15857 reach,
15858 px,
15859 py,
15860 y.width,
15861 y.height, fctx,
15862 );
15863 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15864 if skip {
15865 // A skipped leaf still predicts per transform unit: the
15866 // second 4x4 takes its above/left edge from the first
15867 // one's reconstruction, which is NOT what a single 4x8
15868 // prediction of the same mode produces.
15869 let zeros = vec![0i32; 16];
15870 push_intra(0,
15871 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
15872 filter_intra, smooth_neighbor, fctx,
15873 );
15874 neighbours.record_mi_luma(tu_mi, 4, &zeros);
15875 continue;
15876 }
15877 let tu_grid = read_plane(
15878 dec,
15879 cdfs,
15880 if reduced_tx_set {
15881 TxbSet::Luma4
15882 } else {
15883 TxbSet::Luma4Set1
15884 },
15885 scan4,
15886 0,
15887 tu_around,
15888 mode,
15889 mode,
15890 angle_delta_y,
15891 tu_reach,
15892 y,
15893 tu_px,
15894 tu_py,
15895 4,
15896 TX4,
15897 base_q_idx,
15898 None,
15899 filter_intra,
15900 Some(tu_skip_ctx),
15901 smooth_neighbor, fctx,
15902 )?;
15903 if tu_grid.iter().any(|&l| l != 0) {
15904 done += 1;
15905 }
15906 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15907 }
15908 if done > 0 {
15909 if vert {
15910 hit!(TX4X8_CODED_HITS);
15911 } else {
15912 hit!(TX8X4_CODED_HITS);
15913 }
15914 }
15915 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15916 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
15917 if has_chroma {
15918 last_uv = chroma;
15919 }
15920 continue;
15921 }
15922 let grid = if skip {
15923 let zeros = Grid::Zero(bw * bh);
15924 push_intra_rect(0,
15925 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
15926 smooth_neighbor, fctx,
15927 );
15928 zeros
15929 } else {
15930 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
15931 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
15932 // at 0 -- see `decode_leaf_split4`'s own note.
15933 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
15934 let set = if reduced_tx_set {
15935 TxbSet::LumaRect4x8
15936 } else {
15937 TxbSet::LumaRect4x8Set1
15938 };
15939 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
15940 let (levels, tx_type) = read_coeffs_rect(
15941 dec,
15942 &mut coding,
15943 scan,
15944 bw,
15945 bh,
15946 0,
15947 dc_sign_ctx(around.2),
15948 TxType::DctDct,
15949 )?;
15950 if levels.iter().any(|&l| l != 0) {
15951 if vert {
15952 hit!(TX4X8_CODED_HITS);
15953 } else {
15954 hit!(TX8X4_CODED_HITS);
15955 }
15956 }
15957 let residual = dequant_and_inverse_typed_wh(
15958 &levels,
15959 bw,
15960 bh,
15961 crate::decode::bit_depth(fctx),
15962 fctx.current_q_idx.with(|q| q.get()),
15963 plane_q_delta(0, fctx).0,
15964 plane_q_delta(0, fctx).1,
15965 tx_type,
15966 );
15967 push_intra_rect(0,
15968 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
15969 smooth_neighbor, fctx,
15970 );
15971 levels
15972 };
15973 // Plane 0's per-TU coefficient context over this leaf's own mi span
15974 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
15975 // for the whole 8x8 group below).
15976 let state = neighbour_state(&grid);
15977 for cell in 0..h_mi {
15978 if lmi.0 + cell < neighbours.mi_rows {
15979 neighbours.left[lmi.0 + cell][0] = state;
15980 }
15981 }
15982 for cell in 0..w_mi {
15983 if lmi.1 + cell < neighbours.mi_cols {
15984 neighbours.above[lmi.1 + cell][0] = state;
15985 }
15986 }
15987 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15988 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
15989 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
15990 if has_chroma {
15991 last_uv = chroma;
15992 }
15993 }
15994 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15995 let (cpx, cpy) = (gpx / 2, gpy / 2);
15996 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15997 let (uv_mode, angle_delta_uv, alpha) =
15998 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
15999 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16000 neighbours.above_uv_mode[c] = uv_predict_mode;
16001 neighbours.left_uv_mode[r] = uv_predict_mode;
16002 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16003 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] {
16004 // A skipped chroma block still gets its CfL contribution: libaom's
16005 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16006 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16007 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16008 // added -- `skip_txfm` only drops the residual, never the alpha.
16009 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16010 // merge keeps one fix and feeds both lanes' counters so neither of
16011 // their gates goes vacuous.
16012 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16013 if alpha.is_some() {
16014 hit!(CHROMA_SKIP_CFL_HITS);
16015 hit!(SKIP_CFL_HITS);
16016 }
16017 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);
16018 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);
16019 (Grid::Zero(16), Grid::Zero(16))
16020 } else {
16021 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16022 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16023 let ug = read_plane(
16024 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16025 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16026 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16027 )?;
16028 let vg = read_plane(
16029 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16030 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16031 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16032 )?;
16033 (ug, vg)
16034 };
16035 // `update_partition_context` at the 8x8 level writes
16036 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
16037 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
16038 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
16039 // `partition_ctx_mi` reads back off these side values.
16040 for cell in 0..2 {
16041 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
16042 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
16043 }
16044 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16045 let bound_h = round_up_even(neighbours.mi_rows);
16046 let bound_w = round_up_even(neighbours.mi_cols);
16047 let u_state = neighbour_state(&u_grid);
16048 let v_state = neighbour_state(&v_grid);
16049 for cell in 0..2usize {
16050 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
16051 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16052 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16053 }
16054 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
16055 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16056 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16057 }
16058 }
16059 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
16060 // bottom one (the second under HORZ, the left one under VERT), the one a
16061 // neighbour to the right sees is the top-right (the second under VERT).
16062 Ok(if vert {
16063 (leaf_modes[0], leaf_modes[1])
16064 } else {
16065 (leaf_modes[1], leaf_modes[0])
16066 })
16067}
16068
16069/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
16070/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
16071/// (mod 8) reuse the same table.
16072const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
16073 [(-1, 1), (-2, 2)],
16074 [(0, 1), (-1, 2)],
16075 [(0, 1), (0, 2)],
16076 [(0, 1), (1, 2)],
16077 [(1, 1), (2, 2)],
16078 [(1, 0), (2, 1)],
16079 [(1, 0), (2, 0)],
16080 [(1, 0), (2, -1)],
16081];
16082/// A neighbour tap outside the frame's true extent -- `constrain` reads this
16083/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
16084const CDEF_VERY_LARGE: i32 = 0x4000;
16085const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
16086const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
16087
16088fn cdef_msb(x: i32) -> i32 {
16089 31 - x.leading_zeros() as i32
16090}
16091
16092/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
16093/// centre sample a filter tap is allowed to contribute.
16094#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16095fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
16096 if threshold == 0 {
16097 return 0;
16098 }
16099 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
16100}
16101
16102/// `constrain`'s damping shift: a function of the block's threshold and
16103/// damping alone, so the filter loop computes it once per block instead of
16104/// the `leading_zeros` + branch it used to do twice per tap read.
16105fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
16106 (damping - cdef_msb(threshold)).max(0)
16107}
16108
16109/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
16110/// non-zero on every call (the caller only filters when its strength is).
16111fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
16112 let a = diff.abs();
16113 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
16114}
16115
16116/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
16117/// lies inside its own samples grown by this much.
16118const CDEF_BORDER: usize = 2;
16119
16120/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
16121/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
16122/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
16123/// index a small contiguous window instead of re-deriving the frame-bounds
16124/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
16125/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
16126fn cdef_gather(
16127 src: &[u16],
16128 stride: usize,
16129 true_w: usize,
16130 true_h: usize,
16131 ox: usize,
16132 oy: usize,
16133 bw: usize,
16134 bh: usize,
16135 buf: &mut [i16],
16136) {
16137 let bstride = bw + 2 * CDEF_BORDER;
16138 let rows = bh + 2 * CDEF_BORDER;
16139 if oy >= CDEF_BORDER
16140 && ox >= CDEF_BORDER
16141 && oy + bh + CDEF_BORDER <= true_h
16142 && ox + bw + CDEF_BORDER <= true_w
16143 {
16144 // Interior block: every tap is inside the frame, so the whole window
16145 // is `rows` contiguous runs.
16146 for r in 0..rows {
16147 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
16148 let src_row = &src[s0..s0 + bstride];
16149 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
16150 for (d, &v) in dst_row.iter_mut().zip(src_row) {
16151 *d = v as i16;
16152 }
16153 }
16154 return;
16155 }
16156 for r in 0..rows {
16157 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
16158 for c in 0..bstride {
16159 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
16160 buf[r * bstride + c] =
16161 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
16162 CDEF_VERY_LARGE as i16
16163 } else {
16164 src[ny as usize * stride + nx as usize] as i16
16165 };
16166 }
16167 }
16168}
16169
16170/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
16171/// array takes the row, its reverse, its pairwise sums or its total added
16172/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
16173/// per-sample form did become a handful of lane-wide adds per row. i32 is
16174/// exact here: every partial is a sum of at most eight values in -128..127,
16175/// and slot 15 exists only so an eight-lane store at offset 7 fits.
16176fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
16177 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
16178 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
16179 *d += x;
16180 }
16181 }
16182 let mut partial = [[0i32; 16]; 8];
16183 for i in 0..8usize {
16184 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16185 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
16186 // accumulating, same as `constrain`'s threshold shift.
16187 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
16188 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
16189 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
16190 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
16191 let (p, rest) = partial.split_at_mut(1);
16192 add_at(&mut p[0], i, &row); // partial[0][i + j]
16193 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
16194 rest[1][i] = row.iter().sum(); // partial[2][i]
16195 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
16196 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
16197 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
16198 add_at(&mut rest[5], 0, &row); // partial[6][j]
16199 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
16200 }
16201 partial
16202}
16203
16204/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
16205/// direction of an 8x8 luma window and the variance gap between it and its
16206/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
16207/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
16208fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
16209 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
16210 #[cfg(target_arch = "x86_64")]
16211 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16212 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16213 // the same eight rows of eight samples the scalar form does.
16214 #[allow(unsafe_code)]
16215 unsafe {
16216 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
16217 }
16218 } else {
16219 cdef_find_dir_partials(win, bstride, coeff_shift)
16220 };
16221 #[cfg(not(target_arch = "x86_64"))]
16222 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
16223 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
16224 let mut cost = [0i64; 8];
16225 for i in 0..8usize {
16226 cost[2] += sq(partial[2][i]);
16227 cost[6] += sq(partial[6][i]);
16228 }
16229 cost[2] *= DIV_TABLE[8];
16230 cost[6] *= DIV_TABLE[8];
16231 for i in 0..7usize {
16232 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
16233 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
16234 }
16235 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
16236 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
16237 for i in (1..8).step_by(2) {
16238 for j in 0..5usize {
16239 cost[i] += sq(partial[i][3 + j]);
16240 }
16241 cost[i] *= DIV_TABLE[8];
16242 for j in 0..3usize {
16243 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
16244 }
16245 }
16246 let mut best_cost = 0i64;
16247 let mut best_dir = 0usize;
16248 for (i, &c) in cost.iter().enumerate() {
16249 if c > best_cost {
16250 best_cost = c;
16251 best_dir = i;
16252 }
16253 }
16254 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
16255 (best_dir, var as i32)
16256}
16257
16258/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
16259/// (high variance gap) gets more deringing than a flat or non-directional
16260/// one, only ever applied to the luma primary strength.
16261fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
16262 if var == 0 {
16263 return 0;
16264 }
16265 let i = if var >> 6 != 0 {
16266 cdef_msb(var >> 6).min(12)
16267 } else {
16268 0
16269 };
16270 (strength * (4 + i) + 8) >> 4
16271}
16272
16273/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
16274/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
16275/// previously-filtered neighbour must never feed this block's own sum).
16276#[allow(clippy::too_many_arguments)]
16277#[allow(unsafe_code)]
16278fn cdef_filter_block(
16279 src: &[i16],
16280 dst: &mut PlaneBuf<'static>,
16281 ox: usize,
16282 oy: usize,
16283 bw: usize,
16284 bh: usize,
16285 pri_strength: i32,
16286 sec_strength: i32,
16287 dir: usize,
16288 pri_damping: i32,
16289 sec_damping: i32,
16290 enable_primary: bool,
16291 enable_secondary: bool,
16292 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
16293) {
16294 let (stride, smax) = (dst.width, sample_max(fctx));
16295 #[cfg(target_arch = "x86_64")]
16296 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
16297 {
16298 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16299 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
16300 // `bh` runs of `bw` samples the scalar form writes.
16301 unsafe {
16302 cdef_simd::filter_block_avx2(
16303 src,
16304 dst.data.to_mut(),
16305 stride,
16306 ox,
16307 oy,
16308 bw,
16309 bh,
16310 pri_strength,
16311 sec_strength,
16312 dir,
16313 pri_damping,
16314 sec_damping,
16315 enable_primary,
16316 enable_secondary,
16317 coeff_shift,
16318 smax,
16319 )
16320 };
16321 return;
16322 }
16323 cdef_filter_block_scalar(
16324 src,
16325 dst.data.to_mut(),
16326 stride,
16327 ox,
16328 oy,
16329 bw,
16330 bh,
16331 pri_strength,
16332 sec_strength,
16333 dir,
16334 pri_damping,
16335 sec_damping,
16336 enable_primary,
16337 enable_secondary,
16338 coeff_shift,
16339 smax,
16340 );
16341}
16342
16343/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
16344/// the form every non-AVX2 build decodes through and the one
16345/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
16346#[allow(clippy::too_many_arguments)]
16347fn cdef_filter_block_scalar(
16348 src: &[i16],
16349 dst: &mut [u16],
16350 stride: usize,
16351 ox: usize,
16352 oy: usize,
16353 bw: usize,
16354 bh: usize,
16355 pri_strength: i32,
16356 sec_strength: i32,
16357 dir: usize,
16358 pri_damping: i32,
16359 sec_damping: i32,
16360 enable_primary: bool,
16361 enable_secondary: bool,
16362 coeff_shift: i32,
16363 smax: i32,
16364) {
16365 let clipping_required = enable_primary && enable_secondary;
16366 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
16367 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
16368 // derivative) carries the bit-depth shift, so the tap-set parity bit
16369 // must be read back above that shift, not off the raw low bit.
16370 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16371 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
16372 // `constrain`), so they are resolved here rather than per tap read.
16373 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
16374 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
16375 let bstride = bw + 2 * CDEF_BORDER;
16376 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
16377 // reaching +-CDEF_BORDER, so every index below is in range by construction.
16378 let at = |i: i32, j: i32| -> i32 {
16379 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
16380 };
16381 let (pri_dir, sec_dir0, sec_dir1) =
16382 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16383 for i in 0..bh {
16384 for j in 0..bw {
16385 let (i32i, i32j) = (i as i32, j as i32);
16386 let x = at(i32i, i32j);
16387 let mut sum = 0i32;
16388 let mut max = x;
16389 let mut min = x;
16390 for k in 0..2usize {
16391 if enable_primary {
16392 let (tr, tc) = pri_dir[k];
16393 let p0 = at(i32i + tr, i32j + tc);
16394 let p1 = at(i32i - tr, i32j - tc);
16395 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
16396 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
16397 if clipping_required {
16398 if p0 != CDEF_VERY_LARGE {
16399 max = max.max(p0);
16400 }
16401 if p1 != CDEF_VERY_LARGE {
16402 max = max.max(p1);
16403 }
16404 min = min.min(p0).min(p1);
16405 }
16406 }
16407 if enable_secondary {
16408 let (tr0, tc0) = sec_dir0[k];
16409 let (tr1, tc1) = sec_dir1[k];
16410 let s0 = at(i32i + tr0, i32j + tc0);
16411 let s1 = at(i32i - tr0, i32j - tc0);
16412 let s2 = at(i32i + tr1, i32j + tc1);
16413 let s3 = at(i32i - tr1, i32j - tc1);
16414 if clipping_required {
16415 for s in [s0, s1, s2, s3] {
16416 if s != CDEF_VERY_LARGE {
16417 max = max.max(s);
16418 }
16419 }
16420 min = min.min(s0).min(s1).min(s2).min(s3);
16421 }
16422 sum += CDEF_SEC_TAPS[k]
16423 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
16424 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
16425 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
16426 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
16427 }
16428 }
16429 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
16430 if clipping_required {
16431 y = y.clamp(min, max);
16432 }
16433 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
16434 }
16435 }
16436}
16437
16438/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
16439/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
16440/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
16441/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
16442/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
16443/// a time in 16-bit lanes.
16444///
16445/// 16-bit lanes are exact for every value this filter sees: window samples
16446/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
16447/// `i16`, a `constrain` result is bounded by the threshold (at most
16448/// `15 << 4`), and the tap-weighted sum by `24 *` that.
16449#[cfg(target_arch = "x86_64")]
16450#[allow(unsafe_code)]
16451#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16452mod cdef_simd {
16453 use super::{
16454 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
16455 CDEF_VERY_LARGE,
16456 };
16457 use std::arch::x86_64::*;
16458
16459 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
16460 /// register (low half = row `i`).
16461 ///
16462 /// # Safety
16463 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
16464 #[target_feature(enable = "avx2")]
16465 #[inline]
16466 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
16467 let lo = _mm_loadu_si128(w.offset(off).cast());
16468 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
16469 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
16470 }
16471
16472 /// Spec 7.15.3's `constrain`, lane-parallel:
16473 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
16474 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
16475 /// clamped magnitude is already 0 where `diff` is).
16476 ///
16477 /// # Safety
16478 /// Requires AVX2.
16479 #[target_feature(enable = "avx2")]
16480 #[inline]
16481 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
16482 let diff = _mm256_sub_epi16(p, x);
16483 let a = _mm256_abs_epi16(diff);
16484 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
16485 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
16486 _mm256_sign_epi16(t, diff)
16487 }
16488
16489 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
16490 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
16491 /// four the auto-vectorised scalar form gets without the feature.
16492 ///
16493 /// # Safety
16494 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
16495 /// grown by `CDEF_BORDER` at row stride `bstride`.
16496 #[target_feature(enable = "avx2")]
16497 pub unsafe fn find_dir_partials_avx2(
16498 win: &[i16],
16499 bstride: usize,
16500 coeff_shift: i32,
16501 ) -> [[i32; 16]; 8] {
16502 #[target_feature(enable = "avx2")]
16503 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
16504 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
16505 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
16506 }
16507 #[target_feature(enable = "avx2")]
16508 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
16509 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
16510 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
16511 }
16512 let mut partial = [[0i32; 16]; 8];
16513 let shift = _mm_cvtsi32_si128(coeff_shift);
16514 let c128 = _mm256_set1_epi32(128);
16515 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
16516 let mut p6 = _mm256_setzero_si256();
16517 for i in 0..8usize {
16518 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16519 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
16520 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
16521 let rev = _mm256_permutevar8x32_epi32(row, revidx);
16522 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
16523 // four pairwise sums are the two lanes' low halves joined.
16524 let h = _mm256_hadd_epi32(row, row);
16525 let pair =
16526 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
16527 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
16528 let hs = _mm_hadd_epi32(pair, pair);
16529 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
16530 add8(&mut partial[0], i, row);
16531 add4(&mut partial[1], i, pair);
16532 partial[2][i] = total;
16533 add4(&mut partial[3], i, rpair);
16534 add8(&mut partial[4], i, rev);
16535 add8(&mut partial[5], 3 - i / 2, row);
16536 p6 = _mm256_add_epi32(p6, row);
16537 add8(&mut partial[7], i / 2, row);
16538 }
16539 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
16540 partial
16541 }
16542
16543 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
16544 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
16545 /// `bw == 4` the upper four lanes of each half are window samples read
16546 /// past the row (never past the buffer -- `w` is padded to 256 entries),
16547 /// computed and then dropped by the 64-bit store.
16548 ///
16549 /// # Safety
16550 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
16551 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
16552 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
16553 /// of `bw` samples at `(ox, oy)`.
16554 #[target_feature(enable = "avx2")]
16555 #[allow(clippy::too_many_arguments)]
16556 pub unsafe fn filter_block_avx2(
16557 src: &[i16],
16558 dst: &mut [u16],
16559 stride: usize,
16560 ox: usize,
16561 oy: usize,
16562 bw: usize,
16563 bh: usize,
16564 pri_strength: i32,
16565 sec_strength: i32,
16566 dir: usize,
16567 pri_damping: i32,
16568 sec_damping: i32,
16569 enable_primary: bool,
16570 enable_secondary: bool,
16571 coeff_shift: i32,
16572 smax: i32,
16573 ) {
16574 let bstride = bw + 2 * CDEF_BORDER;
16575 // The caller's window is already `i16` and 256 entries long, so the
16576 // kernel taps it in place: the largest two-row load is
16577 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
16578 // 4x4 chroma one, both inside the buffer's zeroed tail.
16579 let w = src;
16580 let clipping_required = enable_primary && enable_secondary;
16581 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16582 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
16583 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
16584 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
16585 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
16586 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
16587 let zero = _mm256_setzero_si256();
16588 let eight = _mm256_set1_epi16(8);
16589 let smaxv = _mm256_set1_epi16(smax as i16);
16590 let (pri_dir, sec_dir0, sec_dir1) =
16591 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16592 let wp = w.as_ptr();
16593 let bs = bstride as isize;
16594 let dp = dst.as_mut_ptr();
16595 let mut i = 0usize;
16596 while i < bh {
16597 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
16598 let x = ld2(wp, base, bs);
16599 let mut sum = zero;
16600 let mut max = x;
16601 let mut min = x;
16602 for k in 0..2usize {
16603 if enable_primary {
16604 let (tr, tc) = pri_dir[k];
16605 let off = tr as isize * bs + tc as isize;
16606 let p0 = ld2(wp, base + off, bs);
16607 let p1 = ld2(wp, base - off, bs);
16608 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
16609 sum = _mm256_add_epi16(
16610 sum,
16611 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
16612 );
16613 sum = _mm256_add_epi16(
16614 sum,
16615 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
16616 );
16617 if clipping_required {
16618 // The sentinel is excluded from the max exactly as the
16619 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
16620 // 0 cannot win a max whose seed `x` is non-negative.
16621 max = _mm256_max_epi16(
16622 max,
16623 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
16624 );
16625 max = _mm256_max_epi16(
16626 max,
16627 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
16628 );
16629 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
16630 }
16631 }
16632 if enable_secondary {
16633 let (tr0, tc0) = sec_dir0[k];
16634 let (tr1, tc1) = sec_dir1[k];
16635 let off0 = tr0 as isize * bs + tc0 as isize;
16636 let off1 = tr1 as isize * bs + tc1 as isize;
16637 let s0 = ld2(wp, base + off0, bs);
16638 let s1 = ld2(wp, base - off0, bs);
16639 let s2 = ld2(wp, base + off1, bs);
16640 let s3 = ld2(wp, base - off1, bs);
16641 if clipping_required {
16642 for s in [s0, s1, s2, s3] {
16643 max = _mm256_max_epi16(
16644 max,
16645 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
16646 );
16647 }
16648 min = _mm256_min_epi16(
16649 min,
16650 _mm256_min_epi16(
16651 _mm256_min_epi16(s0, s1),
16652 _mm256_min_epi16(s2, s3),
16653 ),
16654 );
16655 }
16656 let c = _mm256_add_epi16(
16657 _mm256_add_epi16(
16658 constrain(s0, x, sec_thr, sec_shift),
16659 constrain(s1, x, sec_thr, sec_shift),
16660 ),
16661 _mm256_add_epi16(
16662 constrain(s2, x, sec_thr, sec_shift),
16663 constrain(s3, x, sec_thr, sec_shift),
16664 ),
16665 );
16666 sum = _mm256_add_epi16(
16667 sum,
16668 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
16669 );
16670 }
16671 }
16672 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
16673 let neg = _mm256_cmpgt_epi16(zero, sum);
16674 let mut y = _mm256_add_epi16(
16675 x,
16676 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
16677 );
16678 if clipping_required {
16679 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
16680 }
16681 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
16682 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
16683 let o0 = ((oy + i) * stride + ox) as isize;
16684 let o1 = o0 + stride as isize;
16685 if bw == 8 {
16686 _mm_storeu_si128(dp.offset(o0).cast(), lo);
16687 _mm_storeu_si128(dp.offset(o1).cast(), hi);
16688 } else {
16689 _mm_storel_epi64(dp.offset(o0).cast(), lo);
16690 _mm_storel_epi64(dp.offset(o1).cast(), hi);
16691 }
16692 i += 2;
16693 }
16694 }
16695}
16696
16697/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
16698/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
16699/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
16700/// every block's level comes from [`LoopFilterParams::level`] plus the
16701/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
16702/// `get_filter_level`, precomputed per-block here rather than cached in a
16703/// table the way libaom's `av1_loop_filter_frame_init` does).
16704///
16705/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
16706/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
16707fn apply_deblock(
16708 y: &mut PlaneBuf<'static>,
16709 u: &mut PlaneBuf<'static>,
16710 v: &mut PlaneBuf<'static>,
16711 lf: &LoopFilterParams,
16712 n: &Neighbours,
16713 frame_width: usize,
16714 frame_height: usize, fctx: &crate::decode::FrameCtx,
16715) {
16716 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
16717 // mismatch between the raw reconstruction and post-filter output.
16718 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
16719 return;
16720 }
16721 if lf.level[0] != 0 || lf.level[1] != 0 {
16722 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
16723 }
16724 if lf.level[2] != 0 {
16725 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
16726 }
16727 if lf.level[3] != 0 {
16728 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
16729 }
16730}
16731
16732/// [`apply_deblock`] for ONE pass over ONE band of luma rows
16733/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
16734/// planes' vertical passes and then their three horizontal ones is the same
16735/// output as `apply_deblock`'s plane-at-a-time order: the planes are
16736/// separate buffers and neither pass reads another plane.
16737#[allow(clippy::too_many_arguments)]
16738fn deblock_span(
16739 y: &mut PlaneBuf<'static>,
16740 u: &mut PlaneBuf<'static>,
16741 v: &mut PlaneBuf<'static>,
16742 lf: &LoopFilterParams,
16743 n: &Neighbours,
16744 frame_width: usize,
16745 frame_height: usize,
16746 y_lo: usize,
16747 y_hi: usize,
16748 horz: bool,
16749 fctx: &crate::decode::FrameCtx,
16750) {
16751 if lf.level[0] != 0 || lf.level[1] != 0 {
16752 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
16753 }
16754 if lf.level[2] != 0 {
16755 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16756 }
16757 if lf.level[3] != 0 {
16758 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16759 }
16760}
16761
16762/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
16763/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
16764/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
16765/// mi unit under this decoder's assumed 4:2:0 subsampling).
16766///
16767/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
16768/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
16769/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
16770/// prediction mode is obtained from the bottom/right mi structure of the
16771/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
16772/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
16773/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
16774/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
16775/// the group is split into 4x4 luma blocks (class
16776/// `context-read-from-one-cell`).
16777fn plane_to_mi(chroma: bool, coord: usize) -> usize {
16778 if chroma { (coord / 2) | 1 } else { coord / 4 }
16779}
16780
16781/// This plane's own transform width in pixels at the covering block, spec
16782/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
16783/// width directly; chroma halves it (this decoder's UV transform is always
16784/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
16785/// under 4:2:0 and a block that never splits its own transform).
16786fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16787 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
16788 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16789}
16790
16791/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
16792/// edges step and gate by transform height, which differs from width only
16793/// on rect partition strips.
16794fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16795 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
16796 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16797}
16798
16799/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
16800/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
16801/// present only when its neighbour exists inside the true frame -- whether
16802/// the block immediately above (at this block's own leftmost mi column) or
16803/// to the left (at its own topmost mi row) coded a transform at least as wide
16804/// as `own_side`.
16805fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
16806 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
16807 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
16808 usize::from(above) + usize::from(left)
16809}
16810
16811/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
16812/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
16813/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
16814/// inter path maintains), except that an *inter* neighbour contributes its
16815/// own BLOCK size rather than its transform size -- the two differ the moment
16816/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
16817/// approximation coincides with this only while every neighbour codes one
16818/// whole-block transform, which is exactly what `TxMode::Select` ends.
16819/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
16820/// r1): `get_tx_size_context` compares the neighbour ABOVE against
16821/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
16822/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
16823/// strip are two different numbers. The intra strip inside an inter frame read
16824/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
16825/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
16826/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
16827fn tx_size_context_txfm_rect(
16828 n: &Neighbours,
16829 (mi_r, mi_c): (usize, usize),
16830 own_w: usize,
16831 own_h: usize, fctx: &crate::decode::FrameCtx,
16832) -> usize {
16833 hit!(INTRA_IN_INTER_TXCTX_HITS);
16834 let has_above = mi_r > n.tile_row0_mi;
16835 let has_left = mi_c > n.tile_col0_mi;
16836 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
16837 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
16838 if has_above && n.above_inter[mi_c] {
16839 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
16840 }
16841 if has_left && n.left_inter[mi_r] {
16842 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
16843 }
16844 if crate::envflags::env_flag!("EC_TXCTX") {
16845 eprintln!(
16846 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
16847 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16848 above={above} left={left}",
16849 n.above_txfm[mi_c],
16850 n.left_txfm[mi_r],
16851 n.above_inter[mi_c],
16852 n.left_inter[mi_r],
16853 n.above_side_mi[mi_c],
16854 n.left_side_mi[mi_r],
16855 );
16856 }
16857 let ctx = match (has_above, has_left) {
16858 (true, true) => usize::from(above) + usize::from(left),
16859 (true, false) => usize::from(above),
16860 (false, true) => usize::from(left),
16861 (false, false) => 0,
16862 };
16863 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
16864 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
16865 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
16866 // intra in an inter frame" tally is green on the buggy code too (class
16867 // gate-blind-to-feature).
16868 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16869 let (cw, ch) = (own_w.min(64), own_h.min(64));
16870 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
16871 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
16872 if ctx != stale {
16873 hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS);
16874 }
16875 }
16876 ctx
16877}
16878
16879/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
16880/// are written and read everywhere else with a raw mi index); the SUB-cell
16881/// division this pair used read a cell four blocks away, so the inter-neighbour
16882/// override above fired on the wrong neighbour -- the first divergence of the
16883/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
16884/// at the intra block right of an inter one).
16885fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
16886 let has_above = mi_r > n.tile_row0_mi;
16887 let has_left = mi_c > n.tile_col0_mi;
16888 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
16889 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
16890 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
16891 // `above_inter`/`left_inter` bands are written per MI unit
16892 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
16893 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
16894 // block whenever the neighbour column/row is not the cell's first. A
16895 // 16x16 intra block whose left neighbour is an inter block at mi row 4
16896 // then missed libaom's "an inter neighbour contributes its BLOCK size"
16897 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
16898 if has_above && n.above_inter[mi_c] {
16899 above = usize::from(n.above_side_mi[mi_c]) >= side;
16900 }
16901 if has_left && n.left_inter[mi_r] {
16902 left = usize::from(n.left_side_mi[mi_r]) >= side;
16903 }
16904 if crate::envflags::env_flag!("EC_TXCTX") {
16905 eprintln!(
16906 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
16907 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16908 above={above} left={left}",
16909 n.above_txfm[mi_c],
16910 n.left_txfm[mi_r],
16911 n.above_inter[mi_c],
16912 n.left_inter[mi_r],
16913 n.above_side_mi[mi_c],
16914 n.left_side_mi[mi_r],
16915 );
16916 }
16917 match (has_above, has_left) {
16918 (true, true) => usize::from(above) + usize::from(left),
16919 (true, false) => usize::from(above),
16920 (false, true) => usize::from(left),
16921 (false, false) => 0,
16922 }
16923}
16924
16925/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
16926/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
16927/// the transform's own side in pixels (`side >> depth`) -- this decoder's
16928/// four square categories (8/16/32/64) each halve at most twice, matching
16929/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
16930fn read_tx_size(
16931 dec: &mut SymbolDecoder,
16932 cdfs: &mut Cdfs,
16933 n: &Neighbours,
16934 at_mi: (usize, usize),
16935 side: usize,
16936 // lane-txselect: `get_tx_size_context`'s real context, for the callers
16937 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
16938 // key-frame path's own deblock-grid approximation.
16939 ctx_override: Option<usize>,
16940) -> usize {
16941 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
16942 // `get_tx_size_context`): a block wider than 64 still tops out at
16943 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
16944 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
16945 // never against its own 128 side (lane-sb128b r1).
16946 let max_tx = side.min(64);
16947 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
16948 let depth = match max_tx {
16949 8 => {
16950 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16951 }
16952 16 => {
16953 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
16954 }
16955 32 => {
16956 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
16957 }
16958 64 => {
16959 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
16960 }
16961 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
16962 };
16963 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16964 let (rng, _) = dec.debug_state();
16965 let (mi_r, mi_c) = at_mi;
16966 eprintln!(
16967 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
16968 );
16969 }
16970 if depth != 0 {
16971 hit!(TX_DEPTH_HITS);
16972 }
16973 max_tx >> depth
16974}
16975
16976/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
16977/// `txfm_split` context -- a category from the block's own largest square
16978/// transform and whether this unit already sits below it, times three, plus
16979/// the two neighbour terms (whether the transform last written above/left of
16980/// this unit is narrower/shorter than the unit itself).
16981#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16982fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
16983 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
16984}
16985
16986/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
16987/// libaom's `txfm_partition_context` compares the above context against
16988/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
16989/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
16990/// side for a square transform, which is why the square form above is a
16991/// special case of this one.
16992pub(crate) fn txfm_partition_ctx_rect(
16993 above_px: u8,
16994 left_px: u8,
16995 blk_max_px: usize,
16996 tx_w: usize,
16997 tx_h: usize,
16998) -> usize {
16999 let above = usize::from(usize::from(above_px) < tx_w);
17000 let left = usize::from(usize::from(left_px) < tx_h);
17001 let tx_px = tx_w.max(tx_h);
17002 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
17003 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
17004 // `log2(px) - 2`.
17005 let max_tx = blk_max_px.min(64);
17006 let max_idx = max_tx.trailing_zeros() as usize - 2;
17007 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
17008 category * 3 + above + left
17009}
17010
17011/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
17012/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
17013/// resolved transform's own size.
17014#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17015fn txfm_partition_update(
17016 n: &mut Neighbours,
17017 at_mi: (usize, usize),
17018 tx_px: usize,
17019 txb_px: usize,
17020) {
17021 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
17022}
17023
17024/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
17025/// the left column records `tx_size_high` over the parent's own height and
17026/// the above row records `tx_size_wide` over its width.
17027/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
17028/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
17029/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
17030/// key frame writes neither (its readers use the deblock grid), so the
17031/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
17032/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
17033/// at the call site (the transform size comes back to them); the 1:4 arms
17034/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
17035/// so they call this where their own depth resolves. A no-op on a key frame
17036/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
17037///
17038/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
17039/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
17040/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
17041/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
17042/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
17043/// / early-return-skips-tail).
17044fn publish_txfm_bands_if_in_inter(
17045 n: &mut Neighbours,
17046 at_mi: (usize, usize),
17047 (tx_w, tx_h): (usize, usize),
17048 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
17049) {
17050 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
17051 return;
17052 }
17053 let (mi_r, mi_c) = at_mi;
17054 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17055 for i in 0..bw / MI {
17056 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17057 *cell = tx_w as u8;
17058 }
17059 }
17060 for i in 0..bh / MI {
17061 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17062 *cell = tx_h as u8;
17063 }
17064 }
17065}
17066
17067fn txfm_partition_update_rect(
17068 n: &mut Neighbours,
17069 (mi_r, mi_c): (usize, usize),
17070 (tx_w, tx_h): (usize, usize),
17071 (txb_w, txb_h): (usize, usize),
17072) {
17073 if crate::envflags::env_flag!("EC_TXUPD") {
17074 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
17075 }
17076 for i in 0..txb_h / MI {
17077 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17078 *cell = tx_h as u8;
17079 }
17080 }
17081 for i in 0..txb_w / MI {
17082 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17083 *cell = tx_w as u8;
17084 }
17085 }
17086}
17087
17088/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
17089/// same contexts -- a skipped *inter* block records its own block size rather
17090/// than its transform size.
17091fn set_txfm_ctxs(
17092 n: &mut Neighbours,
17093 (mi_r, mi_c): (usize, usize),
17094 tx_px: usize,
17095 w_mi: usize,
17096 h_mi: usize,
17097 skip_inter: bool,
17098) {
17099 if crate::envflags::env_flag!("EC_TXUPD") {
17100 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
17101 }
17102 let bw = if skip_inter { w_mi * MI } else { tx_px };
17103 let bh = if skip_inter { h_mi * MI } else { tx_px };
17104 for i in 0..w_mi {
17105 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17106 *cell = bw as u8;
17107 }
17108 }
17109 for i in 0..h_mi {
17110 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17111 *cell = bh as u8;
17112 }
17113 }
17114}
17115
17116/// The value libaom initialises both transform contexts to -- NOT zero:
17117/// `av1_zero_above_context` memsets the txfm row to
17118/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
17119/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17120/// pixels, so an unwritten neighbour reads as the *widest* possible
17121/// transform, not the narrowest.
17122pub(crate) const TXFM_CTX_INIT: u8 = 64;
17123
17124/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17125/// twice below its own largest transform.
17126const MAX_VARTX_DEPTH: usize = 2;
17127
17128/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
17129/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
17130/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
17131/// small ones, square everywhere else.
17132fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
17133 match (tx_w, tx_h) {
17134 (4, 4) => (4, 4),
17135 (8, 8) => (4, 4),
17136 (16, 16) => (8, 8),
17137 (32, 32) => (16, 16),
17138 (64, 64) => (32, 32),
17139 (4, 8) | (8, 4) => (4, 4),
17140 (8, 16) | (16, 8) => (8, 8),
17141 (16, 32) | (32, 16) => (16, 16),
17142 (32, 64) | (64, 32) => (32, 32),
17143 (4, 16) => (4, 8),
17144 (16, 4) => (8, 4),
17145 (8, 32) => (8, 16),
17146 (32, 8) => (16, 8),
17147 (16, 64) => (16, 32),
17148 (64, 16) => (32, 16),
17149 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
17150 }
17151}
17152
17153#[test]
17154fn sub_tx_size_map_matches_libaom() {
17155 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
17156 const TABLE: [((usize, usize), (usize, usize)); 19] = [
17157 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
17158 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
17159 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
17160 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
17161 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
17162 ];
17163 for (tx, want) in TABLE {
17164 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
17165 }
17166}
17167
17168/// The domain of var-tx leaf sizes, enumerated against the two refusals that
17169/// name a leaf "larger than 32x32" / "larger than 64x64".
17170///
17171/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
17172/// either the unit it was entered with or a `sub_tx_size_map` step below it:
17173/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
17174/// return. So the leaf set reachable from an entry unit is that unit plus the
17175/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
17176/// which this test enumerates, and over which no leaf is ever larger than the
17177/// entry.
17178///
17179/// That closes both refusals:
17180///
17181/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
17182/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
17183/// 64x64" names a leaf the tree cannot produce;
17184/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
17185/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
17186/// reached only when `side == 64`, and then the block is ONE unit whose only
17187/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
17188/// case the refusal is guarded by.
17189#[test]
17190fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
17191 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
17192 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
17193 out.push((depth, entry.0, entry.1));
17194 if depth == MAX_VARTX_DEPTH {
17195 return;
17196 }
17197 let sub = sub_tx_size_map(entry.0, entry.1);
17198 if sub == (4, 4) {
17199 out.push((depth + 1, 4, 4));
17200 return;
17201 }
17202 reachable(sub, depth + 1, out);
17203 }
17204
17205 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
17206 let mut leaves = Vec::new();
17207 reachable(entry, 0, &mut leaves);
17208 for (depth, w, h) in &leaves {
17209 assert!(
17210 w.max(h) <= &entry.0.max(entry.1),
17211 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
17212 entry.0,
17213 entry.1
17214 );
17215 }
17216 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
17217 if entry == (64, 64) {
17218 let above: Vec<&(usize, usize, usize)> =
17219 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
17220 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
17221 }
17222 }
17223
17224 // The entry size and ceiling each caller uses, over the block sides that
17225 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
17226 // enters at a fixed 64).
17227 for side in [8usize, 16, 32, 64, 128] {
17228 let max_tx = side.min(64);
17229 let ceiling = if side > 64 { 64 } else { 32 };
17230 let units = (side / max_tx) * (side / max_tx);
17231 if max_tx <= ceiling {
17232 continue;
17233 }
17234 assert_eq!(
17235 (side, units),
17236 (64, 1),
17237 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
17238 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
17239 );
17240 }
17241}
17242
17243/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
17244/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
17245/// max-transform-sized unit of an inter block, collecting the resolved leaf
17246/// transform units into `out` as `(row offset, col offset, side)` in mi units
17247/// -- exactly the order `decode_reconstruct_tx` later reads their
17248/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
17249/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
17250/// `max_block_high`).
17251#[allow(clippy::too_many_arguments)]
17252fn read_var_tx_size(
17253 dec: &mut SymbolDecoder,
17254 cdfs: &mut Cdfs,
17255 n: &mut Neighbours,
17256 at_mi: (usize, usize),
17257 blk_max_px: usize,
17258 (max_w_mi, max_h_mi): (usize, usize),
17259 (tx_w, tx_h): (usize, usize),
17260 depth: usize,
17261 blk_row: usize,
17262 blk_col: usize,
17263 out: &mut Vec<(usize, usize, usize, usize)>,
17264) {
17265 if blk_row >= max_h_mi || blk_col >= max_w_mi {
17266 return;
17267 }
17268 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
17269 if depth == MAX_VARTX_DEPTH {
17270 out.push((blk_row, blk_col, tx_w, tx_h));
17271 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17272 return;
17273 }
17274 let ctx = txfm_partition_ctx_rect(
17275 n.above_txfm[unit.1],
17276 n.left_txfm[unit.0],
17277 blk_max_px,
17278 tx_w,
17279 tx_h,
17280 );
17281 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17282 hit!(TXFM_SPLIT_READS);
17283 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17284 let (rng, _) = dec.debug_state();
17285 eprintln!(
17286 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
17287 unit.0,
17288 unit.1,
17289 u8::from(split)
17290 );
17291 }
17292 if !split {
17293 out.push((blk_row, blk_col, tx_w, tx_h));
17294 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17295 return;
17296 }
17297 hit!(TXFM_SPLIT_HITS);
17298 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17299 if (sub_w, sub_h) == (4, 4) {
17300 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
17301 // unit is marked 4x4 (raster order) without recursing.
17302 for row in 0..tx_h / MI {
17303 for col in 0..tx_w / MI {
17304 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
17305 out.push((blk_row + row, blk_col + col, 4, 4));
17306 }
17307 }
17308 }
17309 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
17310 return;
17311 }
17312 for row in (0..tx_h / MI).step_by(sub_h / MI) {
17313 for col in (0..tx_w / MI).step_by(sub_w / MI) {
17314 read_var_tx_size(
17315 dec,
17316 cdfs,
17317 n,
17318 at_mi,
17319 blk_max_px,
17320 (max_w_mi, max_h_mi),
17321 (sub_w, sub_h),
17322 depth + 1,
17323 blk_row + row,
17324 blk_col + col,
17325 out,
17326 );
17327 }
17328 }
17329}
17330
17331/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
17332/// branch): every block of a `TxMode::Select` inter frame codes its transform
17333/// size right after its own mode info -- an inter non-skip block through the
17334/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
17335/// every other block through the intra `tx_depth` symbol (a skipped inter
17336/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
17337/// block's own resolved transform side and the leaf list, the latter only
17338/// when the tree resolved to more than one transform unit.
17339#[allow(clippy::too_many_arguments)]
17340fn read_block_tx_size(
17341 dec: &mut SymbolDecoder,
17342 cdfs: &mut Cdfs,
17343 n: &mut Neighbours,
17344 at_mi: (usize, usize),
17345 side: usize,
17346 (mi_cols, mi_rows): (usize, usize),
17347 is_inter: bool,
17348 skip: bool, fctx: &crate::decode::FrameCtx,
17349) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17350 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17351 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
17352 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
17353 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
17354 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
17355 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
17356 if side > 64 {
17357 let step = 64 / MI;
17358 let mut leaves = Vec::new();
17359 for row in (0..side / MI).step_by(step) {
17360 for col in (0..side / MI).step_by(step) {
17361 leaves.push((row, col, 64, 64));
17362 }
17363 }
17364 return Ok((64, Some(leaves)));
17365 }
17366 return Ok((side, None));
17367 }
17368 let side_mi = side / MI;
17369 if is_inter && !skip {
17370 let max_tx = side.min(64);
17371 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
17372 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
17373 let mut leaves = Vec::new();
17374 let step = max_tx / MI;
17375 for row in (0..side_mi).step_by(step) {
17376 for col in (0..side_mi).step_by(step) {
17377 read_var_tx_size(
17378 dec,
17379 cdfs,
17380 n,
17381 at_mi,
17382 side,
17383 (max_w_mi, max_h_mi),
17384 (max_tx, max_tx),
17385 0,
17386 row,
17387 col,
17388 &mut leaves,
17389 );
17390 }
17391 }
17392 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
17393 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
17394 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
17395 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
17396 // which the mu-chunk reader above codes as their 32x32 coded corner.
17397 let leaf_ceiling = if side > 64 { 64 } else { 32 };
17398 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
17399 // Only a block wider than a superblock's own 64x64 max transform
17400 // reaches here; this crate has no 64-point *inter* coefficient
17401 // table set ([`inter_txbset_for`] stops at 32).
17402 return Err(unsupported(
17403 "an inter var-tx tree with a leaf transform larger than 32x32",
17404 ));
17405 }
17406 let resolved = leaves.last().map_or(side, |l| l.2);
17407 return Ok((resolved, (!single).then_some(leaves)));
17408 }
17409 let tx = if is_inter {
17410 side.min(64)
17411 } else {
17412 read_tx_size(
17413 dec,
17414 cdfs,
17415 n,
17416 at_mi,
17417 side,
17418 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
17419 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
17420 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
17421 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
17422 )
17423 };
17424 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
17425 if !is_inter && tx != side {
17426 // lane-intrainter r1: an intra block inside an inter frame whose
17427 // `tx_depth` split its luma transform codes exactly the key-frame
17428 // split path's transform units (`decode_block`'s multi-TU loop),
17429 // raster order over the block. Handed back in the same leaf shape the
17430 // inter var-tx tree uses, so the caller's per-TU luma loop, the
17431 // `record_split_luma` neighbour write-back and the per-TU deblock
17432 // edges are the ones it already runs for a var-tx inter block. A
17433 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
17434 // seeing `Some` here.
17435 let step = tx / MI;
17436 let mut leaves = Vec::new();
17437 for row in (0..side_mi).step_by(step) {
17438 for col in (0..side_mi).step_by(step) {
17439 leaves.push((row, col, tx, tx));
17440 }
17441 }
17442 hit_do! {
17443 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
17444 let mut h = c.get();
17445 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
17446 c.set(h);
17447 });
17448 }
17449 return Ok((tx, Some(leaves)));
17450 }
17451 Ok((tx, None))
17452}
17453
17454/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
17455/// decoder codes -- a 2:1 strip whose own max rect transform
17456/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
17457/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
17458/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
17459/// 64-point rect transform, and 16x8/8x16 needs
17460/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
17461/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
17462/// rect transform), neither of which exists yet -- both stay refused by name.
17463pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
17464 matches!(
17465 (w, h),
17466 // 2:1 strips whose transform is coded in full (lane-inter4).
17467 (32, 16) | (16, 32) | (16, 8) | (8, 16)
17468 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
17469 // codes all 64 of its positions, and its chroma pair is an 8x4 /
17470 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
17471 | (16, 4) | (4, 16)
17472 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
17473 // only the low 32 coefficients of a 64-length axis, so these read
17474 // exactly the truncated corner the INTRA superblock-strip path
17475 // already reads (`read_intra_mode_rect`), through
17476 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
17477 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
17478 // `tx_type` symbol is coded at all.
17479 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
17480 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
17481 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
17482 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
17483 // refused earlier ("an inter partition below 8x8").
17484 | (8, 4) | (4, 8)
17485 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
17486 // one rectangular transform -- `max_txsize_rect_lookup
17487 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
17488 // TX_64X64 units read through the mu-chunk loop, same as the
17489 // 128x128 NONE block's four.
17490 | (128, 64) | (64, 128)
17491 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
17492 // 10-bit film cuts and every measured 1080p offset stop on
17493 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
17494 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
17495 // positions, and its chroma pair is a 16x4 / 4x16 unit
17496 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
17497 | (32, 8) | (8, 32)
17498 )
17499}
17500
17501// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
17502// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
17503// the "rectangular ... has no ... here" refusals. `side` is the square context
17504// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
17505// `inter_piece!` derives `reject_residual` from exactly that inequality, so
17506// these triples are what decides whether those refusals can fire at all. Bit
17507// 31 is "a triple this table does not list", which is what makes the gate a
17508// census rather than a restatement of its own table.
17509pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
17510 (16, 16, 16),
17511 (32, 32, 32),
17512 (32, 16, 32),
17513 (32, 32, 16),
17514 (16, 8, 16),
17515 (16, 16, 8),
17516 (32, 8, 32),
17517 (64, 64, 64),
17518 (32, 32, 8),
17519 (64, 16, 64),
17520 (128, 128, 128),
17521 (64, 32, 64),
17522 (64, 64, 32),
17523 (16, 4, 16),
17524 (64, 64, 16),
17525 (16, 16, 4),
17526 (128, 128, 64),
17527 (128, 64, 128),
17528];
17529
17530/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
17531/// outside [`INTER_BLOCK_SHAPES`].
17532pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
17533
17534thread_local! {
17535 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
17536}
17537
17538/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
17539/// gate reading it sees only the streams it decoded itself).
17540pub fn inter_block_shape_mask() -> u32 {
17541 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
17542}
17543
17544/// Records one block's shape. The table is ordered by measured frequency over
17545/// the three witnesses the census gate decodes, so the common square shapes
17546/// leave the scan on their first comparison.
17547fn census_inter_block_shape(side: usize, w: usize, h: usize) {
17548 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
17549 Some(i) => 1u32 << i,
17550 None => INTER_BLOCK_SHAPE_UNLISTED,
17551 };
17552 let seen = inter_block_shape_mask();
17553 if seen & bit == 0 {
17554 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
17555 }
17556}
17557
17558/// The luma coefficient/`tx_type` table set of a whole-block rectangular
17559/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
17560/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
17561/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
17562/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
17563/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
17564/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
17565/// row (`txsize_sqr_map`), never the 16x16 one.
17566fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
17567 Ok(match (w, h) {
17568 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
17569 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
17570 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
17571 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
17572 // ALL16 otherwise -- both at the TX_4X4 row.
17573 (8, 4) | (4, 8) => {
17574 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17575 TxbSet::LumaRect8x4Inter
17576 } else {
17577 TxbSet::LumaRect8x4InterSet1
17578 }
17579 }
17580 (16, 4) | (4, 16) => {
17581 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17582 TxbSet::LumaRect16x4Inter
17583 } else {
17584 TxbSet::LumaRect16x4Inter1
17585 }
17586 }
17587 (16, 8) | (8, 16) => {
17588 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17589 TxbSet::LumaRect16x8Inter
17590 } else {
17591 TxbSet::LumaRect16x8InterSet1
17592 }
17593 }
17594 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
17595 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
17596 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
17597 // adjusted size, so the existing sets are bit-exact. Neither carries a
17598 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
17599 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
17600 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
17601 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
17602 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
17603 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
17604 (64, 32) | (32, 64) => TxbSet::Luma64,
17605 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
17606 _ => {
17607 return Err(unsupported(
17608 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
17609 ));
17610 }
17611 })
17612}
17613
17614/// The chroma table set of the same block's single rectangular chroma unit
17615/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
17616/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
17617/// the luma unit's.
17618fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
17619 Ok(match (w, h) {
17620 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
17621 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
17622 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
17623 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
17624 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
17625 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
17626 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
17627 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
17628 (32, 8) | (8, 32) => TxbSet::Chroma16,
17629 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
17630 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
17631 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
17632 (16, 4) | (4, 16) => TxbSet::Chroma8,
17633 _ => {
17634 return Err(unsupported(
17635 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
17636 ));
17637 }
17638 })
17639}
17640
17641/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
17642/// inter path reaches, from the block's TRUE footprint rather than the
17643/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
17644/// everything 32 and above -> 3.
17645fn size_group_wh(w: usize, h: usize) -> usize {
17646 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
17647 // `common_data.h:60`) is 0 for every block with a 4-px side
17648 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
17649 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
17650 match w.min(h) {
17651 0..=4 => 0,
17652 8 => 1,
17653 16 => 2,
17654 _ => 3,
17655 }
17656}
17657
17658#[test]
17659fn size_group_wh_matches_libaom_size_group_lookup() {
17660 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
17661 // transcribed values (common_data.h:60-62).
17662 const TABLE: [((usize, usize), usize); 22] = [
17663 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
17664 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
17665 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
17666 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
17667 ];
17668 for ((w, h), want) in TABLE {
17669 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
17670 }
17671}
17672
17673/// The default (2D) coefficient scan of a rectangular transform.
17674fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
17675 Ok(match (w, h) {
17676 (32, 16) => &SCAN_32X16,
17677 (16, 32) => &SCAN_16X32,
17678 (16, 8) => &SCAN_16X8,
17679 (8, 16) => &SCAN_8X16,
17680 (16, 4) => &SCAN_16X4,
17681 (4, 16) => &SCAN_4X16,
17682 (8, 4) => &SCAN_8X4,
17683 (4, 8) => &SCAN_4X8,
17684 (32, 8) => &SCAN_32X8,
17685 (8, 32) => &SCAN_8X32,
17686 _ => {
17687 return Err(unsupported(
17688 "a rectangular transform unit whose shape has no coefficient scan table here",
17689 ));
17690 }
17691 })
17692}
17693
17694/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
17695/// transform unit whose shape has no coefficient table set here" / "a
17696/// rectangular transform unit whose shape has no coefficient scan table here"
17697/// arms, enumerated against the MEASURED domain of the inter block path
17698/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
17699/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
17700///
17701/// What each helper is actually handed:
17702///
17703/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
17704/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
17705/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
17706/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
17707/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
17708/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
17709/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
17710/// unit, and only when that corner is not 32x32 (a square corner goes
17711/// through the square reader with `rect_shape = Some((w, h))`).
17712///
17713/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
17714/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
17715/// loop, which is why they are skipped below.
17716#[test]
17717fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
17718 let fctx = &crate::decode::FrameCtx::new();
17719 let corner_scan = |w: usize, h: usize| {
17720 let (cw, ch) = (w.min(32), h.min(32));
17721 if (cw, ch) == (32, 32) {
17722 return; // the square coefficient reader, not `rect_scan`
17723 }
17724 assert!(
17725 rect_scan(cw, ch).is_ok(),
17726 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
17727 );
17728 };
17729 let mut checked = 0;
17730 for &(side, w, h) in &INTER_BLOCK_SHAPES {
17731 if (w, h) == (side, side) || w.max(h) > 64 {
17732 continue;
17733 }
17734 assert!(
17735 rect_inter_luma_set(w, h, fctx).is_ok(),
17736 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
17737 );
17738 corner_scan(w, h);
17739 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
17740 // footprint for every other shape.
17741 let (cw, ch) = match (w, h) {
17742 (16, 4) => (8, 4),
17743 (4, 16) => (4, 8),
17744 _ => (w / 2, h / 2),
17745 };
17746 assert!(
17747 rect_inter_chroma_set(cw, ch).is_ok(),
17748 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
17749 );
17750 corner_scan(cw, ch);
17751 checked += 1;
17752 }
17753 assert_eq!(
17754 checked, 12,
17755 "the block-shape census changed: {checked} rect shapes reach the rect transform \
17756 tables, not the 12 this claim was measured over"
17757 );
17758 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
17759 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
17760 for (w, h) in [(8usize, 4usize), (4, 8)] {
17761 assert!(
17762 rect_inter_luma_set(w, h, fctx).is_ok(),
17763 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
17764 );
17765 corner_scan(w, h);
17766 }
17767}
17768
17769/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
17770/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
17771/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
17772/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
17773/// own width/height; a `0` leaves one whole-block rect transform unit
17774/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
17775/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
17776/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
17777/// every leaf of a split rect block is square and the existing square leaf
17778/// loop reconstructs it unchanged.
17779#[allow(clippy::too_many_arguments)]
17780fn read_block_tx_size_rect(
17781 dec: &mut SymbolDecoder,
17782 cdfs: &mut Cdfs,
17783 n: &mut Neighbours,
17784 at_mi: (usize, usize),
17785 (bw, bh): (usize, usize),
17786 (mi_cols, mi_rows): (usize, usize),
17787 skip: bool, fctx: &crate::decode::FrameCtx,
17788) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
17789 if skip {
17790 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
17791 // its own BLOCK size -- width above, height left -- not a transform.
17792 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
17793 return Ok(None);
17794 }
17795 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
17796 // `rect_inter_residual_supported` has already excluded everything above 32.
17797 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
17798 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
17799 // is TWO square top-level transform units side by side and a 64x128 one is
17800 // two stacked -- exactly what libaom `read_block_tx_size`
17801 // (decodeframe.c:1140) codes with its `idy/idx` loop over
17802 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
17803 // own `txfm_partition` symbol at depth 0.
17804 if bw.max(bh) > 64 {
17805 let tx = 64usize;
17806 let (max_w_mi, max_h_mi) = (
17807 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
17808 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
17809 );
17810 let mut leaves = Vec::new();
17811 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17812 for row in (0..bh / MI).step_by(tx / MI) {
17813 for col in (0..bw / MI).step_by(tx / MI) {
17814 leaves.push((row, col, tx, tx));
17815 }
17816 }
17817 for &(row, col, tw, th) in &leaves {
17818 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
17819 }
17820 return Ok(Some(leaves));
17821 }
17822 for row in (0..bh / MI).step_by(tx / MI) {
17823 for col in (0..bw / MI).step_by(tx / MI) {
17824 read_var_tx_size(
17825 dec,
17826 cdfs,
17827 n,
17828 at_mi,
17829 bw.max(bh),
17830 (max_w_mi, max_h_mi),
17831 (tx, tx),
17832 0,
17833 row,
17834 col,
17835 &mut leaves,
17836 );
17837 }
17838 }
17839 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
17840 return Err(unsupported(
17841 "an inter var-tx tree with a leaf transform larger than 64x64",
17842 ));
17843 }
17844 return Ok(Some(leaves));
17845 }
17846 let (tx_w, tx_h) = (bw, bh);
17847 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17848 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
17849 // transform, and `set_txfm_ctxs` records exactly what
17850 // `txfm_partition_update` would for that same unit.
17851 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17852 hit!(RECT_INTER_TU_HITS);
17853 return Ok(None);
17854 }
17855 let ctx = txfm_partition_ctx_rect(
17856 n.above_txfm[at_mi.1],
17857 n.left_txfm[at_mi.0],
17858 bw.max(bh),
17859 tx_w,
17860 tx_h,
17861 );
17862 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17863 hit!(TXFM_SPLIT_READS);
17864 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17865 let (rng, _) = dec.debug_state();
17866 eprintln!(
17867 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17868 at_mi.0,
17869 at_mi.1,
17870 u8::from(split)
17871 );
17872 }
17873 if !split {
17874 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17875 hit!(RECT_INTER_TU_HITS);
17876 return Ok(None);
17877 }
17878 hit!(TXFM_SPLIT_HITS);
17879 hit!(RECT_INTER_TXSPLIT_HITS);
17880 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
17881 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
17882 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
17883 // rect one and its leaves carry their own width and height.
17884 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17885 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
17886 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
17887 let mut leaves = Vec::new();
17888 for row in (0..bh / MI).step_by(sub_h / MI) {
17889 for col in (0..bw / MI).step_by(sub_w / MI) {
17890 read_var_tx_size(
17891 dec,
17892 cdfs,
17893 n,
17894 at_mi,
17895 bw.max(bh),
17896 (max_w_mi, max_h_mi),
17897 (sub_w, sub_h),
17898 1,
17899 row,
17900 col,
17901 &mut leaves,
17902 );
17903 }
17904 }
17905 Ok(Some(leaves))
17906}
17907
17908/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
17909/// the coefficients are read with the rect coefficient machinery
17910/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
17911/// types), inverted with the rect inverse transform
17912/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
17913/// and added onto the top-left `w x h` of the block's own square-strided
17914/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
17915/// and the coded `tx_type`.
17916///
17917/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
17918/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
17919#[allow(clippy::too_many_arguments)]
17920fn read_inter_plane_rect(
17921 dec: &mut SymbolDecoder,
17922 cdfs: &mut Cdfs,
17923 set: TxbSet,
17924 (w, h): (usize, usize),
17925 stride: usize,
17926 plane_idx: usize,
17927 around: (bool, bool, i32),
17928 tx_mode: usize,
17929 // lane-wave1 step (i): unread -- this reader records its write
17930 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
17931 // stays in the signature so every call site still proves the plane is
17932 // exclusively held while its coefficients are parsed.
17933 _plane: &mut PlaneBuf<'static>,
17934 x: usize,
17935 y: usize,
17936 prediction: Pred<'_>,
17937 inherited_luma_tx_type: Option<TxType>,
17938 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
17939) -> Result<(Grid, TxType)> {
17940 let skip_ctx = if plane_idx == 0 {
17941 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
17942 // block; a var-tx leaf passes its own neighbour-table context.
17943 luma_skip_ctx.unwrap_or(0)
17944 } else {
17945 usize::from(around.0) + usize::from(around.1)
17946 };
17947 let mut coding = cdfs.txb(set, tx_mode);
17948 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
17949 // the *longer* side of this rect transform.
17950 let default_tx_type = match inherited_luma_tx_type {
17951 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
17952 None => TxType::DctDct,
17953 };
17954 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
17955 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
17956 // corner, zero-extended into the true `w x h` grid before the inverse
17957 // transform -- exactly what the intra superblock-strip path does. A
17958 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
17959 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
17960 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
17961 // rectangular shape (lane-sbpart r8).
17962 let (cw, ch) = (w.min(32), h.min(32));
17963 if plane_idx == 0 && w.max(h) == 64 {
17964 hit!(RECT64_INTER_TU_HITS);
17965 }
17966 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
17967 hit_do! {
17968 RECT32X8_INTER_TU_HITS.with(|c| {
17969 let mut v = c.get();
17970 v[usize::from(w == 8)] += 1;
17971 c.set(v);
17972 });
17973 }
17974 }
17975 let (corner, tx_type) = if (cw, ch) == (32, 32) {
17976 let scan32 = default_scan(TX32);
17977 read_coeffs(
17978 dec,
17979 &mut coding,
17980 &scan32,
17981 skip_ctx,
17982 dc_sign_ctx(around.2),
17983 default_tx_type,
17984 Some((w, h)),
17985 )?
17986 } else {
17987 read_coeffs_rect(
17988 dec,
17989 &mut coding,
17990 rect_scan(cw, ch)?,
17991 cw,
17992 ch,
17993 skip_ctx,
17994 dc_sign_ctx(around.2),
17995 default_tx_type,
17996 )?
17997 };
17998 let grid = extend_corner(corner, cw, ch, w, h);
17999 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
18000 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
18001 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
18002 }
18003 // `reconstruct_mc_rect` reads both buffers at the square prediction
18004 // stride, so the dense `w x h` residual is re-laid at that stride
18005 // (`TxParams::stride`) after the inverse transform.
18006 let tx = TxParams {
18007 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18008 stride,
18009 };
18010 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
18011 Ok((grid, tx_type))
18012}
18013
18014/// The coded `cw x ch` corner of a transform zero-extended into its true
18015/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
18016/// corner that coded nothing stays the shared zero grid -- no allocation
18017/// (lane-coefgrid).
18018fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
18019 if (cw, ch) == (w, h) {
18020 return corner;
18021 }
18022 if let Grid::Zero(_) = corner {
18023 return Grid::Zero(w * h);
18024 }
18025 let mut full = vec![0i32; w * h];
18026 for row in 0..ch {
18027 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
18028 }
18029 Grid::Own(full)
18030}
18031
18032/// A rect coefficient grid re-laid into the square `stride x stride` grid the
18033/// neighbour/deblock stamps downstream of the residual expect.
18034fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
18035 let mut full = vec![0i32; stride * stride];
18036 for row in 0..h {
18037 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
18038 }
18039 full
18040}
18041
18042/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
18043/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
18044/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
18045/// raster order, each reading its own coefficient context off the units
18046/// already decoded before it. Returns the block's luma grid (all-zero in the
18047/// split case, whose reconstruction has already happened unit by unit) and
18048/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
18049/// which for a split block lands on the top-left unit.
18050#[allow(clippy::too_many_arguments)]
18051fn read_inter_luma8(
18052 dec: &mut SymbolDecoder,
18053 cdfs: &mut Cdfs,
18054 neighbours: &mut Neighbours,
18055 leaf_mi: (usize, usize),
18056 y: &mut PlaneBuf<'static>,
18057 px: usize,
18058 py: usize,
18059 pred_y: Pred<'_>,
18060 mode_for_tx: usize,
18061 base_q_idx: u8,
18062 scan8: &[u16],
18063 scan4: &[u16],
18064 reduced_tx_set: bool,
18065 split: bool, fctx: &crate::decode::FrameCtx,
18066) -> Result<(Grid, TxType)> {
18067 if !split {
18068 return read_inter_plane(
18069 dec,
18070 cdfs,
18071 if reduced_tx_set {
18072 TxbSet::Luma8Inter
18073 } else {
18074 TxbSet::Luma8InterSet1
18075 },
18076 scan8,
18077 0,
18078 neighbours.around_mi(leaf_mi, 8)[0],
18079 mode_for_tx,
18080 y,
18081 px,
18082 py,
18083 8,
18084 base_q_idx,
18085 pred_y,
18086 None,
18087 None, fctx,
18088 );
18089 }
18090 let mut first = TxType::DctDct;
18091 for tu_row in 0..2 {
18092 for tu_col in 0..2 {
18093 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18094 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
18095 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18096 let (tu_grid, tu_tx_type) = read_inter_plane(
18097 dec,
18098 cdfs,
18099 if reduced_tx_set {
18100 TxbSet::Luma4Inter
18101 } else {
18102 TxbSet::Luma4InterSet1
18103 },
18104 scan4,
18105 0,
18106 neighbours.around_mi(tu_mi, 4)[0],
18107 mode_for_tx,
18108 y,
18109 px + tu_col * 4,
18110 py + tu_row * 4,
18111 4,
18112 base_q_idx,
18113 tu_pred,
18114 None,
18115 Some(tu_skip_ctx), fctx,
18116 )?;
18117 if tu_row == 0 && tu_col == 0 {
18118 first = tu_tx_type;
18119 }
18120 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18121 }
18122 }
18123 Ok((Grid::Zero(64), first))
18124}
18125
18126/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
18127/// coefficient tables from -- the inter counterpart of [`txbset_for`].
18128/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
18129/// an inter block's chroma transform inherits the *colocated luma* unit's
18130/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
18131/// of the extended set the CHROMA transform size selects
18132/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
18133/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
18134/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
18135/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
18136/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
18137/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
18138/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
18139/// sync and only corrupted the inverse transform (one 64x64 superblock of
18140/// high-frequency chroma noise, luma bit-exact).
18141fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
18142 use TxType::*;
18143 let sqr_up = w.max(h);
18144 let sqr = w.min(h);
18145 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
18146 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
18147 let allowed: &[TxType] = if sqr_up > 32 {
18148 // EXT_TX_SET_DCTONLY
18149 &[DctDct]
18150 } else if sqr_up == 32 || reduced {
18151 // EXT_TX_SET_DCT_IDTX
18152 &[DctDct, Idtx]
18153 } else if sqr == 16 {
18154 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
18155 // the four 1D ADST/FLIPADST types.
18156 &[
18157 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
18158 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
18159 ]
18160 } else {
18161 // EXT_TX_SET_ALL16
18162 return t;
18163 };
18164 if allowed.contains(&t) { t } else { DctDct }
18165}
18166
18167fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18168 match tx_px {
18169 // lane-sb128c r1: a 128x128 inter block's own luma unit
18170 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
18171 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
18172 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
18173 // coincide -- exactly the set the whole-64x64 inter block already uses.
18174 64 => TxbSet::Luma64,
18175 32 => TxbSet::Luma32Inter,
18176 16 if reduced_tx_set => TxbSet::Luma16Inter,
18177 16 => TxbSet::Luma16InterSet1,
18178 8 if reduced_tx_set => TxbSet::Luma8Inter,
18179 8 => TxbSet::Luma8InterSet1,
18180 4 if reduced_tx_set => TxbSet::Luma4Inter,
18181 4 => TxbSet::Luma4InterSet1,
18182 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
18183 }
18184}
18185
18186/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
18187/// the only four sizes a `TxMode::Select` block's coded coefficient grid
18188/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
18189fn scan_for<'a>(
18190 tx_px: usize,
18191 scan32: &'a [u16],
18192 scan16: &'a [u16],
18193 scan8: &'a [u16],
18194 scan4: &'a [u16],
18195) -> &'a [u16] {
18196 match tx_px {
18197 32 => scan32,
18198 16 => scan16,
18199 8 => scan8,
18200 4 => scan4,
18201 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
18202 }
18203}
18204
18205/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
18206/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
18207/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
18208/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
18209/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
18210/// regardless of the flag (`av1_get_ext_tx_set_type`'s
18211/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
18212/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
18213/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
18214/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
18215/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
18216/// inter `ext_tx` sets, never the mode-indexed intra ones.
18217fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18218 match tx_px {
18219 64 => TxbSet::Luma64,
18220 32 => TxbSet::Luma32Inter,
18221 16 if reduced_tx_set => TxbSet::Luma16Inter,
18222 16 => TxbSet::Luma16InterSet1,
18223 8 if reduced_tx_set => TxbSet::Luma8Inter,
18224 8 => TxbSet::Luma8InterSet1,
18225 _ => TxbSet::Luma64,
18226 }
18227}
18228
18229fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18230 match tx_px {
18231 64 => TxbSet::Luma64,
18232 32 => TxbSet::Luma32,
18233 16 => TxbSet::Luma16,
18234 8 if reduced_tx_set => TxbSet::Luma8,
18235 8 => TxbSet::Luma8Set1,
18236 4 if reduced_tx_set => TxbSet::Luma4,
18237 4 => TxbSet::Luma4Set1,
18238 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
18239 }
18240}
18241
18242/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
18243/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
18244fn unit_log2(px: u32) -> i32 {
18245 if px == 0 {
18246 0
18247 } else {
18248 px.trailing_zeros() as i32 - 2
18249 }
18250}
18251
18252/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
18253/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
18254/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
18255/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
18256/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
18257/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
18258/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
18259/// block anywhere aborted the whole stream's decode before comparison).
18260fn lf_level(
18261 lf: &LoopFilterParams,
18262 plane_idx: usize,
18263 dir: usize,
18264 ref_frame: i8,
18265 delta_lf: i32,
18266 segment_id: u8, fctx: &crate::decode::FrameCtx,
18267) -> i32 {
18268 let base = i32::from(if plane_idx == 0 {
18269 lf.level[dir]
18270 } else if plane_idx == 1 {
18271 lf.level[2]
18272 } else {
18273 lf.level[3]
18274 });
18275 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
18276 // ref/mode delta scaling below, and regardless of `delta_enabled`
18277 // (that flag only gates `ref_deltas`/`mode_deltas`).
18278 let base = (base + delta_lf).clamp(0, 63);
18279 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
18280 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
18281 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
18282 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
18283 // for chroma.
18284 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18285 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
18286 // when the frame codes no segmentation (`seg_lf_active`), which is what
18287 // spares the deblock loop two thread-local reads per 4x4 edge.
18288 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
18289 Some(data) => (base + data).clamp(0, 63),
18290 None => base,
18291 };
18292 if !lf.delta_enabled {
18293 return base;
18294 }
18295 let scale = 1i32 << (base >> 5);
18296 let is_inter = ref_frame != 0;
18297 let is_globalmv = ref_frame < 0;
18298 let ref_idx = ref_frame.unsigned_abs() as usize;
18299 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
18300 if is_inter {
18301 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
18302 }
18303 lvl.clamp(0, 63)
18304}
18305
18306thread_local! {
18307 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
18308 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
18309 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
18310 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
18311 /// build per plane and pass serves the whole frame. The pipeline builds
18312 /// an `EdgeCtx` per superblock-row band rather than per frame, which
18313 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
18314 static LVL_CACHE: std::cell::RefCell<
18315 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
18316 > = const { std::cell::RefCell::new(Vec::new()) };
18317}
18318
18319/// `lf_level` over the whole `(base level, ref frame)` domain -- see
18320/// [`LVL_CACHE`]. `lf_level`'s own first step is
18321/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
18322/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
18323fn lvl_table(
18324 lf: &LoopFilterParams,
18325 plane_idx: usize,
18326 dir: usize,
18327 base0: i32,
18328 fctx: &crate::decode::FrameCtx,
18329) -> [[u8; 15]; 64] {
18330 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18331 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
18332 if let Some(t) = LVL_CACHE.with(|c| {
18333 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
18334 }) {
18335 return t;
18336 }
18337 let mut lvl = [[0u8; 15]; 64];
18338 for (b, row) in lvl.iter_mut().enumerate() {
18339 for (r, cell) in row.iter_mut().enumerate() {
18340 *cell =
18341 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
18342 }
18343 }
18344 LVL_CACHE.with(|c| {
18345 let mut c = c.borrow_mut();
18346 if c.len() >= 8 {
18347 c.remove(0);
18348 }
18349 c.push((key, lvl));
18350 });
18351 lvl
18352}
18353
18354/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18355/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18356/// that a coded block's transform is always its own full size -- so a TU
18357/// edge is always also a PU edge, and the "both sides skipped, not a PU
18358/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18359/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18360/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18361/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
18362/// seven values that used to be re-passed per 4-pixel edge group -- half of
18363/// them on the stack, into an `inline(never)` body -- plus libaom's
18364/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
18365/// filter level for every `(base level, ref frame)` pair once per frame
18366/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
18367struct EdgeCtx<'a> {
18368 lf: &'a LoopFilterParams,
18369 n: &'a Neighbours,
18370 fctx: &'a crate::decode::FrameCtx,
18371 plane_idx: usize,
18372 dir: usize,
18373 chroma: bool,
18374 seg_lf_active: bool,
18375 /// `delta_lf_grid`'s column for this plane and direction.
18376 delta_idx: usize,
18377 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
18378 /// chroma.
18379 step: usize,
18380 /// This pass's own `lf.level[..]`, the LUT's base.
18381 base0: i32,
18382 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
18383 /// override -- the whole domain, since a level is `0..=63` and a ref
18384 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
18385 /// entries and is indexed by the ref frame's magnitude).
18386 lvl: [[u8; 15]; 64],
18387}
18388
18389impl<'a> EdgeCtx<'a> {
18390 fn new(
18391 lf: &'a LoopFilterParams,
18392 n: &'a Neighbours,
18393 plane_idx: usize,
18394 dir: usize,
18395 chroma: bool,
18396 seg_lf_active: bool,
18397 fctx: &'a crate::decode::FrameCtx,
18398 ) -> Self {
18399 let base0 = i32::from(if plane_idx == 0 {
18400 lf.level[dir]
18401 } else if plane_idx == 1 {
18402 lf.level[2]
18403 } else {
18404 lf.level[3]
18405 });
18406 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
18407 Self {
18408 lf,
18409 n,
18410 fctx,
18411 plane_idx,
18412 dir,
18413 chroma,
18414 seg_lf_active,
18415 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
18416 step: if chroma { 2 } else { 1 },
18417 base0,
18418 lvl,
18419 }
18420 }
18421
18422 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
18423 /// override it (which is every frame that codes no segmentation).
18424 #[inline(always)]
18425 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
18426 if self.seg_lf_active {
18427 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
18428 }
18429 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
18430 debug_assert!((-7..=7).contains(&ref_frame));
18431 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
18432 i32::from(self.lvl[b][r])
18433 }
18434}
18435
18436/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18437/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18438/// that a coded block's transform is always its own full size -- so a TU
18439/// edge is always also a PU edge, and the "both sides skipped, not a PU
18440/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18441/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18442/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18443#[inline(always)]
18444fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
18445 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
18446 let cur_tx = if c.dir == 0 {
18447 tx_px_at(c.n, c.chroma, mi_r, mi_c)
18448 } else {
18449 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
18450 };
18451 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
18452 // test is a mask, not the hardware `divl` this used to emit (10.7% of
18453 // `edge_params`' own samples sat on that divide's result test).
18454 //
18455 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
18456 // the covering transform does not start at), so this head is inlined
18457 // into the deblock loops and only survivors pay the call and the
18458 // register-spilling prologue of the body below.
18459 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
18460 return None;
18461 }
18462 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
18463}
18464
18465/// [`edge_params`] past its transform-alignment gate.
18466#[inline(never)]
18467fn edge_params_body(
18468 c: &EdgeCtx,
18469 x0: usize,
18470 y0: usize,
18471 mi_r: usize,
18472 mi_c: usize,
18473 cur_tx: u32,
18474) -> Option<(u8, i32)> {
18475 let n = c.n;
18476 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18477 // The previous cell must keep the odd parity `plane_to_mi` just
18478 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
18479 // not the other half of this one.
18480 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
18481 (mi_r, mi_c - c.step)
18482 } else {
18483 (mi_r - c.step, mi_c)
18484 };
18485 let pv_tx = if c.dir == 0 {
18486 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18487 } else {
18488 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18489 };
18490 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
18491 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
18492 let pv_delta_lf =
18493 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
18494
18495 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
18496 // SKIPPED INTER blocks is filtered only when it is also a prediction
18497 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
18498 // omission of this term (on the stale invariant "a coded block's transform
18499 // is always its own full size", which var-tx broke) had us filtering an
18500 // interior 8-px lattice the reference never touches: on the pinned 192x68
18501 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
18502 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
18503 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
18504 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
18505 // edge of a sub-8x8 group is a prediction edge, even though the group's
18506 // bottom/right mi does not start there. Comparing mi origins instead is
18507 // the same test only while the block's own origin is aligned to its
18508 // size, which a 4x4 luma block read at the `| 1` mi is not.
18509 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18510 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
18511 let (org_px, dim_mi) = if c.dir == 0 {
18512 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
18513 } else {
18514 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
18515 };
18516 let pu_edge = if c.chroma {
18517 let plane_dim = (dim_mi * MI / 2).max(4);
18518 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
18519 } else {
18520 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
18521 };
18522 if !pu_edge
18523 && cur_ref != 0
18524 && pv_ref != 0
18525 && n.skip_at(mi_r, mi_c)
18526 && n.skip_at(pv_mi_r, pv_mi_c)
18527 {
18528 return None;
18529 }
18530 let (cur_seg, pv_seg) = if c.seg_lf_active {
18531 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
18532 } else {
18533 (0, 0)
18534 };
18535 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
18536 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
18537 if cur_level == 0 && pv_level == 0 {
18538 return None;
18539 }
18540 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
18541 let len: u8 = if c.chroma {
18542 if dim == 0 { 4 } else { 6 }
18543 } else {
18544 [4, 8, 14, 14, 14][dim]
18545 };
18546 let level = if cur_level != 0 { cur_level } else { pv_level };
18547 hit!(DEBLOCK_HITS);
18548 Some((len, level))
18549}
18550
18551/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
18552fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
18553 let sharpness = i32::from(sharpness);
18554 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
18555 let mut lim = level >> shift;
18556 if sharpness > 0 {
18557 lim = lim.min(9 - sharpness);
18558 }
18559 lim = lim.max(1);
18560 (2 * (level + 2) + lim, lim, level >> 4)
18561}
18562
18563#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
18564fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
18565 // libaom's `signed_char_clamp_high`: the clamp range scales with
18566 // `128 << (bit_depth - 8)` alongside the centering constant below.
18567 let scale = 1i32 << (bit_depth(fctx) - 8);
18568 v.clamp(-128 * scale, 128 * scale - 1)
18569}
18570
18571fn round_pow2(v: i32, n: u32) -> i32 {
18572 (v + (1 << (n - 1))) >> n
18573}
18574
18575/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
18576/// fallback.
18577fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
18578 if !mask {
18579 return [p1, p0, q0, q1];
18580 }
18581 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
18582 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
18583 // this kernel's eight clamps, and this kernel runs per deblocked sample.
18584 // Same bound, resolved once.
18585 let scale = 1i32 << (bit_depth(fctx) - 8);
18586 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
18587 let centre = 128i32 * scale;
18588 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
18589 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
18590 let filter = sclamp(outer + 3 * (qs0 - ps0));
18591 let filter1 = sclamp(filter + 4) >> 3;
18592 let filter2 = sclamp(filter + 3) >> 3;
18593 let oq0 = sclamp(qs0 - filter1) + centre;
18594 let op0 = sclamp(ps0 + filter2) + centre;
18595 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
18596 let oq1 = sclamp(qs1 - tap) + centre;
18597 let op1 = sclamp(ps1 + tap) + centre;
18598 [op1, op0, oq0, oq1]
18599}
18600
18601/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
18602/// `filter4`'s narrow taps.
18603#[allow(clippy::too_many_arguments)]
18604fn filter6(
18605 mask: bool,
18606 thresh: i32,
18607 flat: bool,
18608 p2: i32,
18609 p1: i32,
18610 p0: i32,
18611 q0: i32,
18612 q1: i32,
18613 q2: i32, fctx: &crate::decode::FrameCtx,
18614) -> [i32; 4] {
18615 if flat && mask {
18616 [
18617 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
18618 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
18619 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
18620 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
18621 ]
18622 } else {
18623 filter4(mask, thresh, p1, p0, q0, q1, fctx)
18624 }
18625}
18626
18627/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
18628#[allow(clippy::too_many_arguments)]
18629fn filter8(
18630 mask: bool,
18631 thresh: i32,
18632 flat: bool,
18633 p3: i32,
18634 p2: i32,
18635 p1: i32,
18636 p0: i32,
18637 q0: i32,
18638 q1: i32,
18639 q2: i32,
18640 q3: i32, fctx: &crate::decode::FrameCtx,
18641) -> [i32; 6] {
18642 if flat && mask {
18643 [
18644 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
18645 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
18646 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
18647 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
18648 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
18649 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
18650 ]
18651 } else {
18652 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
18653 [p2, op1, op0, oq0, oq1, q2]
18654 }
18655}
18656
18657/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
18658/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
18659/// way -- they are only ever taps here, never written).
18660#[allow(clippy::too_many_arguments)]
18661fn filter14(
18662 mask: bool,
18663 thresh: i32,
18664 flat: bool,
18665 flat2: bool,
18666 p6: i32,
18667 p5: i32,
18668 p4: i32,
18669 p3: i32,
18670 p2: i32,
18671 p1: i32,
18672 p0: i32,
18673 q0: i32,
18674 q1: i32,
18675 q2: i32,
18676 q3: i32,
18677 q4: i32,
18678 q5: i32,
18679 q6: i32, fctx: &crate::decode::FrameCtx,
18680) -> [i32; 12] {
18681 if flat2 && flat && mask {
18682 [
18683 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
18684 round_pow2(
18685 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
18686 4,
18687 ),
18688 round_pow2(
18689 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
18690 4,
18691 ),
18692 round_pow2(
18693 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
18694 4,
18695 ),
18696 round_pow2(
18697 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
18698 4,
18699 ),
18700 round_pow2(
18701 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
18702 4,
18703 ),
18704 round_pow2(
18705 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
18706 4,
18707 ),
18708 round_pow2(
18709 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
18710 4,
18711 ),
18712 round_pow2(
18713 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
18714 4,
18715 ),
18716 round_pow2(
18717 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
18718 4,
18719 ),
18720 round_pow2(
18721 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
18722 4,
18723 ),
18724 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
18725 ]
18726 } else {
18727 let [op2, op1, op0, oq0, oq1, oq2] =
18728 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
18729 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
18730 }
18731}
18732
18733/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
18734/// the first (`q0`) sample past the edge, `outer_stride` advances to the
18735/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
18736/// the next along the edge's own filtering direction.
18737#[allow(clippy::too_many_arguments)]
18738fn filter_edge(
18739 data: &mut [u16],
18740 base: usize,
18741 outer_stride: isize,
18742 tap_stride: isize,
18743 len: u8,
18744 level: i32,
18745 sharpness: u8, fctx: &crate::decode::FrameCtx,
18746) {
18747 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
18748 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
18749 // every 8-bit threshold (including the flat masks' fixed `1`) is
18750 // compared against a raw pixel difference on the stream's own bit-depth
18751 // scale, so each is shifted left by `bit_depth - 8` before use.
18752 let shift = bit_depth(fctx) - 8;
18753 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
18754 let flat_thresh = 1i32 << shift;
18755 let smax = sample_max(fctx);
18756 for i in 0..4isize {
18757 let center = (base as isize + i * outer_stride) as usize;
18758 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
18759 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
18760 match len {
18761 4 => {
18762 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
18763 let mask = (p1 - p0).abs() <= limit
18764 && (q1 - q0).abs() <= limit
18765 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18766 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
18767 data[idx(-2)] = op1.clamp(0, smax) as u16;
18768 data[idx(-1)] = op0.clamp(0, smax) as u16;
18769 data[idx(0)] = oq0.clamp(0, smax) as u16;
18770 data[idx(1)] = oq1.clamp(0, smax) as u16;
18771 }
18772 6 => {
18773 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
18774 let mask = (p2 - p1).abs() <= limit
18775 && (p1 - p0).abs() <= limit
18776 && (q1 - q0).abs() <= limit
18777 && (q2 - q1).abs() <= limit
18778 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18779 let flat = (p1 - p0).abs() <= flat_thresh
18780 && (q1 - q0).abs() <= flat_thresh
18781 && (p2 - p0).abs() <= flat_thresh
18782 && (q2 - q0).abs() <= flat_thresh;
18783 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
18784 data[idx(-2)] = op1.clamp(0, smax) as u16;
18785 data[idx(-1)] = op0.clamp(0, smax) as u16;
18786 data[idx(0)] = oq0.clamp(0, smax) as u16;
18787 data[idx(1)] = oq1.clamp(0, smax) as u16;
18788 }
18789 8 => {
18790 let (p3, p2, p1, p0, q0, q1, q2, q3) =
18791 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
18792 let mask = (p3 - p2).abs() <= limit
18793 && (p2 - p1).abs() <= limit
18794 && (p1 - p0).abs() <= limit
18795 && (q1 - q0).abs() <= limit
18796 && (q2 - q1).abs() <= limit
18797 && (q3 - q2).abs() <= limit
18798 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18799 let flat = (p1 - p0).abs() <= flat_thresh
18800 && (q1 - q0).abs() <= flat_thresh
18801 && (p2 - p0).abs() <= flat_thresh
18802 && (q2 - q0).abs() <= flat_thresh
18803 && (p3 - p0).abs() <= flat_thresh
18804 && (q3 - q0).abs() <= flat_thresh;
18805 let [op2, op1, op0, oq0, oq1, oq2] =
18806 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
18807 data[idx(-3)] = op2.clamp(0, smax) as u16;
18808 data[idx(-2)] = op1.clamp(0, smax) as u16;
18809 data[idx(-1)] = op0.clamp(0, smax) as u16;
18810 data[idx(0)] = oq0.clamp(0, smax) as u16;
18811 data[idx(1)] = oq1.clamp(0, smax) as u16;
18812 data[idx(2)] = oq2.clamp(0, smax) as u16;
18813 }
18814 _ => {
18815 let (p6, p5, p4, p3, p2, p1, p0) =
18816 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
18817 let (q0, q1, q2, q3, q4, q5, q6) =
18818 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
18819 let mask = (p3 - p2).abs() <= limit
18820 && (p2 - p1).abs() <= limit
18821 && (p1 - p0).abs() <= limit
18822 && (q1 - q0).abs() <= limit
18823 && (q2 - q1).abs() <= limit
18824 && (q3 - q2).abs() <= limit
18825 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18826 let flat = (p1 - p0).abs() <= flat_thresh
18827 && (q1 - q0).abs() <= flat_thresh
18828 && (p2 - p0).abs() <= flat_thresh
18829 && (q2 - q0).abs() <= flat_thresh
18830 && (p3 - p0).abs() <= flat_thresh
18831 && (q3 - q0).abs() <= flat_thresh;
18832 let flat2 = (p4 - p0).abs() <= flat_thresh
18833 && (q4 - q0).abs() <= flat_thresh
18834 && (p5 - p0).abs() <= flat_thresh
18835 && (q5 - q0).abs() <= flat_thresh
18836 && (p6 - p0).abs() <= flat_thresh
18837 && (q6 - q0).abs() <= flat_thresh;
18838 let out = filter14(
18839 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
18840 q6, fctx,
18841 );
18842 for (k, v) in (-6..=5isize).zip(out) {
18843 data[idx(k)] = v.clamp(0, smax) as u16;
18844 }
18845 }
18846 }
18847 }
18848}
18849
18850/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
18851/// 4K decode's self time, spent almost entirely on the per-tap strided
18852/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
18853/// arithmetic). Nothing here is spec logic: the same masks, the same
18854/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
18855/// rounding, done for 16 edge lines at once.
18856///
18857/// 16-bit lanes are exact for every value these filters see. Samples are in
18858/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
18859/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
18860/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
18861/// wide kernels' weights each total 8 or 16, so their sums (at most
18862/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
18863/// rounding shift, which is the unsigned shift the scalar's non-negative sum
18864/// takes.
18865#[cfg(target_arch = "x86_64")]
18866#[allow(unsafe_code)]
18867#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
18868mod deblock_simd {
18869 use std::arch::x86_64::*;
18870
18871 /// `a <= b` lane-wise, as a full-width mask.
18872 ///
18873 /// # Safety
18874 /// Requires AVX2.
18875 #[target_feature(enable = "avx2")]
18876 #[inline]
18877 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
18878 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
18879 }
18880
18881 /// `|a - b|` lane-wise.
18882 ///
18883 /// # Safety
18884 /// Requires AVX2.
18885 #[target_feature(enable = "avx2")]
18886 #[inline]
18887 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
18888 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
18889 }
18890
18891 /// `signed_char_clamp_high`, lane-wise.
18892 ///
18893 /// # Safety
18894 /// Requires AVX2.
18895 #[target_feature(enable = "avx2")]
18896 #[inline]
18897 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
18898 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
18899 }
18900
18901 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
18902 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
18903 ///
18904 /// # Safety
18905 /// Requires AVX2.
18906 #[target_feature(enable = "avx2")]
18907 unsafe fn transpose16(t: &mut [__m256i; 16]) {
18908 let mut a = [_mm256_setzero_si256(); 16];
18909 for k in 0..8 {
18910 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
18911 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
18912 }
18913 let mut b = [_mm256_setzero_si256(); 16];
18914 for g in 0..4 {
18915 let s = 4 * g;
18916 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
18917 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
18918 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
18919 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
18920 }
18921 let mut c = [_mm256_setzero_si256(); 16];
18922 for g in 0..2 {
18923 let s = 8 * g;
18924 for j in 0..4 {
18925 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
18926 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
18927 }
18928 }
18929 for i in 0..8 {
18930 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
18931 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
18932 }
18933 }
18934
18935 /// The wide kernels' tap weights, in tap order and with the spec's
18936 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
18937 /// over `p3..q3`, `filter14` over `p6..q6`.
18938 const W6: [[i16; 6]; 4] = [
18939 [3, 2, 2, 1, 0, 0],
18940 [1, 2, 2, 2, 1, 0],
18941 [0, 1, 2, 2, 2, 1],
18942 [0, 0, 1, 2, 2, 3],
18943 ];
18944 const W8: [[i16; 8]; 6] = [
18945 [3, 2, 1, 1, 1, 0, 0, 0],
18946 [2, 1, 2, 1, 1, 1, 0, 0],
18947 [1, 1, 1, 2, 1, 1, 1, 0],
18948 [0, 1, 1, 1, 2, 1, 1, 1],
18949 [0, 0, 1, 1, 1, 2, 1, 2],
18950 [0, 0, 0, 1, 1, 1, 2, 3],
18951 ];
18952 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
18953 const W14: [[i16; 14]; 12] = [
18954 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
18955 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
18956 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
18957 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
18958 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
18959 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
18960 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
18961 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
18962 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
18963 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
18964 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
18965 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
18966 ];
18967
18968 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
18969 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
18970 /// below `1 << 16`, so the logical shift is the arithmetic one.
18971 ///
18972 /// # Safety
18973 /// Requires AVX2.
18974 ///
18975 /// lane-deblock: the tap count, the weights and the shift are all const
18976 /// here (they were slice parameters, which left the weight `match` as a
18977 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
18978 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
18979 #[target_feature(enable = "avx2")]
18980 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
18981 unsafe fn wsum<const N: usize, const SHIFT: i32>(
18982 taps: &[__m256i; N],
18983 w: &[i16; N],
18984 ) -> __m256i {
18985 let mut s = _mm256_setzero_si256();
18986 for i in 0..N {
18987 match w[i] {
18988 0 => {}
18989 1 => s = _mm256_add_epi16(s, taps[i]),
18990 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
18991 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
18992 }
18993 }
18994 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
18995 if SHIFT == 3 {
18996 _mm256_srli_epi16(s, 3)
18997 } else {
18998 _mm256_srli_epi16(s, 4)
18999 }
19000 }
19001
19002 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
19003 /// `t[8]`; the filtered taps are written back in place. Returns `false`
19004 /// when the filter mask is empty on every one of the 16 lines -- nothing
19005 /// was written and the caller can skip the whole write-back.
19006 ///
19007 /// # Safety
19008 /// Requires AVX2.
19009 ///
19010 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
19011 /// its own kernel holding only its own taps, and every wide row is
19012 /// clamped straight into `t` instead of into a shared twelve-entry
19013 /// result array (which the register allocator spilled -- 35% of this
19014 /// kernel's samples were `vmovdqa` to the stack).
19015 #[target_feature(enable = "avx2")]
19016 #[allow(clippy::too_many_arguments)]
19017 unsafe fn filter16<const LEN: u8>(
19018 t: &mut [__m256i; 16],
19019 blimit: i32,
19020 limit: i32,
19021 hev_thr: i32,
19022 flat_thresh: i32,
19023 scale: i32,
19024 smax: i32,
19025 ) -> bool {
19026 let lim = _mm256_set1_epi16(limit as i16);
19027 let blim = _mm256_set1_epi16(blimit as i16);
19028 let hthr = _mm256_set1_epi16(hev_thr as i16);
19029 let fthr = _mm256_set1_epi16(flat_thresh as i16);
19030 let zero = _mm256_setzero_si256();
19031 let smaxv = _mm256_set1_epi16(smax as i16);
19032 macro_rules! put {
19033 ($i:expr, $v:expr) => {
19034 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
19035 };
19036 }
19037 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
19038 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
19039
19040 // `highbd_filter_mask`: the neighbour steps this kernel's length
19041 // reaches, plus the shared `blimit` term.
19042 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
19043 let mut md = d1;
19044 if LEN >= 6 {
19045 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
19046 }
19047 if LEN >= 8 {
19048 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
19049 }
19050 let bl = _mm256_add_epi16(
19051 _mm256_slli_epi16(ad(p0, q0), 1),
19052 _mm256_srli_epi16(ad(p1, q1), 1),
19053 );
19054 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
19055 // lane-deblock2: an empty mask leaves every tap at its loaded value
19056 // (the flat masks are `& mask`, so they are empty too, and the final
19057 // clamp is the identity on samples that came out of the plane), so
19058 // the whole write-back -- including the vertical edge's second
19059 // transpose -- is dead.
19060 if _mm256_testz_si256(mask, mask) != 0 {
19061 return false;
19062 }
19063 let hev = _mm256_cmpgt_epi16(d1, hthr);
19064
19065 // `filter4`, in the centred domain.
19066 let centre = _mm256_set1_epi16((128 * scale) as i16);
19067 let lo = _mm256_set1_epi16((-128 * scale) as i16);
19068 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
19069 let ps1 = _mm256_sub_epi16(p1, centre);
19070 let ps0 = _mm256_sub_epi16(p0, centre);
19071 let qs0 = _mm256_sub_epi16(q0, centre);
19072 let qs1 = _mm256_sub_epi16(q1, centre);
19073 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
19074 let f = sclamp(
19075 _mm256_add_epi16(
19076 outer,
19077 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
19078 ),
19079 lo,
19080 hi,
19081 );
19082 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
19083 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
19084 let tap = _mm256_andnot_si256(
19085 hev,
19086 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
19087 );
19088 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
19089 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
19090 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
19091 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
19092 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
19093 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
19094 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
19095 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
19096 if LEN == 4 {
19097 put!(6, b_p1);
19098 put!(7, b_p0);
19099 put!(8, b_q0);
19100 put!(9, b_q1);
19101 return true;
19102 }
19103
19104 // `highbd_flat_mask4`, over the same reach as this length's mask.
19105 let mut fl = _mm256_max_epi16(
19106 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
19107 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
19108 );
19109 if LEN >= 8 {
19110 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
19111 }
19112 let flat = _mm256_and_si256(le(fl, fthr), mask);
19113 let any_flat = _mm256_testz_si256(flat, flat) == 0;
19114 if LEN == 6 {
19115 if any_flat {
19116 let taps = [p2, p1, p0, q0, q1, q2];
19117 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
19118 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
19119 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
19120 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
19121 } else {
19122 put!(6, b_p1);
19123 put!(7, b_p0);
19124 put!(8, b_q0);
19125 put!(9, b_q1);
19126 }
19127 return true;
19128 }
19129
19130 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
19131 let (o0, o1, o2, o3, o4, o5) = if any_flat {
19132 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
19133 (
19134 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
19135 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
19136 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
19137 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
19138 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
19139 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
19140 )
19141 } else {
19142 (p2, b_p1, b_p0, b_q0, b_q1, q2)
19143 };
19144 macro_rules! put8 {
19145 () => {
19146 put!(5, o0);
19147 put!(6, o1);
19148 put!(7, o2);
19149 put!(8, o3);
19150 put!(9, o4);
19151 put!(10, o5);
19152 };
19153 }
19154 if LEN == 8 {
19155 put8!();
19156 return true;
19157 }
19158
19159 let fl2 = _mm256_max_epi16(
19160 _mm256_max_epi16(
19161 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
19162 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
19163 ),
19164 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
19165 );
19166 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
19167 if _mm256_testz_si256(flat2, flat2) != 0 {
19168 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
19169 // taps they were loaded with, exactly as the blend would.
19170 put8!();
19171 return true;
19172 }
19173 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
19174 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
19175 // j is a constant vector with two negative and two positive
19176 // entries), so each output costs one add, one sub and the rounding
19177 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
19178 // become 44. Exact: every partial sum is taken mod 2^16 by
19179 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
19180 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
19181 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
19182 // it against `filter_edge` at 8/10/12-bit.
19183 let mut s = _mm256_add_epi16(
19184 _mm256_add_epi16(
19185 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
19186 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
19187 ),
19188 _mm256_add_epi16(
19189 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
19190 q0,
19191 ),
19192 );
19193 let add2 = |a, b| _mm256_add_epi16(a, b);
19194 macro_rules! row14 {
19195 ($idx:literal, $base:expr) => {
19196 put!(
19197 $idx,
19198 _mm256_blendv_epi8(
19199 $base,
19200 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
19201 flat2,
19202 )
19203 );
19204 };
19205 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
19206 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
19207 row14!($idx, $base);
19208 };
19209 }
19210 row14!(2, p5);
19211 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
19212 row14!(4, p3, add2(p2, q2), add2(p6, p5));
19213 row14!(5, o0, add2(p1, q3), add2(p6, p4));
19214 row14!(6, o1, add2(p0, q4), add2(p6, p3));
19215 row14!(7, o2, add2(q0, q5), add2(p6, p2));
19216 row14!(8, o3, add2(q1, q6), add2(p6, p1));
19217 row14!(9, o4, add2(q2, q6), add2(p5, p0));
19218 row14!(10, o5, add2(q3, q6), add2(p4, q0));
19219 row14!(11, q3, add2(q4, q6), add2(p3, q1));
19220 row14!(12, q4, add2(q5, q6), add2(p2, q2));
19221 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
19222 true
19223 }
19224
19225 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
19226 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
19227 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
19228 /// consecutive columns with each tap a whole row segment.
19229 ///
19230 /// # Safety
19231 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
19232 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
19233 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
19234 /// must be inside it.
19235 #[target_feature(enable = "avx2")]
19236 #[allow(clippy::too_many_arguments)]
19237 pub unsafe fn edge16(
19238 data: &mut [u16],
19239 base: usize,
19240 stride: usize,
19241 vertical: bool,
19242 len: u8,
19243 blimit: i32,
19244 limit: i32,
19245 hev_thr: i32,
19246 flat_thresh: i32,
19247 scale: i32,
19248 smax: i32,
19249 ) {
19250 let p = data.as_mut_ptr();
19251 let mut t = [_mm256_setzero_si256(); 16];
19252 // The taps this length reads, as `t` indices.
19253 let (lo, hi) = match len {
19254 4 => (6, 10),
19255 6 => (5, 11),
19256 8 => (4, 12),
19257 _ => (1, 15),
19258 };
19259 if vertical {
19260 for j in 0..16 {
19261 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
19262 }
19263 transpose16(&mut t);
19264 } else {
19265 let top = base - 8 * stride;
19266 for i in lo..hi {
19267 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
19268 }
19269 }
19270 // lane-deblock2: one monomorphised kernel per edge length, and an
19271 // empty filter mask returns without any write-back at all.
19272 let modified = match len {
19273 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19274 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19275 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19276 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19277 };
19278 if !modified {
19279 return;
19280 }
19281 if vertical {
19282 transpose16(&mut t);
19283 for j in 0..16 {
19284 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
19285 }
19286 } else {
19287 let top = base - 8 * stride;
19288 let (a, b) = match len {
19289 4 | 6 => (6, 10),
19290 8 => (5, 11),
19291 _ => (2, 14),
19292 };
19293 for i in a..b {
19294 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
19295 }
19296 }
19297 }
19298}
19299
19300/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
19301/// output. Returns `false` when this build or CPU has no kernel, leaving the
19302/// caller on the scalar path.
19303#[allow(unused_variables)]
19304fn filter_edge16(
19305 data: &mut [u16],
19306 base: usize,
19307 stride: usize,
19308 vertical: bool,
19309 len: u8,
19310 level: i32,
19311 sharpness: u8, fctx: &crate::decode::FrameCtx,
19312) -> bool {
19313 #[cfg(target_arch = "x86_64")]
19314 {
19315 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
19316 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19317 let shift = bit_depth(fctx) - 8;
19318 // SAFETY: the avx2 arm is reached only when the CPU reports it,
19319 // and `deblock_plane` checks the kernel's edge bounds.
19320 #[allow(unsafe_code)]
19321 unsafe {
19322 deblock_simd::edge16(
19323 data,
19324 base,
19325 stride,
19326 vertical,
19327 len,
19328 blimit << shift,
19329 limit << shift,
19330 hev_thr << shift,
19331 1 << shift,
19332 1 << shift,
19333 sample_max(fctx),
19334 )
19335 };
19336 return true;
19337 }
19338 }
19339 false
19340}
19341
19342/// One plane's worth of spec 7.14: every vertical edge across the plane,
19343/// then every horizontal edge (the order the spec and libaom both use).
19344fn deblock_plane(
19345 plane: &mut PlaneBuf<'static>,
19346 plane_idx: usize,
19347 lf: &LoopFilterParams,
19348 n: &Neighbours,
19349 frame_width: usize,
19350 frame_height: usize, fctx: &crate::decode::FrameCtx,
19351) {
19352 // spec 7.14's order: this plane's whole vertical pass, then its whole
19353 // horizontal one. lane-pipefilt split the two into one row-ranged
19354 // function so the per-superblock-row pipeline can run them a band at a
19355 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
19356 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
19357 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
19358}
19359
19360/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
19361/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
19362///
19363/// A row span is a legal cut of either pass because a band boundary is a
19364/// multiple of 16 rows and every edge's kernel stays inside its own
19365/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
19366/// what keep the two passes in spec order across bands.
19367#[allow(clippy::too_many_arguments)]
19368fn deblock_plane_span(
19369 plane: &mut PlaneBuf<'static>,
19370 plane_idx: usize,
19371 lf: &LoopFilterParams,
19372 n: &Neighbours,
19373 frame_width: usize,
19374 frame_height: usize,
19375 span_lo: usize,
19376 span_hi: usize,
19377 horz: bool,
19378 fctx: &crate::decode::FrameCtx,
19379) {
19380 let chroma = plane_idx != 0;
19381 // r7: libaom clips the deblock loop to the CODED frame's own
19382 // width/height, not the mi-aligned `true_width`/`true_height` margin
19383 // (the padding up to the next 8-pixel/superblock boundary that
19384 // reconstruction still fills in but the loop filter never visits).
19385 // Confirmed against the superres gate: with the margin included, the
19386 // last coded mi column's horizontal edges were filtered when libaom's
19387 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
19388 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
19389 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
19390 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
19391 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
19392 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
19393 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
19394 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
19395 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
19396 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
19397 // all in columns 64..67; frame 0 survived because that edge carried no
19398 // filter level there). r7's superres measurement is preserved: its frame
19399 // was already 8-aligned, so this bound equals `frame_width` there and
19400 // still excludes the superblock padding up to `true_width`.
19401 let (cw, ch) = if chroma {
19402 (frame_width.div_ceil(2), frame_height.div_ceil(2))
19403 } else {
19404 (frame_width, frame_height)
19405 };
19406 let (tw, th, stride) = (
19407 plane.true_width.min(cw),
19408 plane.true_height.min(ch),
19409 plane.width,
19410 );
19411 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
19412 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
19413 }
19414 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
19415 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
19416 // kernel. The swap is order-preserving: a filtered group overlaps only
19417 // groups along the edge it sits on -- the vertical pass's writes at
19418 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
19419 // dependence is on ascending `x0` within a row, which stays the outer
19420 // loop's order, and rows remain independent (horizontal pass mirrored).
19421 let rows = plane.data.len() / stride.max(1);
19422 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
19423 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
19424 // bands along the axis whose writes are disjoint. A vertical edge's
19425 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
19426 // row bands never touch each other; a horizontal edge's groups write rows
19427 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
19428 // read the mode-info grids immutably. The grouping a band starts with is
19429 // free: every 4-row (4-column) group's output is a pure function of that
19430 // group, whether it goes through `filter_edge16` with three neighbours or
19431 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
19432 // group ever straddles one.
19433 // lane-perf10 merge: the output plane is owned (perf10 made mutable
19434 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
19435 // the bands below never clone it concurrently.
19436 plane.data.to_mut();
19437 let threads = crate::par::filter_threads();
19438 let sp = crate::par::Shared::new(plane);
19439 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
19440 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
19441 Vec::new()
19442 } else {
19443 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
19444 .into_iter()
19445 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
19446 .collect()
19447 };
19448 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
19449 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
19450 // no other band touches (see `Shared`'s own corner-cut note).
19451 #[allow(unsafe_code)]
19452 let plane = unsafe { sp.get() };
19453 // lane-deblock2: this band's own level table and pass constants,
19454 // built once per band instead of re-derived per 4-pixel edge.
19455 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
19456 let mut x0 = 4usize;
19457 while x0 < tw {
19458 let mut y0 = y_lo;
19459 while y0 < y_hi {
19460 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
19461 let ps: [Option<(u8, i32)>; 4] =
19462 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
19463 if let Some((len, level)) = ps[0] {
19464 if ps.iter().all(|p| *p == ps[0])
19465 && filter_edge16(
19466 plane.data.to_mut(),
19467 y0 * stride + x0,
19468 stride,
19469 true,
19470 len,
19471 level,
19472 lf.sharpness, fctx,
19473 )
19474 {
19475 y0 += 16;
19476 continue;
19477 }
19478 }
19479 for (k, p) in ps.iter().enumerate() {
19480 if let Some((len, level)) = *p {
19481 filter_edge(
19482 plane.data.to_mut(),
19483 (y0 + 4 * k) * stride + x0,
19484 stride as isize,
19485 1,
19486 len,
19487 level,
19488 lf.sharpness, fctx,
19489 );
19490 }
19491 }
19492 y0 += 16;
19493 continue;
19494 }
19495 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
19496 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
19497 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
19498 }
19499 filter_edge(
19500 plane.data.to_mut(),
19501 y0 * stride + x0,
19502 stride as isize,
19503 1,
19504 len,
19505 level,
19506 lf.sharpness, fctx,
19507 );
19508 }
19509 y0 += 4;
19510 }
19511 x0 += 4;
19512 }
19513 });
19514 // The horizontal pass runs only after the WHOLE vertical pass of this
19515 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
19516 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
19517 Vec::new()
19518 } else {
19519 crate::par::bands(tw.div_ceil(16), threads)
19520 .into_iter()
19521 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19522 .collect()
19523 };
19524 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
19525 // SAFETY: this band writes only columns `x_lo..x_hi`.
19526 #[allow(unsafe_code)]
19527 let plane = unsafe { sp.get() };
19528 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
19529 let mut y0 = sp_lo.max(4);
19530 while y0 < sp_hi {
19531 let mut x0 = x_lo;
19532 while x0 < x_hi {
19533 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
19534 let ps: [Option<(u8, i32)>; 4] =
19535 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
19536 if let Some((len, level)) = ps[0] {
19537 if ps.iter().all(|p| *p == ps[0])
19538 && filter_edge16(
19539 plane.data.to_mut(),
19540 y0 * stride + x0,
19541 stride,
19542 false,
19543 len,
19544 level,
19545 lf.sharpness, fctx,
19546 )
19547 {
19548 x0 += 16;
19549 continue;
19550 }
19551 }
19552 for (k, p) in ps.iter().enumerate() {
19553 if let Some((len, level)) = *p {
19554 filter_edge(
19555 plane.data.to_mut(),
19556 y0 * stride + x0 + 4 * k,
19557 1,
19558 stride as isize,
19559 len,
19560 level,
19561 lf.sharpness, fctx,
19562 );
19563 }
19564 }
19565 x0 += 16;
19566 continue;
19567 }
19568 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
19569 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
19570 && plane_idx == 0
19571 && x0 == 44
19572 {
19573 eprintln!(
19574 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
19575 lf.sharpness
19576 );
19577 }
19578 filter_edge(
19579 plane.data.to_mut(),
19580 y0 * stride + x0,
19581 1,
19582 stride as isize,
19583 len,
19584 level,
19585 lf.sharpness, fctx,
19586 );
19587 }
19588 x0 += 4;
19589 }
19590 y0 += 4;
19591 } });
19592}
19593
19594/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
19595/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
19596/// restoration is active, and a fresh LR destination per plane -- freshly
19597/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
19598/// sample written also takes a first-touch page fault. The buffers are handed
19599/// back here instead and refilled in place.
19600///
19601/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
19602/// stay on one thread: the frame thread allocates the snapshots and a filter
19603/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
19604/// into the pool from whichever worker ran it), so a per-thread pool leaked
19605/// whole-plane buffers into every worker it touched -- 19 MB a set, times
19606/// every pool thread the decode ever created. One shared pool with a hard
19607/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
19608/// many threads cycle through it; anything over the cap is freed.
19609static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
19610
19611/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
19612/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
19613/// flight cycle through far fewer.
19614const SCRATCH_CAP: usize = 32;
19615
19616/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
19617/// CAPACITY so a chroma-sized request does not permanently promote a
19618/// luma-sized allocation (every pooled buffer would drift to the largest
19619/// size otherwise). `None` when the pool is empty.
19620fn scratch_take(n: usize) -> Option<Vec<u16>> {
19621 let mut p = PLANE_SCRATCH.lock().unwrap();
19622 if p.is_empty() {
19623 return None;
19624 }
19625 let fit = p
19626 .iter()
19627 .enumerate()
19628 .filter(|(_, v)| v.capacity() >= n)
19629 .min_by_key(|(_, v)| v.capacity())
19630 .map(|(i, _)| i);
19631 let i = match fit {
19632 Some(i) => i,
19633 // Nothing big enough: grow the largest rather than a small one.
19634 None => p
19635 .iter()
19636 .enumerate()
19637 .max_by_key(|(_, v)| v.capacity())
19638 .map(|(i, _)| i)
19639 .expect("the pool is not empty"),
19640 };
19641 Some(p.swap_remove(i))
19642}
19643
19644/// A pooled buffer holding a copy of `src`.
19645fn scratch_from(src: &[u16]) -> Vec<u16> {
19646 let mut v = scratch_take(src.len()).unwrap_or_default();
19647 v.clear();
19648 v.extend_from_slice(src);
19649 v
19650}
19651
19652/// An empty pooled buffer, for a caller that fills it itself.
19653fn scratch_empty() -> Vec<u16> {
19654 let mut v = scratch_take(0).unwrap_or_default();
19655 v.clear();
19656 v
19657}
19658
19659/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
19660/// for a caller that writes every element it later reads (lane-copy: the
19661/// post-deblock snapshot writes 4 rows in 64 and reads no other).
19662fn scratch_sized(n: usize) -> Vec<u16> {
19663 let mut v = scratch_take(n).unwrap_or_default();
19664 if v.len() > n {
19665 v.truncate(n);
19666 } else if v.len() < n {
19667 v.resize(n, 0);
19668 }
19669 v
19670}
19671
19672/// A plane's post-deblock snapshot, its samples taken from the pool (every
19673/// other field is `usize`).
19674///
19675/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
19676/// boundary substitution reads the post-deblock plane at just four rows
19677/// around each interior stripe boundary (`row` outside
19678/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
19679/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
19680/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
19681/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
19682/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
19683/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
19684/// the pooled buffer keeps whatever a previous frame left there -- an
19685/// initialised value that no reader ever reaches.
19686fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
19687 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
19688}
19689
19690fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
19691 let mut data = scratch_sized(p.data.len());
19692 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
19693 let stripe_h = 64usize >> ss_y;
19694 let offset = 8usize >> ss_y;
19695 let mut b = stripe_h - offset;
19696 while b < rows {
19697 let (lo, hi) = (b - 2, (b + 2).min(rows));
19698 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
19699 b += stripe_h;
19700 }
19701 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
19702}
19703
19704/// The pre-filter reconstruction of one coded frame, plus the per-block state
19705/// the loop filters read.
19706///
19707/// The encoder's filter search ([`crate::filter_search::pick_filters`])
19708/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
19709/// sets to score each one, and the entropy decode and reconstruction it
19710/// repeats are identical every time -- both filters run after it, on the
19711/// finished planes. That re-parse was 24% of the encoder's profile. A caller
19712/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
19713/// alone through [`replay_filters`]; the result is the same picture the full
19714/// decode would have returned, because it is the same two calls on a copy of
19715/// the same planes.
19716pub(crate) struct FilterReplay {
19717 y: PlaneBuf<'static>,
19718 u: PlaneBuf<'static>,
19719 v: PlaneBuf<'static>,
19720 neighbours: Neighbours,
19721 frame_width: usize,
19722 frame_height: usize,
19723 width: usize,
19724 height: usize,
19725 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
19726 /// stash the cropped return path leaves behind.
19727 true_width: usize,
19728 true_height: usize,
19729 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
19730 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
19731 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
19732 /// 1080p frame's wall in allocation, not in filtering. Recycled here
19733 /// instead; the pool holds at most the six planes one candidate has live.
19734 scratch: Vec<Vec<u16>>,
19735 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
19736 /// post-deblock rows loop restoration substitutes at its stripe
19737 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
19738 /// rows) -- what [`replay_restoration`] filters, instead of decoding
19739 /// the re-coded tile a second time.
19740 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
19741 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
19742 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
19743 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
19744 /// no deblocking level, so every candidate of it used to copy the three
19745 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
19746 /// destinations are kept and only the units the last candidate touched
19747 /// are restored -- the same bytes, since a unit nobody wrote still holds
19748 /// the deblocked sample it was copied from.
19749 work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19750 wrote: Vec<u8>,
19751 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
19752 /// new candidate can only write MORE units than the old one needs no
19753 /// restore at all, since every unit CDEF writes it writes from the
19754 /// post-deblock source alone.
19755 work_cdef: Option<CdefParams>,
19756 /// The last deblocked planes and the levels that produced them.
19757 /// Deblocking depends on nothing else the search moves, and the search
19758 /// fixes the levels before it walks the CDEF strengths, so every
19759 /// candidate after the first of a level pair replays CDEF alone.
19760 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19761}
19762
19763thread_local! {
19764 /// Set by [`arm_filter_replay`] for the span of one decode.
19765 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
19766 /// What that decode captured, until [`clear_filter_replay`].
19767 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
19768 const { std::cell::RefCell::new(None) };
19769}
19770
19771/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
19772pub(crate) fn arm_filter_replay() {
19773 REPLAY_ARMED.set(true);
19774}
19775
19776/// Test-only: force every filter candidate through a full decode, so a gate
19777/// can hold the replay against the decode it stands in for
19778/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
19779#[cfg(test)]
19780static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
19781
19782#[cfg(test)]
19783pub(crate) fn set_filter_replay_disabled(off: bool) {
19784 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
19785}
19786
19787// Test-only: run the capture decode `replay_final` replaced as well, and
19788// hold its picture and its `FilterStages` against the replay's
19789// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
19790// Thread-local, not a global: the filter stage runs on the frame thread the
19791// test itself drives, and a process-wide flag would put every test encoding
19792// in parallel with this one through the extra decode too.
19793#[cfg(test)]
19794thread_local! {
19795 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
19796}
19797
19798#[cfg(test)]
19799pub(crate) fn set_verify_final_replay(on: bool) {
19800 VERIFY_FINAL.set(on);
19801}
19802
19803#[cfg(test)]
19804pub(crate) fn verify_final_replay() -> bool {
19805 VERIFY_FINAL.get()
19806}
19807
19808/// Drop the armed flag and anything captured: the tile it belongs to is done.
19809pub(crate) fn clear_filter_replay() {
19810 REPLAY_ARMED.set(false);
19811 REPLAY.with_borrow_mut(|r| *r = None);
19812}
19813
19814/// The capture itself, called from the decoder's own pre-filter point. Owns
19815/// copies of the planes, since the caller filters them in place.
19816fn capture_filter_replay(
19817 y: &PlaneBuf<'_>,
19818 u: &PlaneBuf<'_>,
19819 v: &PlaneBuf<'_>,
19820 neighbours: &Neighbours,
19821 frame_width: usize,
19822 frame_height: usize,
19823 width: usize,
19824 height: usize,
19825 true_width: usize,
19826 true_height: usize,
19827) {
19828 if !REPLAY_ARMED.replace(false) {
19829 return;
19830 }
19831 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
19832 REPLAY.with_borrow_mut(|slot| {
19833 *slot = Some(FilterReplay {
19834 y: own(y),
19835 u: own(u),
19836 v: own(v),
19837 neighbours: neighbours.clone(),
19838 frame_width,
19839 frame_height,
19840 width,
19841 height,
19842 true_width,
19843 true_height,
19844 scratch: Vec::new(),
19845 work: None,
19846 wrote: Vec::new(),
19847 work_cdef: None,
19848 final_luma: None,
19849 deblocked: None,
19850 });
19851 });
19852}
19853
19854/// Restores, from the post-deblock cache, every sample the previous CDEF
19855/// candidate may have written: for each unit row, the column span between
19856/// its first and last written unit (a superset of the written units, which
19857/// is what makes the copy contiguous -- and never more than the whole-plane
19858/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
19859/// 4 for 4:2:0 chroma.
19860fn restore_written(
19861 dst: &mut PlaneBuf<'static>,
19862 src: &PlaneBuf<'_>,
19863 wrote: &[u8],
19864 mask: u8,
19865 unit_cols: usize,
19866 unit: usize,
19867) {
19868 let w = dst.width;
19869 if w == 0 || unit_cols == 0 || wrote.is_empty() {
19870 return;
19871 }
19872 let rows = dst.data.len() / w;
19873 let s: &[u16] = &src.data;
19874 let d = dst.data.to_mut();
19875 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
19876 for (i, row) in wr.chunks(unit_cols).enumerate() {
19877 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
19878 continue;
19879 };
19880 let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
19881 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
19882 let ur = ur0 + i;
19883 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
19884 for r in y0..y1 {
19885 let off = (r - ur0 * unit) * w;
19886 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
19887 }
19888 }
19889 };
19890 let urows = wrote.len() / unit_cols;
19891 let threads = crate::par::filter_threads().min(urows.max(1));
19892 if threads <= 1 {
19893 band(d, wrote, 0);
19894 return;
19895 }
19896 let per = urows.div_ceil(threads);
19897 let batch = crate::par::Batch::new("ec-av1-filter");
19898 for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
19899 {
19900 let band = &band;
19901 batch.submit(move || band(dc, wr, i * per));
19902 }
19903}
19904
19905/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
19906/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
19907/// allocator and the page fault handler out of the filter search.
19908fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
19909 let mut buf = scratch.pop().unwrap_or_default();
19910 let src: &[u16] = &p.data;
19911 let threads = crate::par::filter_threads();
19912 if buf.len() != src.len() || threads <= 1 {
19913 buf.clear();
19914 buf.extend_from_slice(src);
19915 } else {
19916 // A recycled buffer is already the right length, so the copy is a
19917 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
19918 // candidate is memory bandwidth, not arithmetic, and the halves are
19919 // disjoint `&mut` slices (no `par::Shared` needed).
19920 let per = src.len().div_ceil(threads);
19921 let batch = crate::par::Batch::new("ec-av1-filter");
19922 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
19923 batch.submit(move || dst.copy_from_slice(src));
19924 }
19925 }
19926 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
19927}
19928
19929/// The filter half of a captured decode, under new parameters: exactly the
19930/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
19931/// copy of the captured planes. `None` when nothing is captured (the caller
19932/// then decodes for real).
19933pub(crate) fn replay_filters(
19934 loop_filter: &LoopFilterParams,
19935 cdef: &CdefParams,
19936 fctx: &FrameCtx,
19937) -> Option<Picture> {
19938 #[cfg(test)]
19939 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19940 return None;
19941 }
19942 replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture)
19943}
19944
19945/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters,
19946/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage
19947/// used to reach this picture by decoding that re-coded tile a second time
19948/// (10% of a 4K frame's encode), only because the loop-restoration search
19949/// needs the decoder's own post-CDEF plane
19950/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls
19951/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter
19952/// planes in the same order, so it is the same bytes -- pinned by
19953/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which
19954/// runs the decode as well and holds picture and stages against it.
19955///
19956/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that
19957/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF
19958/// snapshot and handed the post-CDEF plane over for both stages.
19959pub(crate) fn replay_final(
19960 loop_filter: &LoopFilterParams,
19961 cdef: &CdefParams,
19962 idx_grid: &[u8],
19963 want_stages: bool,
19964 fctx: &FrameCtx,
19965) -> Option<(Picture, Option<FilterStages>)> {
19966 #[cfg(test)]
19967 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19968 return None;
19969 }
19970 replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx)
19971}
19972
19973fn replay_inner(
19974 loop_filter: &LoopFilterParams,
19975 cdef: &CdefParams,
19976 // `Some((cdef_idx grid, capture the filter stages))` for the final
19977 // replay; `None` for a scoring candidate, which always codes `bits == 0`.
19978 final_pass: Option<(&[u8], bool)>,
19979 fctx: &FrameCtx,
19980) -> Option<(Picture, Option<FilterStages>)> {
19981 REPLAY.with_borrow_mut(|slot| {
19982 let r = slot.as_mut()?;
19983 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
19984 // Set when the working planes ARE the deblocked planes (see below):
19985 // they go into the cache at the end, and the picture is cropped out
19986 // of them rather than taking their buffers.
19987 let mut share = false;
19988 let cpt = crate::par::timer(crate::par::S_COPY);
19989 let unit_cols = r.neighbours.mi_cols.div_ceil(2);
19990 let unit_rows = r.neighbours.mi_rows.div_ceil(2);
19991 let (mut y, mut u, mut v) = if hit {
19992 let work = r.work.take();
19993 let wrote = std::mem::take(&mut r.wrote);
19994 // `cdef_adjust_strength` is monotone in the strength it is given,
19995 // so a candidate whose primary strength is no lower and whose
19996 // secondary is zero only if the last one's was writes every unit
19997 // the last one wrote -- and writes it from the same post-deblock
19998 // source, so the samples under it need not be put back first.
19999 // Only while both candidates carry ONE strength pair (`bits ==
20000 // 0`, every scoring candidate) and read the same `cdef_idx` grid.
20001 let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
20002 let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
20003 (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
20004 superset(
20005 (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
20006 (old.y_pri_strength[0], old.y_sec_strength[0]),
20007 ),
20008 superset(
20009 (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
20010 (old.uv_pri_strength[0], old.uv_sec_strength[0]),
20011 ),
20012 ),
20013 _ => (false, false),
20014 };
20015 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
20016 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
20017 match work {
20018 Some((mut wy, mut wu, mut wv)) => {
20019 if !skip_y {
20020 restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
20021 }
20022 if !skip_uv {
20023 restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
20024 restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
20025 }
20026 (wy, wu, wv)
20027 }
20028 None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
20029 }
20030 } else {
20031 // The levels moved, so the cached deblocked planes are dead:
20032 // their buffers are this candidate's working copies.
20033 for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
20034 r.scratch.push(plane.data.into_owned());
20035 }
20036 r.work_cdef = None;
20037 if let Some((_, dy, du, dv)) = r.deblocked.take() {
20038 r.scratch.push(dy.data.into_owned());
20039 r.scratch.push(du.data.into_owned());
20040 r.scratch.push(dv.data.into_owned());
20041 }
20042 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
20043 let (mut y, mut u, mut v) =
20044 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
20045 let _t = crate::par::timer(crate::par::S_DEBLOCK);
20046 apply_deblock(
20047 &mut y,
20048 &mut u,
20049 &mut v,
20050 loop_filter,
20051 &r.neighbours,
20052 r.frame_width,
20053 r.frame_height,
20054 fctx,
20055 );
20056 // lane-av1cap2: an all-zero-strength CDEF writes no sample at
20057 // all ([`cdef_all_zero`]'s own early return), so THESE planes
20058 // are already this candidate's output -- they become the
20059 // deblock cache at the end instead of being copied into it
20060 // here, which is three ~6 MB copies less per candidate that
20061 // moves the levels (the whole deblocking half of the search:
20062 // its CDEF strengths are still (0,0)).
20063 share = cdef_all_zero(cdef);
20064 if !share {
20065 let scratch = &mut r.scratch;
20066 r.deblocked = Some((
20067 *loop_filter,
20068 pooled(&y, scratch),
20069 pooled(&u, scratch),
20070 pooled(&v, scratch),
20071 ));
20072 }
20073 (y, u, v)
20074 };
20075 drop(cpt);
20076 // The winner's `cdef_idx` literals live in the re-coded tile, which
20077 // nothing parses on this path -- hand the grid the encoder already
20078 // chose straight to the filter (`bits == 0` leaves the grid the last
20079 // parse sized, which is what every scoring candidate reads).
20080 if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) {
20081 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
20082 }
20083 let ct = crate::par::timer(crate::par::S_CDEF);
20084 let mut wrote = std::mem::take(&mut r.wrote);
20085 wrote.clear();
20086 wrote.resize(unit_cols * unit_rows, 0);
20087 r.work_cdef = Some(*cdef);
20088 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
20089 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
20090 });
20091 apply_cdef(
20092 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
20093 pre,
20094 Some(&mut wrote),
20095 );
20096 drop(ct);
20097 if final_pass.is_some_and(|(_, want)| want) {
20098 // The loop-restoration search runs on the stages above (where
20099 // post-CDEF stands in for post-deblock, as the capture decode
20100 // had it); the FILTER this frame ends up applying reads the
20101 // real post-deblock rows, which is what the decoder does.
20102 let snapshot = if share {
20103 // Nothing filtered these planes after the deblock, so they
20104 // are the post-deblock picture themselves.
20105 Some(plane_snapshot(&y, 0))
20106 } else {
20107 r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0))
20108 };
20109 let scratch = &mut r.scratch;
20110 r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d));
20111 }
20112 let stages = final_pass.and_then(|(_, want)| {
20113 want.then(|| FilterStages {
20114 deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20115 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20116 stride: [y.width, u.width, v.width],
20117 })
20118 });
20119 // The capture only happens on the shape whose tail is the two
20120 // filter calls and the crop (no superres, no loop restoration), so
20121 // what is left is that crop -- byte for byte the cropped return path
20122 // of the decode this replaces, wide-margin stash included.
20123 //
20124 // lane-av1fpar: the crop is why this arm exists at all. The capture
20125 // used to demand `frame == plane` dimensions, which no editor size
20126 // meets (1080 and 1608 both pad to a superblock row), so every
20127 // candidate of every frame at those sizes fell through to a full
20128 // re-decode -- 57% of a 1080p frame's wall.
20129 let (fw, fh) = (r.frame_width, r.frame_height);
20130 if fw == r.width && fh == r.height {
20131 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20132 r.wrote = Vec::new();
20133 r.work_cdef = None;
20134 if share {
20135 let picture = Picture {
20136 width: r.width,
20137 height: r.height,
20138 y: y.data.to_vec(),
20139 u: u.data.to_vec(),
20140 v: v.data.to_vec(),
20141 };
20142 r.deblocked = Some((*loop_filter, y, u, v));
20143 return Some((picture, stages));
20144 }
20145 return Some((
20146 Picture {
20147 width: r.width,
20148 height: r.height,
20149 y: y.data.into_owned(),
20150 u: u.data.into_owned(),
20151 v: v.data.into_owned(),
20152 },
20153 stages,
20154 ));
20155 }
20156 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
20157 let mut out = Vec::with_capacity(w * h);
20158 for row in 0..h {
20159 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20160 }
20161 out
20162 };
20163 let (tw, th) = (r.true_width, r.true_height);
20164 fctx.last_frame_wide_margin.with(|m| {
20165 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
20166 width: tw,
20167 height: th,
20168 y: crop(&y, tw, th),
20169 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
20170 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
20171 });
20172 });
20173 let out = Picture {
20174 width: fw,
20175 height: fh,
20176 y: crop(&y, fw, fh),
20177 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20178 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20179 };
20180 // The working planes outlive the crop: either they ARE the
20181 // deblocked planes this candidate's successors reuse, or they go
20182 // back to the pool.
20183 if share {
20184 r.wrote = Vec::new();
20185 r.work_cdef = None;
20186 r.deblocked = Some((*loop_filter, y, u, v));
20187 } else {
20188 // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20189 // next candidate, together with the map of what CDEF wrote.
20190 r.wrote = wrote;
20191 r.work = Some((y, u, v));
20192 }
20193 Some((out, stages))
20194 })
20195}
20196
20197/// lane-av1cap2: the loop-restoration half of the final replay. Once the
20198/// units are chosen the tile is coded a second time to carry them, and that
20199/// re-coded tile used to be DECODED to reach the restored reference frame
20200/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that
20201/// tile but the per-unit filters the encoder just picked: it is the
20202/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on
20203/// the post-CDEF plane the final replay produced, with the TRUE
20204/// post-deblock stripe-border rows -- the same call the decoder's
20205/// `apply_loop_restoration` makes, on the same input. Only luma moves: the
20206/// encoder never writes a chroma restoration type other than
20207/// `RESTORE_NONE`, whose kernel hands its input straight back.
20208///
20209/// Returns the cropped luma plane and refreshes the wide-margin stash's own
20210/// luma (restoration writes strictly inside `frame_width x frame_height`,
20211/// so the margin columns past it stand). `None` when nothing was captured
20212/// -- the caller then decodes for real.
20213pub(crate) fn replay_restoration(
20214 lr: &LoopRestorationParams,
20215 units: &[Option<crate::restoration::WienerInfo>],
20216 fctx: &FrameCtx,
20217) -> Option<Vec<u16>> {
20218 #[cfg(test)]
20219 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20220 return None;
20221 }
20222 REPLAY.with_borrow_mut(|slot| {
20223 let r = slot.as_mut()?;
20224 let (cdefed, deblocked) = r.final_luma.as_ref()?;
20225 let (fw, fh) = (r.frame_width, r.frame_height);
20226 let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
20227 let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]);
20228 if horz == 0 || units.len() != horz * vert {
20229 return None;
20230 }
20231 for (i, filter) in units.iter().enumerate() {
20232 if let Some(info) = filter {
20233 grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info));
20234 }
20235 }
20236 let stride = cdefed.width;
20237 let mut out = scratch_empty();
20238 crate::restoration::apply_loop_restoration_plane(
20239 &cdefed.data,
20240 &deblocked.data,
20241 stride,
20242 fw,
20243 fh,
20244 0,
20245 lr.frame_restoration_type[0],
20246 lr.loop_restoration_size[0],
20247 &grid,
20248 0,
20249 &mut out,
20250 None,
20251 fctx,
20252 );
20253 fctx.last_frame_wide_margin.with(|m| {
20254 if let Some(p) = m.borrow_mut().as_mut() {
20255 let tw = p.width;
20256 for row in 0..p.height.min(fh) {
20257 let n = tw.min(fw);
20258 p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]);
20259 }
20260 }
20261 });
20262 let mut y = Vec::with_capacity(fw * fh);
20263 for row in 0..fh {
20264 y.extend(out[row * stride..][..fw].iter().copied());
20265 }
20266 scratch_return(out);
20267 Some(y)
20268 })
20269}
20270
20271/// The output crop, taking the plane by value: a frame whose width is
20272/// already superblock-aligned (only its height is padded) has a padded
20273/// buffer whose stride equals the visible width, so the crop is a pure
20274/// truncation of the buffer we already own -- no full-plane copy at all
20275/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
20276/// serial tail). Any other shape falls back to the row-by-row copy.
20277fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
20278 let stride = plane.width;
20279 let mut data = plane.data.into_owned();
20280 if stride == w {
20281 data.truncate(w * h);
20282 return data;
20283 }
20284 let mut out = Vec::with_capacity(w * h);
20285 for row in 0..h {
20286 out.extend(data[row * stride..][..w].iter().copied());
20287 }
20288 out
20289}
20290
20291/// Hands a buffer back to the pool; the capacity is what is worth keeping.
20292/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
20293/// what keeps a pool shared by every thread from being an unbounded stash.
20294fn scratch_return(v: Vec<u16>) {
20295 let mut p = PLANE_SCRATCH.lock().unwrap();
20296 if p.len() < SCRATCH_CAP {
20297 p.push(v);
20298 }
20299}
20300
20301/// One CDEF mi-row band, as a real function rather than the body of the
20302/// `run_bands` closure: inside the closure the destination planes are
20303/// `&mut` references derived from a `par::Shared` raw pointer in the same
20304/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
20305/// re-loads through them on every tap. Reference parameters restore `noalias`
20306/// (lane-perf11 (a): -x% instructions at one filter thread).
20307#[allow(clippy::too_many_arguments)]
20308fn cdef_band(
20309 r_lo: usize,
20310 r_hi: usize,
20311 y: &mut PlaneBuf<'static>,
20312 u: &mut PlaneBuf<'static>,
20313 v: &mut PlaneBuf<'static>,
20314 src_y: &[u16],
20315 src_u: &[u16],
20316 src_v: &[u16],
20317 cdef: &CdefParams,
20318 skip_grid: &Neighbours,
20319 idx_grid: &[u8],
20320 sb_cols: usize,
20321 coeff_shift: i32,
20322 damping: i32,
20323 damping_uv: i32,
20324 (frame_w, frame_h): (usize, usize),
20325 fctx: &crate::decode::FrameCtx,
20326 // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
20327 // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
20328 // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
20329 // `cdef_adjust_strength` zeroes a unit's primary strength off its own
20330 // variance, so which units a candidate writes is not a function of its
20331 // strengths alone -- the encoder's filter replay reuses one destination
20332 // plane across candidates and needs the map to restore it.
20333 mut wrote: Option<&mut [u8]>,
20334) {
20335 let unit_cols = skip_grid.mi_cols.div_ceil(2);
20336 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
20337 if sb_cols == 0 {
20338 return 0;
20339 }
20340 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
20341 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
20342 };
20343 // One scratch window per plane kind, reused by every unit (8x8 luma and
20344 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
20345 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
20346 // AVX2 kernel taps the window in place with two-row loads that reach
20347 // past the last sample, and the tail stays zero for every unit.
20348 let mut win_y = [0i16; 256];
20349 let mut win_uv = [0i16; 256];
20350 let mut mi_r = r_lo;
20351 while mi_r < r_hi {
20352 let mut mi_c = 0usize;
20353 while mi_c < skip_grid.mi_cols {
20354 if skip_grid.is_skip_txfm(mi_r, mi_c) {
20355 hit!(CDEF_SKIPPED_UNITS);
20356 }
20357 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
20358 let sidx = strength_idx(mi_r, mi_c);
20359 let (ox, oy) = (mi_c * 4, mi_r * 4);
20360 // Nothing to do for this unit at all: the direction search is
20361 // only ever consumed through a strength, so a unit whose four
20362 // strengths are zero never needs its 8x8 window gathered.
20363 if cdef.y_pri_strength[sidx] == 0
20364 && cdef.y_sec_strength[sidx] == 0
20365 && cdef.uv_pri_strength[sidx] == 0
20366 && cdef.uv_sec_strength[sidx] == 0
20367 {
20368 mi_c += 2;
20369 continue;
20370 }
20371 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
20372 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
20373 // lane-cdef r1: the direction search reads the SAME padded
20374 // block the taps do -- libaom runs `cdef_find_dir` on the
20375 // prepared filter block (`cdef_block.c:296-320` over
20376 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
20377 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
20378 // Clamping to the last real sample instead made every straddling
20379 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
20380 // a different `adjust_strength`, hence a +-1 band at the crop edge.
20381 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
20382
20383 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
20384 // -- each plane zeroes the shared direction when *its own*
20385 // frame-level primary strength is 0, independent of the
20386 // per-block adjusted `t` and of the other plane's strength.
20387 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
20388 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
20389 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
20390 let t = cdef_adjust_strength(y_pri_strength, var);
20391 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
20392 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
20393 eprintln!(
20394 "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}"
20395 );
20396 }
20397 let enable_primary = t != 0;
20398 let enable_secondary = y_sec_strength != 0;
20399 if (ox + 8 > frame_w || oy + 8 > frame_h)
20400 && (enable_primary
20401 || enable_secondary
20402 || cdef.uv_pri_strength[sidx] != 0
20403 || cdef.uv_sec_strength[sidx] != 0)
20404 {
20405 hit!(CDEF_STRADDLE_UNITS);
20406 }
20407 if enable_primary || enable_secondary {
20408 cdef_filter_block(
20409 &win_y,
20410 y,
20411 ox,
20412 oy,
20413 8,
20414 8,
20415 t,
20416 y_sec_strength,
20417 y_dir,
20418 damping,
20419 damping,
20420 enable_primary,
20421 enable_secondary,
20422 coeff_shift, fctx,
20423 );
20424 }
20425
20426 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
20427 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
20428 let uv_dir = if t_uv != 0 { dir } else { 0 };
20429 let enable_primary_uv = t_uv != 0;
20430 let enable_secondary_uv = uv_sec_strength != 0;
20431 if let Some(w) = wrote.as_deref_mut() {
20432 let mark = u8::from(enable_primary || enable_secondary)
20433 | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
20434 w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
20435 }
20436 if enable_primary_uv || enable_secondary_uv {
20437 let (cox, coy) = (ox / 2, oy / 2);
20438 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
20439 let (tw, th) = (plane.true_width, plane.true_height);
20440 let stride = plane.width;
20441 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
20442 cdef_filter_block(
20443 &win_uv,
20444 plane,
20445 cox,
20446 coy,
20447 4,
20448 4,
20449 t_uv,
20450 uv_sec_strength,
20451 uv_dir,
20452 damping_uv,
20453 damping_uv,
20454 enable_primary_uv,
20455 enable_secondary_uv,
20456 coeff_shift, fctx,
20457 );
20458 }
20459 }
20460 }
20461 mi_c += 2;
20462 }
20463 mi_r += 2;
20464 }
20465}
20466
20467
20468// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
20469//
20470// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
20471// every plane's vertical deblock edges, then every plane's horizontal ones,
20472// then CDEF, then -- unpipelined -- superres and loop restoration).
20473// A band is 64 luma rows, one superblock row (a 128 superblock is two).
20474//
20475// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
20476// band r, so no filter may touch band r before band r+1 is reconstructed.
20477// Hence V(r) waits for `ready >= r + 2`.
20478// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
20479// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
20480// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
20481// side of the band boundary, so H(r-1)'s last edge reaches into band r,
20482// which the whole-frame order has already vertical-filtered -- V(r)
20483// before H(r-1) reproduces exactly that.
20484// * post-deblock finality: band j's own bottom rows are still rewritten by
20485// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
20486// only be taken after H(j+1).
20487// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
20488// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
20489//
20490// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
20491// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
20492// superres upscale, which is a whole-frame refusal for this path) stay in the
20493// frame thread's tail; the snapshot the pipeline built is what LR reads.
20494struct PipeQ {
20495 /// Bands whose reconstruction the frame thread has released.
20496 ready: usize,
20497 abort: bool,
20498}
20499
20500pub(crate) struct PipeSync {
20501 m: std::sync::Mutex<PipeQ>,
20502 cv: std::sync::Condvar,
20503}
20504
20505impl PipeSync {
20506 fn new() -> Self {
20507 Self {
20508 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
20509 cv: std::sync::Condvar::new(),
20510 }
20511 }
20512 fn note(&self, ready: usize) {
20513 let mut q = self.m.lock().unwrap();
20514 if ready > q.ready {
20515 q.ready = ready;
20516 self.cv.notify_all();
20517 }
20518 }
20519 /// Releases every remaining band (`abort` = the tile decoder is bailing
20520 /// out, so the worker returns instead of finishing the frame).
20521 fn close(&self, all: usize, abort: bool) {
20522 let mut q = self.m.lock().unwrap();
20523 q.ready = q.ready.max(all);
20524 q.abort |= abort;
20525 self.cv.notify_all();
20526 }
20527 /// `false` when the frame was aborted.
20528 fn wait_for(&self, want: usize) -> bool {
20529 let mut q = self.m.lock().unwrap();
20530 while q.ready < want && !q.abort {
20531 q = self.cv.wait(q).unwrap();
20532 }
20533 !q.abort
20534 }
20535}
20536
20537/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
20538/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
20539/// otherwise only the four rows around each stripe boundary that loop
20540/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
20541fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
20542 let w = src.width;
20543 if w == 0 {
20544 return;
20545 }
20546 let rows = src.data.len() / w;
20547 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
20548 if lo >= hi {
20549 return;
20550 }
20551 if full {
20552 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
20553 return;
20554 }
20555 let stripe_h = 64usize >> ss_y;
20556 let offset = 8usize >> ss_y;
20557 let mut b = stripe_h - offset;
20558 while b < rows {
20559 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
20560 if a < e {
20561 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
20562 }
20563 b += stripe_h;
20564 }
20565}
20566
20567/// Everything the pipeline worker needs that is not a plane or a grid.
20568struct PipeCfg<'a> {
20569 lf: &'a LoopFilterParams,
20570 cdef: &'a CdefParams,
20571 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
20572 /// entries of the superblock rows the pipeline has not reached; the Vec
20573 /// itself is sized once per frame, so the pointer stays valid.
20574 idx_grid: (*const u8, usize),
20575 sb_cols: usize,
20576 frame_w: usize,
20577 frame_h: usize,
20578 nbands: usize,
20579 cdef_on: bool,
20580 snap_on: bool,
20581}
20582
20583// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
20584// per frame and only ever written at indices the pipeline is three bands
20585// behind (see this module's dependency note).
20586#[allow(unsafe_code)]
20587unsafe impl Send for PipeCfg<'_> {}
20588
20589#[allow(unsafe_code)]
20590#[allow(clippy::too_many_arguments)]
20591fn pipe_run(
20592 sync: &PipeSync,
20593 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20594 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20595 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20596 sn: crate::par::Shared<'_, Neighbours>,
20597 cfg: PipeCfg<'_>,
20598 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20599 lr_sync: Option<&PipeSync>,
20600 fctx: &crate::decode::FrameCtx,
20601) {
20602 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
20603 // is at least two behind, and the two ranges never meet -- see the
20604 // dependency note above and `Shared`'s own corner-cut.
20605 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20606 let n: &Neighbours = unsafe { sn.get() };
20607 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
20608 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
20609 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
20610 let damping_uv = (damping - 1).max(0);
20611 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20612 let nb = cfg.nbands;
20613 for k in 0..nb + 3 {
20614 if !sync.wait_for((k + 2).min(nb)) {
20615 if let Some(ls) = lr_sync {
20616 ls.close(nb, true);
20617 }
20618 return;
20619 }
20620 if k < nb {
20621 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
20622 }
20623 if k >= 1 && k - 1 < nb {
20624 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
20625 }
20626 if cfg.snap_on && k >= 2 && k - 2 < nb {
20627 let j = k - 2;
20628 if let Some((sy2, su2, sv2)) = snap.as_mut() {
20629 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
20630 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20631 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20632 }
20633 }
20634 if cfg.cdef_on && k >= 3 && k - 3 < nb {
20635 let j = k - 3;
20636 if let Some((sy2, su2, sv2)) = snap.as_ref() {
20637 cdef_rows(
20638 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
20639 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
20640 None,
20641 );
20642 }
20643 }
20644 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
20645 // them to the loop restoration worker.
20646 if let Some(ls) = lr_sync {
20647 ls.note(k.saturating_sub(2));
20648 }
20649 }
20650 if let Some(ls) = lr_sync {
20651 ls.close(nb, false);
20652 }
20653}
20654
20655/// The pipeline's loop restoration worker, a second task alongside
20656/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
20657/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
20658/// post-deblock snapshot at most two rows past `v_end` (see
20659/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
20660/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
20661/// iteration `band + 3` and the snapshot band one iteration earlier, so the
20662/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
20663/// indices being at most one band apart. Running it as its own worker (not
20664/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
20665/// critical path: serialised into that loop it measured ~1% slower than the
20666/// whole-frame form, which at least ran its RU rows across the filter pool.
20667#[allow(unsafe_code)]
20668fn pipe_run_lr(
20669 sync: &PipeSync,
20670 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20671 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20672 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20673 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
20674 cfg: LrCfg<'_>,
20675 fctx: &crate::decode::FrameCtx,
20676) {
20677 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
20678 // and writes its own `out` buffers; the final swap happens after the
20679 // last CDEF band, which is `pipe_run`'s last plane write.
20680 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20681 let snap = unsafe { snap.get() };
20682 let grid = unsafe { &*cfg.lr_grid };
20683 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20684 let dims = [
20685 (fw, fh, 0u32, y.width, y.data.len()),
20686 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
20687 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
20688 ];
20689 let mut planes: Vec<LrPlane> = Vec::new();
20690 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
20691 let rows = crate::restoration::lr_unit_rows(
20692 ph,
20693 cfg.lr.loop_restoration_size[p],
20694 ss,
20695 cfg.lr.frame_restoration_type[p],
20696 );
20697 if rows.is_empty() {
20698 continue;
20699 }
20700 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
20701 }
20702 for band in 0..cfg.nbands {
20703 if !sync.wait_for(band + 1) {
20704 return;
20705 }
20706 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
20707 for lp in &mut planes {
20708 let stripe = 64usize >> lp.ss;
20709 let r_lo = lp.next;
20710 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
20711 lp.next += 1;
20712 }
20713 if lp.next == r_lo {
20714 continue;
20715 }
20716 let (src, deb) = match lp.p {
20717 0 => (&y.data, &sy2.data),
20718 1 => (&u.data, &su2.data),
20719 _ => (&v.data, &sv2.data),
20720 };
20721 crate::restoration::apply_loop_restoration_plane(
20722 src,
20723 deb,
20724 lp.stride,
20725 lp.pw,
20726 lp.ph,
20727 lp.ss,
20728 cfg.lr.frame_restoration_type[lp.p],
20729 cfg.lr.loop_restoration_size[lp.p],
20730 grid,
20731 lp.p,
20732 &mut lp.out,
20733 Some((r_lo, lp.next)),
20734 fctx,
20735 );
20736 }
20737 }
20738 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
20739 // untouched by restoration and copied here, then the restored plane
20740 // takes the picture's place (the whole-frame path's own final swap).
20741 for mut lp in planes {
20742 let buf: &mut PlaneBuf<'static> = match lp.p {
20743 0 => &mut *y,
20744 1 => &mut *u,
20745 _ => &mut *v,
20746 };
20747 let tail = lp.ph * lp.stride;
20748 if tail < buf.data.len() {
20749 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
20750 }
20751 scratch_return(
20752 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
20753 );
20754 }
20755}
20756
20757/// Everything [`pipe_run_lr`] needs beyond the planes.
20758struct LrCfg<'a> {
20759 lr: &'a LoopRestorationParams,
20760 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
20761 /// many bands ahead of every unit this worker reads.
20762 lr_grid: *const crate::restoration::RestorationGrid,
20763 frame_w: usize,
20764 frame_h: usize,
20765 nbands: usize,
20766}
20767
20768// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
20769#[allow(unsafe_code)]
20770unsafe impl Send for LrCfg<'_> {}
20771
20772/// One plane's pipelined loop restoration state (see [`pipe_run`]).
20773struct LrPlane {
20774 p: usize,
20775 /// The restored plane, built band by band and swapped in at the end.
20776 out: Vec<u16>,
20777 rows: Vec<(u32, u32)>,
20778 /// The first RU row not yet restored.
20779 next: usize,
20780 pw: usize,
20781 ph: usize,
20782 ss: u32,
20783 stride: usize,
20784}
20785
20786/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
20787/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
20788/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
20789/// pointers into the frame's planes, so it may not outlive them).
20790struct PipeGuard<'a> {
20791 sync: std::sync::Arc<PipeSync>,
20792 batch: Option<crate::par::Batch<'a>>,
20793 nbands: usize,
20794 /// The loop restoration worker's own gate, aborted with the first one.
20795 lr_sync: Option<std::sync::Arc<PipeSync>>,
20796}
20797
20798impl PipeGuard<'_> {
20799 fn note(&self, bands: usize) {
20800 self.sync.note(bands);
20801 }
20802 fn finish(&mut self) {
20803 self.sync.close(self.nbands, false);
20804 // Dropping the batch waits the worker out.
20805 self.batch.take();
20806 }
20807}
20808
20809impl Drop for PipeGuard<'_> {
20810 fn drop(&mut self) {
20811 self.sync.close(self.nbands, true);
20812 if let Some(ls) = &self.lr_sync {
20813 ls.close(self.nbands, true);
20814 }
20815 }
20816}
20817
20818/// Leading superblock rows of the live tile's wavefront that are fully
20819/// reconstructed: parsed out to the last column and with every job that
20820/// carried a write finished. 0 when reconstruction is inline (no wavefront),
20821/// where the caller uses the parse position instead.
20822fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
20823 let st = fctx.wave.with(|w| w.borrow().clone());
20824 let Some(st) = st else { return 0 };
20825 let q = st.q.lock().unwrap();
20826 let mut n = 0;
20827 while n < q.rows.len() {
20828 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
20829 break;
20830 }
20831 n += 1;
20832 }
20833 n
20834}
20835
20836/// Frames whose loop filters ran pipelined, and frames that took the
20837/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
20838static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
20839static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
20840
20841/// Whether this frame's filters may run per superblock row. Everything that
20842/// reads the picture out of band order, or the pipeline's own inputs out of
20843/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
20844/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
20845/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
20846/// frame row is only complete after the last tile column's own parse), and
20847/// every pixel-dump / stage-skip debug flag, whose whole point is the
20848/// unpipelined stage boundary. The pipeline also stays off unless some
20849/// threading is on -- at (1, 1) the filters would run on a worker thread for
20850/// nothing and the crate's `thread_local!` gate counters would miss them.
20851fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
20852 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
20853 return false;
20854 }
20855 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
20856 return false;
20857 }
20858 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
20859 return false;
20860 }
20861 if fctx.seg.with(|s| s.borrow().enabled) {
20862 return false;
20863 }
20864 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
20865 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
20866 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
20867 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
20868 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
20869 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
20870 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
20871 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
20872 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
20873 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
20874 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
20875 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
20876}
20877
20878/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
20879/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
20880/// never enters `apply_cdef`, so it calls this itself).
20881fn cdef_scan_counters(skip_grid: &Neighbours) {
20882 let _ = skip_grid;
20883 hit_do! {
20884 let mut r = 0usize;
20885 while r < skip_grid.mi_rows {
20886 let mut c = 0usize;
20887 while c < skip_grid.mi_cols {
20888 if (0..2).any(|rr| {
20889 (0..2).any(|cc| {
20890 !skip_grid
20891 .blk_grid
20892 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
20893 .map_or(true, |x| x.written)
20894 })
20895 }) {
20896 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
20897 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
20898 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
20899 }
20900 }
20901 let cell = |rr: usize, cc: usize| {
20902 skip_grid
20903 .blk_grid
20904 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
20905 .is_some_and(|x| x.skip)
20906 };
20907 let first = cell(0, 0);
20908 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
20909 hit!(CDEF_MIXED_SKIP_UNITS);
20910 }
20911 c += 2;
20912 }
20913 r += 2;
20914 }
20915 }
20916}
20917
20918/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
20919/// means "no filtering at all" whenever the single (index 0) strength pair
20920/// is all-zero, the fast path every existing gate stream takes.
20921fn cdef_all_zero(cdef: &CdefParams) -> bool {
20922 cdef.bits == 0
20923 && cdef.y_pri_strength[0] == 0
20924 && cdef.y_sec_strength[0] == 0
20925 && cdef.uv_pri_strength[0] == 0
20926 && cdef.uv_sec_strength[0] == 0
20927}
20928
20929/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
20930/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
20931/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
20932/// row range's own pixels.
20933#[allow(clippy::too_many_arguments)]
20934fn cdef_rows(
20935 y: &mut PlaneBuf<'static>,
20936 u: &mut PlaneBuf<'static>,
20937 v: &mut PlaneBuf<'static>,
20938 src_y: &[u16],
20939 src_u: &[u16],
20940 src_v: &[u16],
20941 cdef: &CdefParams,
20942 skip_grid: &Neighbours,
20943 idx_grid: &[u8],
20944 sb_cols: usize,
20945 coeff_shift: i32,
20946 damping: i32,
20947 damping_uv: i32,
20948 (frame_w, frame_h): (usize, usize),
20949 r_lo0: usize,
20950 r_hi0: usize, fctx: &crate::decode::FrameCtx,
20951 // See [`cdef_band`]. Shared because the bands below write disjoint unit
20952 // ROWS of it, exactly as they write disjoint plane rows.
20953 wrote: Option<crate::par::Shared<'_, [u8]>>,
20954) {
20955 let mi_rows = skip_grid.mi_rows;
20956 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
20957 if lo >= hi {
20958 return;
20959 }
20960 let (sy, su, sv) = (
20961 crate::par::Shared::new(y),
20962 crate::par::Shared::new(u),
20963 crate::par::Shared::new(v),
20964 );
20965 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
20966 .into_iter()
20967 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
20968 .collect();
20969 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
20970 // SAFETY: this band writes only the plane rows its own mi rows cover,
20971 // disjoint from every other band's (see `Shared`).
20972 #[allow(unsafe_code)]
20973 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20974 // SAFETY: this band marks only the unit rows its own mi rows cover,
20975 // disjoint from every other band's (see `Shared`).
20976 #[allow(unsafe_code)]
20977 let wr = wrote.as_ref().map(|w| unsafe { w.get() });
20978 cdef_band(
20979 r_lo,
20980 r_hi,
20981 y,
20982 u,
20983 v,
20984 src_y,
20985 src_u,
20986 src_v,
20987 cdef,
20988 skip_grid,
20989 idx_grid,
20990 sb_cols,
20991 coeff_shift,
20992 damping,
20993 damping_uv,
20994 (frame_w, frame_h),
20995 fctx,
20996 wr,
20997 );
20998 });
20999}
21000
21001fn apply_cdef(
21002 y: &mut PlaneBuf<'static>,
21003 u: &mut PlaneBuf<'static>,
21004 v: &mut PlaneBuf<'static>,
21005 cdef: &CdefParams,
21006 skip_grid: &Neighbours,
21007 // This frame header's own CROPPED luma size, for the straddling-unit
21008 // counter only -- CDEF itself walks the mi-rounded plane.
21009 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21010 // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter
21011 // starts by copying all three (~19 MB at 4K). The encoder's filter
21012 // replay already holds an untouched copy of exactly those planes -- its
21013 // post-deblock cache, which is where the working planes were copied FROM
21014 // -- so it hands them straight in and the copy does not happen. `None`
21015 // (every decode) copies as before.
21016 src: Option<(&[u16], &[u16], &[u16])>,
21017 // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
21018 // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
21019 // before the call.
21020 mut wrote: Option<&mut [u8]>,
21021) {
21022 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
21023 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
21024 return;
21025 }
21026 cdef_scan_counters(skip_grid);
21027 // `cdef.bits == 0` still means "no filtering at all" whenever the single
21028 // (index 0) strength pair is all-zero -- the fast path every existing
21029 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
21030 // at every index, but that is rare enough not to special-case; the
21031 // per-superblock lookup below degrades to the same index-0 read anyway
21032 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
21033 if cdef_all_zero(cdef) {
21034 return;
21035 }
21036 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
21037 // One entry per superblock (a few hundred at 4K), so this clone is not
21038 // one of the per-frame copies lane-perf6 pooled below.
21039 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
21040 let owned = src.is_none();
21041 let (src_y, src_u, src_v) = match src {
21042 Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)),
21043 None => (
21044 std::borrow::Cow::Owned(scratch_from(&y.data)),
21045 std::borrow::Cow::Owned(scratch_from(&u.data)),
21046 std::borrow::Cow::Owned(scratch_from(&v.data)),
21047 ),
21048 };
21049 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
21050 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
21051 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21052 let damping = i32::from(cdef.damping) + coeff_shift;
21053 let damping_uv = (damping - 1).max(0);
21054 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
21055 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
21056 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
21057 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
21058 // disjoint row range of all three planes.
21059 cdef_rows(
21060 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
21061 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21062 wrote.as_deref_mut().map(crate::par::Shared::new),
21063 );
21064 if owned {
21065 scratch_return(src_y.into_owned());
21066 scratch_return(src_u.into_owned());
21067 scratch_return(src_v.into_owned());
21068 }
21069}
21070
21071/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
21072/// restoration on both tile paths: hands the encoder's restoration search the
21073/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
21074/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
21075/// a capture is worth three plane copies and nothing else -- and when the
21076/// capture flag is off (every decode but that search) it is worth a bool.
21077fn capture_stages(
21078 y: &PlaneBuf<'_>,
21079 u: &PlaneBuf<'_>,
21080 v: &PlaneBuf<'_>,
21081 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21082 fctx: &FrameCtx,
21083) {
21084 if !fctx.capture_stages.get() {
21085 return;
21086 }
21087 // Without an active restoration type the decoder took no pre-CDEF
21088 // snapshot; the post-CDEF plane then stands in for it, which is exact
21089 // everywhere but LR's own 3-row stripe borders (the encoder's search
21090 // always asks with a type set, so this is the defensive arm).
21091 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
21092 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
21093 None => p.data.to_vec(),
21094 };
21095 *fctx.stages.borrow_mut() = Some(FilterStages {
21096 deblocked: [db(0, y), db(1, u), db(2, v)],
21097 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
21098 stride: [y.width, u.width, v.width],
21099 });
21100}
21101
21102/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
21103/// ordering note: libaom also runs `superres_post_decode` between the two,
21104/// but this decoder never implements super-resolution, so there is nothing
21105/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
21106/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
21107/// restoration's stripe-boundary rows read from it instead of the
21108/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
21109#[allow(clippy::too_many_arguments)]
21110fn apply_loop_restoration(
21111 y: &mut PlaneBuf<'static>,
21112 u: &mut PlaneBuf<'static>,
21113 v: &mut PlaneBuf<'static>,
21114 deblocked_y: &PlaneBuf<'_>,
21115 deblocked_u: &PlaneBuf<'_>,
21116 deblocked_v: &PlaneBuf<'_>,
21117 lr: &LoopRestorationParams,
21118 grid: &crate::restoration::RestorationGrid,
21119 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
21120 // restoration is the ONE post-decode filter that does NOT run over the
21121 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
21122 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
21123 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
21124 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
21125 // -- and asserts it equals the buffer's CROP width
21126 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
21127 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
21128 // that cropped edge before any unit is filtered. Deblock and CDEF DO
21129 // walk the mi grid, which is why passing `true_width`/`true_height`
21130 // here went unnoticed until a frame whose size is not a multiple of 8
21131 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
21132 // read this decoder's own decoded samples at columns 68..71 where
21133 // libaom reads column 67 replicated -- +-1 over the straddling band
21134 // (class av1-truesize-lane: true frame size vs mi-rounded).
21135 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21136) {
21137 let mut out = scratch_empty();
21138 crate::restoration::apply_loop_restoration_plane(
21139 &y.data,
21140 &deblocked_y.data,
21141 y.width,
21142 frame_w,
21143 frame_h,
21144 0,
21145 lr.frame_restoration_type[0],
21146 lr.loop_restoration_size[0],
21147 grid,
21148 0,
21149 &mut out, None, fctx,
21150 );
21151 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
21152 let mut out = scratch_empty();
21153 crate::restoration::apply_loop_restoration_plane(
21154 &u.data,
21155 &deblocked_u.data,
21156 u.width,
21157 frame_w.div_ceil(2),
21158 frame_h.div_ceil(2),
21159 1,
21160 lr.frame_restoration_type[1],
21161 lr.loop_restoration_size[1],
21162 grid,
21163 1,
21164 &mut out, None, fctx,
21165 );
21166 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
21167 let mut out = scratch_empty();
21168 crate::restoration::apply_loop_restoration_plane(
21169 &v.data,
21170 &deblocked_v.data,
21171 v.width,
21172 frame_w.div_ceil(2),
21173 frame_h.div_ceil(2),
21174 1,
21175 lr.frame_restoration_type[2],
21176 lr.loop_restoration_size[2],
21177 grid,
21178 2,
21179 &mut out, None, fctx,
21180 );
21181 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
21182}
21183
21184/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
21185/// returning the picture it reconstructs to.
21186///
21187/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
21188/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
21189/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
21190/// `compute_image_size` derives one from the other, but not losslessly: a
21191/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
21192/// what the reconstruction is cropped to on the way out, mirroring
21193/// [`crate::encode::crop_encoded`].
21194///
21195/// # Errors
21196/// Returns an error when a block's partition, mode, skip flag or transform
21197/// type is anything this decoder does not reconstruct (round 2: inter, tx
21198/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
21199/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
21200/// or when the tile payload runs out of the symbols this decode expects (a
21201/// genuinely foreign stream).
21202#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21203pub(crate) fn decode_key_frame_tile(
21204 data: &[u8],
21205 mi_cols: u32,
21206 mi_rows: u32,
21207 base_q_idx: u8,
21208 frame_width: u32,
21209 frame_height: u32,
21210 enable_filter_intra: bool,
21211 cdef: &CdefParams,
21212 loop_filter: &LoopFilterParams,
21213 tx_select: bool,
21214 reduced_tx_set: bool,
21215 allow_screen_content_tools: bool,
21216 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
21217) -> Result<Picture> {
21218 decode_key_frame_tile_lr(
21219 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
21220 cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
21221 &LoopRestorationParams::default(), fctx,
21222 )
21223}
21224
21225/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
21226/// 5.9.20) instead of the no-restoration default -- the per-unit filters
21227/// themselves live in the tile payload, so the header is all this needs.
21228#[allow(clippy::too_many_arguments)]
21229pub(crate) fn decode_key_frame_tile_lr(
21230 data: &[u8],
21231 mi_cols: u32,
21232 mi_rows: u32,
21233 base_q_idx: u8,
21234 frame_width: u32,
21235 frame_height: u32,
21236 enable_filter_intra: bool,
21237 cdef: &CdefParams,
21238 loop_filter: &LoopFilterParams,
21239 tx_select: bool,
21240 reduced_tx_set: bool,
21241 allow_screen_content_tools: bool,
21242 allow_intrabc: bool,
21243 lr: &LoopRestorationParams,
21244 fctx: &crate::decode::FrameCtx,
21245) -> Result<Picture> {
21246 let single_tile = TileInfo {
21247 mi_col_starts: vec![0, mi_cols],
21248 mi_row_starts: vec![0, mi_rows],
21249 ..TileInfo::default()
21250 };
21251 decode_key_frame_tiles_lr(
21252 &[data],
21253 &single_tile,
21254 mi_cols,
21255 mi_rows,
21256 base_q_idx,
21257 frame_width,
21258 frame_height,
21259 enable_filter_intra,
21260 cdef,
21261 loop_filter,
21262 tx_select,
21263 reduced_tx_set,
21264 allow_screen_content_tools,
21265 allow_intrabc,
21266 lr,
21267 fctx,
21268 )
21269}
21270
21271/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
21272/// encoder's own filter search hands back one payload per tile plus the
21273/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
21274/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
21275#[allow(clippy::too_many_arguments)]
21276pub(crate) fn decode_key_frame_tiles_lr(
21277 tiles: &[&[u8]],
21278 tile_info: &TileInfo,
21279 mi_cols: u32,
21280 mi_rows: u32,
21281 base_q_idx: u8,
21282 frame_width: u32,
21283 frame_height: u32,
21284 enable_filter_intra: bool,
21285 cdef: &CdefParams,
21286 loop_filter: &LoopFilterParams,
21287 tx_select: bool,
21288 reduced_tx_set: bool,
21289 allow_screen_content_tools: bool,
21290 allow_intrabc: bool,
21291 lr: &LoopRestorationParams,
21292 fctx: &crate::decode::FrameCtx,
21293) -> Result<Picture> {
21294 let delta = DeltaParams::default();
21295 decode_key_frame_tile_with_cdfs(
21296 tiles,
21297 tile_info,
21298 mi_cols,
21299 mi_rows,
21300 base_q_idx,
21301 crate::quant::QuantDeltas::default(),
21302 frame_width,
21303 frame_height,
21304 enable_filter_intra,
21305 false,
21306 cdef,
21307 loop_filter,
21308 lr,
21309 None,
21310 tx_select,
21311 reduced_tx_set,
21312 allow_screen_content_tools,
21313 allow_intrabc,
21314 delta, fctx,
21315 )
21316 .map(|(picture, _)| picture)
21317}
21318
21319 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
21320 /// the mi-aligned `true_width`, set by the most recent
21321 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
21322 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
21323 /// their reconstructed buffer down from the same mi-aligned extent, so
21324 /// they share this one slot. See each function's own comment at its
21325 /// write site. `None` when there was no margin to save.
21326
21327/// The margin the most recent key- or inter-frame tile decode stashed
21328/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
21329/// reads this immediately after the call, before any other frame
21330/// decode can overwrite it.
21331#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21332pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
21333 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
21334}
21335
21336/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
21337/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
21338/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
21339/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
21340/// since a key frame's own header always forces `primary_ref_frame ==
21341/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
21342/// alongside the picture, for the caller to save into whichever reference
21343/// slots this frame's `refresh_frame_flags` names.
21344/// The order the 64x64 superblock quadrants of a tile are decoded in.
21345///
21346/// At `sb_size == 64` this is plain raster order over the tile's own
21347/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
21348/// each 128x128 superblock in raster order and visits its four 64x64
21349/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
21350/// 64-level bodies must run in that nested order. `row_start` marks the first
21351/// item of each *superblock* row (where the left neighbour context resets),
21352/// `sb_start` the first item of each superblock (where the 128 root's own
21353/// loop-restoration units and partition symbol are read).
21354fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
21355 let mut out = Vec::new();
21356 if !sb128 {
21357 for r in r0..r1 {
21358 for c in c0..c1 {
21359 out.push((r, c, c == c0, true));
21360 }
21361 }
21362 return out;
21363 }
21364 let mut r = r0;
21365 while r < r1 {
21366 let mut first_in_row = true;
21367 let mut c = c0;
21368 while c < c1 {
21369 let mut first_in_sb = true;
21370 for qr in 0..2 {
21371 for qc in 0..2 {
21372 let (rr, cc) = (r + qr, c + qc);
21373 if rr >= r1 || cc >= c1 {
21374 continue;
21375 }
21376 out.push((rr, cc, first_in_row, first_in_sb));
21377 first_in_row = false;
21378 first_in_sb = false;
21379 }
21380 }
21381 c += 2;
21382 }
21383 r += 2;
21384 }
21385 out
21386}
21387
21388// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
21389// the inter tile loop. Its loop-restoration units are read once for the whole
21390// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
21391// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
21392// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
21393// decoder codes, the other seven arms refuse by name.
21394thread_local! {
21395 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
21396 /// whole 128x128 block (lane-sb128b r1's gate counter).
21397 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21398 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
21399 /// when the bottom half is out of frame) -- lane-sb128c r7.
21400 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21401 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
21402 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21403 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
21404 /// only shape a 1080p (mi_rows = 270) stream reaches.
21405 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21406 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21407 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
21408 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
21409 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
21410}
21411
21412/// [`PART128_AB_HITS`], for a gate's own before/after delta.
21413pub(crate) fn part128_ab_hits() -> [usize; 4] {
21414 PART128_AB_HITS.with(std::cell::Cell::get)
21415}
21416
21417/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
21418#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21419pub(crate) fn part128_none_hits() -> usize {
21420 PART128_NONE_HITS.with(std::cell::Cell::get)
21421}
21422
21423/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
21424#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21425pub(crate) fn part128_horz_hits() -> usize {
21426 PART128_HORZ_HITS.with(std::cell::Cell::get)
21427}
21428
21429/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
21430#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21431pub(crate) fn part128_vert_hits() -> usize {
21432 PART128_VERT_HITS.with(std::cell::Cell::get)
21433}
21434
21435/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
21436pub(crate) fn part128_edge_horz_hits() -> usize {
21437 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
21438}
21439
21440/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
21441pub(crate) fn part128_edge_vert_hits() -> usize {
21442 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
21443}
21444
21445thread_local! {
21446 /// How many CHROMA transform units were coded inside a block whose uv
21447 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
21448 /// block, four per plane).
21449 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21450}
21451
21452/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
21453#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21454pub(crate) fn chroma_split_tx_hits() -> usize {
21455 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
21456}
21457
21458fn read_sb128_root(
21459 dec: &mut SymbolDecoder,
21460 cdfs: &mut Cdfs,
21461 neighbours: &Neighbours,
21462 lr: &LoopRestorationParams,
21463 lr_grid: &mut crate::restoration::RestorationGrid,
21464 lr_reference: &mut [(
21465 crate::restoration::WienerInfo,
21466 crate::restoration::SgrprojInfo,
21467 ); 3],
21468 sb_r: u32,
21469 sb_c: u32,
21470 mi_cols: u32,
21471 mi_rows: u32, fctx: &crate::decode::FrameCtx,
21472) -> Result<usize> {
21473 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
21474 crate::restoration::read_lr(
21475 dec,
21476 cdfs,
21477 lr,
21478 lr_grid,
21479 lr_reference,
21480 mi_r128,
21481 mi_c128,
21482 SB_MI * 2, fctx,
21483 );
21484 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
21485 let ctx128 = neighbours.partition_ctx(at128, 128);
21486 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
21487 let part128 = if has_cols128 && has_rows128 {
21488 hit!(PART128_SYMBOLS);
21489 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
21490 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21491 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
21492 }
21493 p
21494 } else {
21495 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
21496 // partition, they are not a forced split -- exactly the discarded-bit
21497 // defect the 64 root carries a comment about at `partition_w64`'s
21498 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
21499 // VERT (cols out of frame), which the refusal below then names
21500 // instead of silently reconstructing a split.
21501 hit!(PART128_GATHERED_SYMBOLS);
21502 match (has_cols128, has_rows128) {
21503 (true, false) => {
21504 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
21505 PARTITION_SPLIT
21506 } else {
21507 hit!(PART128_EDGE_HORZ_HITS);
21508 PARTITION_HORZ
21509 }
21510 }
21511 (false, true) => {
21512 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
21513 PARTITION_SPLIT
21514 } else {
21515 hit!(PART128_EDGE_VERT_HITS);
21516 PARTITION_VERT
21517 }
21518 }
21519 _ => {
21520 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
21521 bump_edge_both_cut(3);
21522 PARTITION_SPLIT
21523 }
21524 }
21525 };
21526 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
21527 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
21528 // four AB shapes) still need the rect/AB machinery at this size.
21529 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
21530 // both tile paths. The four AB shapes (libaom `decode_partition`'s
21531 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
21532 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
21533 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
21534 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
21535 // which stops at VERT_B).
21536 match part128 {
21537 PARTITION_SPLIT => hit!(PART128_SPLIT_HITS),
21538 PARTITION_NONE => hit!(PART128_NONE_HITS),
21539 PARTITION_HORZ => hit!(PART128_HORZ_HITS),
21540 PARTITION_VERT => hit!(PART128_VERT_HITS),
21541 // lane-sb128c r9: the four AB shapes at the 128 root -- one
21542 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
21543 // paths below in libaom `decode_partition`'s own visit order.
21544 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
21545 hit_do! {
21546 PART128_AB_HITS.with(|c| {
21547 let mut h = c.get();
21548 h[p - PARTITION_HORZ_A] += 1;
21549 c.set(h);
21550 });
21551 }
21552 }
21553 _ => {
21554 return Err(unsupported(
21555 "a 128x128 superblock partition value outside the 8-symbol alphabet",
21556 ));
21557 }
21558 }
21559 Ok(part128)
21560}
21561
21562pub(crate) fn decode_key_frame_tile_with_cdfs(
21563 tiles: &[&[u8]],
21564 tile_info: &TileInfo,
21565 mi_cols: u32,
21566 mi_rows: u32,
21567 base_q_idx: u8,
21568 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
21569 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
21570 // tile alongside [`CURRENT_Q_IDX`].
21571 deltas: crate::quant::QuantDeltas,
21572 frame_width: u32,
21573 frame_height: u32,
21574 enable_filter_intra: bool,
21575 enable_edge_filter: bool,
21576 cdef: &CdefParams,
21577 loop_filter: &LoopFilterParams,
21578 lr: &LoopRestorationParams,
21579 initial_cdfs: Option<Cdfs>,
21580 tx_select: bool,
21581 reduced_tx_set: bool,
21582 allow_screen_content_tools: bool,
21583 allow_intrabc: bool,
21584 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
21585 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
21586 // `stream.rs` still refuses a frame with `lf_present` set before this
21587 // function is ever called.
21588 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
21589) -> Result<(Picture, Cdfs)> {
21590 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
21591 // only, so a key frame decoded after an inter frame on this thread would
21592 // otherwise inherit it and read its `tx_depth` context off the inter
21593 // frame's stale `TXFM_CONTEXT` bands.
21594 fctx.tx_select_inter.with(|c| c.set(false));
21595 if mi_cols == 0 || mi_rows == 0 {
21596 return Err(unsupported("a frame with no mode-info grid"));
21597 }
21598 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
21599 let sb128 = sb128(fctx);
21600 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
21601 fctx.intrabc_mi_grid.with(|g| {
21602 *g.borrow_mut() = allow_intrabc.then(|| {
21603 (
21604 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
21605 mi_cols as usize,
21606 mi_rows as usize,
21607 )
21608 });
21609 });
21610 fctx.intrabc_dv.with(|c| c.set(None));
21611 fctx.cdef_bits.with(|c| c.set(cdef.bits));
21612 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
21613 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
21614 fctx.delta_q_present.with(|c| c.set(delta.q_present));
21615 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
21616 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
21617 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
21618 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
21619 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
21620 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
21621 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
21622
21623 let mut y = PlaneBuf {
21624 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
21625 width,
21626 height,
21627 true_width,
21628 true_height,
21629 tile_x0: 0,
21630 tile_y0: 0,
21631 tile_x1: width,
21632 tile_y1: height,
21633 };
21634 let mut u = PlaneBuf {
21635 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21636 width: width / 2,
21637 height: height / 2,
21638 true_width: true_width / 2,
21639 true_height: true_height / 2,
21640 tile_x0: 0,
21641 tile_y0: 0,
21642 tile_x1: width / 2,
21643 tile_y1: height / 2,
21644 };
21645 let mut v = PlaneBuf {
21646 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21647 width: width / 2,
21648 height: height / 2,
21649 true_width: true_width / 2,
21650 true_height: true_height / 2,
21651 tile_x0: 0,
21652 tile_y0: 0,
21653 tile_x1: width / 2,
21654 tile_y1: height / 2,
21655 };
21656
21657 let scan32 = default_scan(TX32);
21658 let scan16 = default_scan(TX16);
21659 let scan8 = default_scan(TX8);
21660 let scan4 = default_scan(TX4);
21661
21662 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
21663 let mut result_cdfs = base_cdfs.clone();
21664 let mut neighbours = Neighbours::new(
21665 cols32 as usize * 2,
21666 rows32 as usize * 2,
21667 mi_cols as usize,
21668 mi_rows as usize, fctx,
21669 );
21670 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
21671 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
21672 // loop restoration runs after the superres upscale.
21673 let mut lr_grid = crate::restoration::RestorationGrid::new(
21674 lr,
21675 superres(fctx).map_or(frame_width, |(w, _)| w),
21676 frame_height,
21677 );
21678
21679 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
21680 // own byte range and its own fresh copy of the frame's initial CDFs
21681 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
21682 // `context_update_tile_id` has its end-of-tile adapted table kept as the
21683 // frame's own output (spec `exit_symbol`) -- every other tile's
21684 // adaptation is discarded, matching the refusal this replaces.
21685 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
21686 let tile_num = tile_idx as u32;
21687 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
21688 let mi_row0 = tile_info.mi_row_starts[trow as usize];
21689 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
21690 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
21691 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
21692 // Tile boundaries are always superblock-aligned in mi units (spec
21693 // 5.9.15's uniform/non-uniform derivation both only ever emit
21694 // multiples of the superblock's own mi size), so plain division is
21695 // exact here -- no rounding needed.
21696 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
21697 // tile boundary) are always superblock-aligned by spec 5.9.15; the
21698 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
21699 // last entry) is not, so the upper bound needs `div_ceil` the same
21700 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
21701 // trailing partial superblock row/column in scope.
21702 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
21703 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
21704
21705 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
21706 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
21707 // once per frame. Carried across a tile boundary, the loop-restoration
21708 // coefficients of the next tile decode off the previous tile's
21709 // reference -- same symbol count, so entropy and reconstruction stay
21710 // exact and only the filtered pixels of every tile after the first
21711 // are wrong.
21712 let mut lr_reference = [(
21713 crate::restoration::WienerInfo::default(),
21714 crate::restoration::SgrprojInfo::default(),
21715 ); 3];
21716 let mut cdfs = base_cdfs.clone();
21717 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
21718 // `base_q_idx` at the top of every tile, not once per frame.
21719 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
21720 fctx.quant_deltas.with(|c| c.set(deltas));
21721 fctx.current_delta_lf.with(|c| c.set([0; 4]));
21722 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21723 eprintln!(
21724 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
21725 tile_bytes.len(),
21726 &tile_bytes[..tile_bytes.len().min(8)]
21727 );
21728 }
21729 let mut dec = SymbolDecoder::new(tile_bytes);
21730 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
21731 y.set_tile_origin(
21732 mi_col0 as usize * 4,
21733 mi_row0 as usize * 4,
21734 (mi_col1 as usize * 4).min(y.width),
21735 (mi_row1 as usize * 4).min(y.height),
21736 );
21737 u.set_tile_origin(
21738 mi_col0 as usize * 2,
21739 mi_row0 as usize * 2,
21740 (mi_col1 as usize * 2).min(u.width),
21741 (mi_row1 as usize * 2).min(u.height),
21742 );
21743 v.set_tile_origin(
21744 mi_col0 as usize * 2,
21745 mi_row0 as usize * 2,
21746 (mi_col1 as usize * 2).min(v.width),
21747 (mi_row1 as usize * 2).min(v.height),
21748 );
21749 hit!(TILE_HITS);
21750
21751 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
21752 // its one block covers all four 64x64 quadrants, so the remaining three
21753 // visits of this superblock code nothing at all.
21754 let mut sb128_none = false;
21755 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
21756 // are performed at their push sites (nothing reaches the queue below).
21757 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
21758 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
21759 // when `sb128`, since a 128 block writes across its four 64x64 visits).
21760 let wave_shift = u32::from(sb128);
21761 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
21762 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
21763 (
21764 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
21765 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
21766 )
21767 } else {
21768 (0, 0)
21769 };
21770 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
21771 let waving = fctx.wave.with(|w| w.borrow().is_some());
21772 let mut wave_job = (0usize, 0usize);
21773 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
21774 // lane-wave1: the previous superblock's recorded writes -- handed to
21775 // the wavefront workers, or replayed here at one recon thread (where
21776 // the queue is empty, every write having run at its push site).
21777 if waving {
21778 if sb_start {
21779 wave_submit(fctx, wave_job.0, wave_job.1);
21780 wave_job = (
21781 (sb_r >> wave_shift) as usize - wave_r0,
21782 (sb_c >> wave_shift) as usize - wave_c0,
21783 );
21784 }
21785 } else {
21786 flush_recon(fctx, &mut y, &mut u, &mut v);
21787 }
21788 if row_start {
21789 neighbours.start_row();
21790 }
21791 if sb_start {
21792 sb128_none = false;
21793 }
21794 if sb128_none {
21795 continue;
21796 }
21797 {
21798 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
21799 // once for the whole 128x128 (spec 5.11.57 is called with the
21800 // superblock's own size), then one partition symbol off the
21801 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
21802 // recurses into the four 64x64 quadrants this decoder codes.
21803 if sb128 && sb_start {
21804 let part128 = read_sb128_root(
21805 &mut dec,
21806 &mut cdfs,
21807 &neighbours,
21808 lr,
21809 &mut lr_grid,
21810 &mut lr_reference,
21811 sb_r,
21812 sb_c,
21813 mi_cols,
21814 mi_rows, fctx,
21815 )?;
21816 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
21817 // lane-sb128c r9: the four AB shapes at the 128 root.
21818 // libaom `decode_partition` (decodeframe.c) codes each as
21819 // two `bsize2` (64x64) squares plus one `subsize`
21820 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
21821 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
21822 // half; VERT_B = left half, TR, BR. AB values only come
21823 // from the FULL alphabet symbol, which is only read when
21824 // both halves of the root are inside the frame, so no
21825 // piece needs libaom's `i > 0` frame-edge break (a piece
21826 // may still overhang the bottom/right, which
21827 // `PlaneBuf::reconstruct`'s r8 clip handles).
21828 sb128_none = true;
21829 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
21830 let (br, bc) = (at128.0 + 4, at128.1 + 4);
21831 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
21832 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
21833 // BR), so only they switch libaom's `has_tr_vert_*` /
21834 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
21835 let _vert_ab =
21836 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
21837 .then(crate::encode::Reach::vert_ab_partition);
21838 // One `cdef_idx` literal per CODED BLOCK, at the first
21839 // non-skip one of each 64x64 CDEF unit; the 128x64 /
21840 // 64x128 half covers two units and its read lands in the
21841 // unit holding its origin, so that value is copied to the
21842 // other one (libaom: every mi of the block points at the
21843 // same `MB_MODE_INFO`).
21844 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
21845 fctx.cdef_idx_grid.with(|g| {
21846 let mut g = g.borrow_mut();
21847 let cols = fctx.cdef_sb_cols.with(|c| c.get());
21848 if cols == 0 {
21849 return;
21850 }
21851 let (si, di) = (
21852 (q_r + src.0) * cols + q_c + src.1,
21853 (q_r + dst.0) * cols + q_c + dst.1,
21854 );
21855 if q_c + src.1 < cols
21856 && q_c + dst.1 < cols
21857 && si < g.len()
21858 && di < g.len()
21859 {
21860 g[di] = g[si];
21861 }
21862 });
21863 };
21864 macro_rules! square64 {
21865 ($at:expr) => {{
21866 fctx.cdef_transmitted.with(|c| c.set(false));
21867 decode_block(
21868 &mut dec,
21869 &mut cdfs,
21870 &mut neighbours,
21871 $at,
21872 SB,
21873 TxbSet::Luma64,
21874 TxbSet::Chroma32,
21875 TX32,
21876 TX32,
21877 (&scan32, &scan32),
21878 false,
21879 &mut y,
21880 &mut u,
21881 &mut v,
21882 base_q_idx,
21883 enable_filter_intra,
21884 allow_screen_content_tools,
21885 allow_intrabc,
21886 &scan32,
21887 &scan16,
21888 &scan8,
21889 &scan4,
21890 tx_select,
21891 reduced_tx_set, fctx,
21892 )?
21893 }};
21894 }
21895 macro_rules! half128 {
21896 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
21897 fctx.cdef_transmitted.with(|c| c.set(false));
21898 decode_block_128rect(
21899 &mut dec,
21900 &mut cdfs,
21901 &mut neighbours,
21902 $at,
21903 $bw,
21904 $bh,
21905 &mut y,
21906 &mut u,
21907 &mut v,
21908 base_q_idx,
21909 enable_filter_intra,
21910 allow_screen_content_tools,
21911 tx_select,
21912 reduced_tx_set, fctx,
21913 )?;
21914 cdef_copy($src, $dst);
21915 }};
21916 }
21917 match part128 {
21918 PARTITION_HORZ_A => {
21919 square64!(at128);
21920 square64!((at128.0, bc));
21921 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
21922 }
21923 PARTITION_HORZ_B => {
21924 half128!(at128, 128, 64, (0, 0), (0, 1));
21925 square64!((br, at128.1));
21926 square64!((br, bc));
21927 }
21928 PARTITION_VERT_A => {
21929 square64!(at128);
21930 square64!((br, at128.1));
21931 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
21932 }
21933 _ => {
21934 half128!(at128, 64, 128, (0, 0), (1, 0));
21935 square64!((at128.0, bc));
21936 square64!((br, bc));
21937 }
21938 }
21939 continue;
21940 }
21941 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
21942 // lane-sb128c r8: libaom `decode_partition`
21943 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
21944 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
21945 // plus a second one at (mi_row + hbs, mi_col) only
21946 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
21947 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
21948 // = 16 mi. Both halves together cover the whole root, so
21949 // the remaining three 64x64 quadrant visits code nothing
21950 // (same flag the NONE arm sets).
21951 sb128_none = true;
21952 let horz = part128 == PARTITION_HORZ;
21953 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
21954 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
21955 for i in 0..2 {
21956 let at = if horz {
21957 (at128.0 + i * 4, at128.1)
21958 } else {
21959 (at128.0, at128.1 + i * 4)
21960 };
21961 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
21962 if i > 0
21963 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
21964 {
21965 break;
21966 }
21967 // Each half reads its OWN `cdef_idx` literal
21968 // (libaom `read_cdef` keys the `-1` test on the
21969 // block's own `MB_MODE_INFO`, and the two halves have
21970 // different ones).
21971 fctx.cdef_transmitted.with(|c| c.set(false));
21972 decode_block_128rect(
21973 &mut dec,
21974 &mut cdfs,
21975 &mut neighbours,
21976 at,
21977 bw,
21978 bh,
21979 &mut y,
21980 &mut u,
21981 &mut v,
21982 base_q_idx,
21983 enable_filter_intra,
21984 allow_screen_content_tools,
21985 tx_select,
21986 reduced_tx_set, fctx,
21987 )?;
21988 }
21989 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
21990 // unit it covers (the inter path's own fan-out).
21991 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
21992 fctx.cdef_idx_grid.with(|g| {
21993 let mut g = g.borrow_mut();
21994 let cols = fctx.cdef_sb_cols.with(|c| c.get());
21995 if cols == 0 {
21996 return;
21997 }
21998 for (src, dst) in if horz {
21999 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
22000 } else {
22001 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
22002 } {
22003 let (si, di) = (
22004 (q_r + src.0) * cols + q_c + src.1,
22005 (q_r + dst.0) * cols + q_c + dst.1,
22006 );
22007 if q_c + src.1 < cols
22008 && q_c + dst.1 < cols
22009 && si < g.len()
22010 && di < g.len()
22011 {
22012 g[di] = g[si];
22013 }
22014 }
22015 });
22016 continue;
22017 }
22018 if part128 == PARTITION_NONE {
22019 // One 128x128 intra block: four TX_64X64 luma units and a
22020 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
22021 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
22022 // block). No CfL, no filter intra, no palette at this size --
22023 // [`read_intra_mode`]'s own size gates already say so.
22024 sb128_none = true;
22025 fctx.cdef_transmitted.with(|c| c.set(false));
22026 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22027 decode_block(
22028 &mut dec,
22029 &mut cdfs,
22030 &mut neighbours,
22031 at128,
22032 SB * 2,
22033 TxbSet::Luma64,
22034 TxbSet::Chroma32,
22035 TX32,
22036 TX32,
22037 (&scan32, &scan32),
22038 false,
22039 &mut y,
22040 &mut u,
22041 &mut v,
22042 base_q_idx,
22043 enable_filter_intra,
22044 allow_screen_content_tools,
22045 allow_intrabc,
22046 &scan32,
22047 &scan16,
22048 &scan8,
22049 &scan4,
22050 tx_select,
22051 reduced_tx_set, fctx,
22052 )?;
22053 // libaom writes one `cdef_strength` into the block's own
22054 // `MB_MODE_INFO`, which every mi cell of the block --
22055 // hence all four 64x64 CDEF units -- points at; our grid
22056 // is per-unit, so the read (which only ever lands in the
22057 // top-left unit, `read_cdef`'s index 0) is copied across.
22058 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22059 fctx.cdef_idx_grid.with(|g| {
22060 let mut g = g.borrow_mut();
22061 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22062 if cols > 0 && q_r * cols + q_c < g.len() {
22063 let idx = g[q_r * cols + q_c];
22064 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
22065 let i = (q_r + dr) * cols + q_c + dc;
22066 if q_c + dc < cols && i < g.len() {
22067 g[i] = idx;
22068 }
22069 }
22070 }
22071 });
22072 continue;
22073 }
22074 }
22075 if !sb128 {
22076 crate::restoration::read_lr(
22077 &mut dec,
22078 &mut cdfs,
22079 lr,
22080 &mut lr_grid,
22081 &mut lr_reference,
22082 sb_r * SB_MI,
22083 sb_c * SB_MI,
22084 SB_MI, fctx,
22085 );
22086 }
22087 fctx.cdef_transmitted.with(|c| c.set(false));
22088 let at = (sb_r as usize * 4, sb_c as usize * 4);
22089 let ctx = neighbours.partition_ctx(at, SB);
22090 let (has_cols, has_rows) = (
22091 sb_c * SB_MI + SB_MI / 2 < mi_cols,
22092 sb_r * SB_MI + SB_MI / 2 < mi_rows,
22093 );
22094 // Recomputed at this superblock's own half (spec
22095 // `decode_partition`): a full alphabet symbol when both halves are
22096 // inside the true frame, a single gathered bit when just one is
22097 // (the superblock cannot be left whole, so this is forced split),
22098 // and nothing at all (SPLIT inferred, no bits) when neither is —
22099 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
22100 // three-way write exactly.
22101 let part = if has_cols && has_rows {
22102 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
22103 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22104 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
22105 }
22106 p
22107 } else {
22108 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
22109 // the unmerged lane-golomb r1): the gathered bit IS the
22110 // partition -- libaom `ec_read_partition_impl` returns
22111 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
22112 // Forcing SPLIT desynced the last superblock row of every
22113 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
22114 // the first block of that row.
22115 match (has_cols, has_rows) {
22116 (true, false) => {
22117 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22118 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
22119 bump_edge32(4 + b.min(1) as usize);
22120 bump_edge_part(b.min(1) as usize);
22121 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22122 }
22123 (false, true) => {
22124 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22125 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
22126 bump_edge32(4 + b.min(1) as usize);
22127 bump_edge_part(b.min(1) as usize);
22128 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22129 }
22130 _ => {
22131 bump_edge_both_cut(2);
22132 PARTITION_SPLIT
22133 }
22134 }
22135 };
22136 match part {
22137 PARTITION_NONE => {
22138 decode_block(
22139 &mut dec,
22140 &mut cdfs,
22141 &mut neighbours,
22142 at,
22143 SB,
22144 TxbSet::Luma64,
22145 TxbSet::Chroma32,
22146 TX32,
22147 TX32,
22148 (&scan32, &scan32),
22149 false,
22150 &mut y,
22151 &mut u,
22152 &mut v,
22153 base_q_idx,
22154 enable_filter_intra,
22155 allow_screen_content_tools,
22156 allow_intrabc,
22157 &scan32,
22158 &scan16,
22159 &scan8,
22160 &scan4,
22161 tx_select,
22162 reduced_tx_set, fctx,
22163 )?;
22164 }
22165 PARTITION_SPLIT => {
22166 for q in 0..4 {
22167 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
22168 if r32 >= rows32 || c32 >= cols32 {
22169 continue;
22170 }
22171 let at32 = (r32 as usize * 2, c32 as usize * 2);
22172 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
22173 let (has_cols32, has_rows32) = (
22174 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
22175 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
22176 );
22177 let part32 = if has_cols32 && has_rows32 {
22178 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
22179 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22180 let (rng, _) = dec.debug_state();
22181 eprintln!(
22182 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
22183 r32 * BLOCK_MI,
22184 c32 * BLOCK_MI
22185 );
22186 }
22187 p
22188 } else {
22189 // lane-hgkf r1: the 32-level frame-edge bit is the
22190 // partition too (same libaom reader as the
22191 // superblock level above).
22192 match (has_cols32, has_rows32) {
22193 (true, false) => {
22194 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22195 let b = dec.symbol_fixed(&gather(
22196 &cdfs.partition_w32[ctx32],
22197 VERT_ALIKE,
22198 ));
22199 bump_edge32(b.min(1) as usize);
22200 bump_edge_part(2 + b.min(1) as usize);
22201 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22202 }
22203 (false, true) => {
22204 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22205 let b = dec.symbol_fixed(&gather(
22206 &cdfs.partition_w32[ctx32],
22207 HORZ_ALIKE,
22208 ));
22209 bump_edge32(b.min(1) as usize);
22210 bump_edge_part(2 + b.min(1) as usize);
22211 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22212 }
22213 _ => {
22214 bump_edge_both_cut(1);
22215 PARTITION_SPLIT
22216 }
22217 }
22218 };
22219 match part32 {
22220 PARTITION_NONE => {
22221 decode_block(
22222 &mut dec,
22223 &mut cdfs,
22224 &mut neighbours,
22225 at32,
22226 BLOCK,
22227 TxbSet::Luma32,
22228 TxbSet::Chroma16,
22229 TX32,
22230 TX16,
22231 (&scan32, &scan16),
22232 true,
22233 &mut y,
22234 &mut u,
22235 &mut v,
22236 base_q_idx,
22237 enable_filter_intra,
22238 allow_screen_content_tools,
22239 allow_intrabc,
22240 &scan32,
22241 &scan16,
22242 &scan8,
22243 &scan4,
22244 tx_select,
22245 reduced_tx_set, fctx,
22246 )?;
22247 }
22248 PARTITION_SPLIT => {
22249 for sub in 0..4 {
22250 let (sr, sc) =
22251 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
22252 if (sr as u32) * SUB_MI >= mi_rows
22253 || (sc as u32) * SUB_MI >= mi_cols
22254 {
22255 continue;
22256 }
22257 let (has_cols16, has_rows16) = (
22258 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
22259 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
22260 );
22261 let at16 = (sr, sc);
22262 let ctx16 = neighbours.partition_ctx(at16, SUB);
22263 if has_cols16 && has_rows16 {
22264 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
22265 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22266 eprintln!(
22267 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
22268 at16.0, at16.1
22269 );
22270 }
22271 if part16 == PARTITION_NONE {
22272 decode_block(
22273 &mut dec,
22274 &mut cdfs,
22275 &mut neighbours,
22276 at16,
22277 SUB,
22278 TxbSet::Luma16,
22279 TxbSet::Chroma8,
22280 TX16,
22281 TX8,
22282 (&scan16, &scan8),
22283 true,
22284 &mut y,
22285 &mut u,
22286 &mut v,
22287 base_q_idx,
22288 enable_filter_intra,
22289 allow_screen_content_tools,
22290 allow_intrabc,
22291 &scan32,
22292 &scan16,
22293 &scan8,
22294 &scan4,
22295 tx_select,
22296 reduced_tx_set, fctx,
22297 )?;
22298 continue;
22299 }
22300 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
22301 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
22302 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
22303 // `decode_partition` visit order (decodeframe.c):
22304 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
22305 // HORZ_B: top 16x8, BL 8x8, BR 8x8
22306 // VERT_A: TL 8x8, BL 8x8, right 8x16
22307 // VERT_B: left 8x16, TR 8x8, BR 8x8
22308 // The squares go through `decode_leaf8`, the strip through
22309 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
22310 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
22311 // used refuses the non-skip case at this size). Both writers keep
22312 // mi-granular mode/skip/palette records, so a later block's
22313 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
22314 // 16x16 cell.
22315 //
22316 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
22317 // top-right neighbour is the partition's own not-yet-decoded
22318 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
22319 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
22320 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
22321 let arm = part16 - PARTITION_HORZ_A;
22322 bump_ab16(arm);
22323 if part16 == PARTITION_VERT_B {
22324 hit!(VERT_B_INTRA_HITS);
22325 }
22326 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
22327 Some(crate::encode::Reach::vert_ab_partition())
22328 } else {
22329 None
22330 };
22331 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
22332 macro_rules! ab_leaf8 {
22333 ($mi:expr, $prev:expr) => {
22334 decode_leaf8(
22335 &mut dec,
22336 &mut cdfs,
22337 &mut neighbours,
22338 at16,
22339 $mi,
22340 (&scan8, &scan4),
22341 $prev,
22342 &mut y,
22343 &mut u,
22344 &mut v,
22345 base_q_idx,
22346 enable_filter_intra,
22347 allow_screen_content_tools,
22348 allow_intrabc,
22349 tx_select,
22350 reduced_tx_set, fctx,
22351 )?
22352 };
22353 }
22354 macro_rules! ab_strip {
22355 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
22356 decode_leaf_rect(
22357 &mut dec,
22358 &mut cdfs,
22359 &mut neighbours,
22360 at16,
22361 $mi,
22362 $bw,
22363 $bh,
22364 $prev,
22365 &mut y,
22366 &mut u,
22367 &mut v,
22368 enable_filter_intra,
22369 allow_screen_content_tools,
22370 base_q_idx,
22371 tx_select,
22372 reduced_tx_set, fctx,
22373 )?
22374 };
22375 }
22376 let tl = (mi_row0, mi_col0);
22377 let tr = (mi_row0, mi_col0 + 2);
22378 let bl = (mi_row0 + 2, mi_col0);
22379 let br = (mi_row0 + 2, mi_col0 + 2);
22380 let mut done: Vec<((usize, usize), usize)> = Vec::new();
22381 match part16 {
22382 PARTITION_HORZ_A => {
22383 let m_tl = ab_leaf8!(tl, done.last().copied());
22384 done.push((tl, m_tl));
22385 let m_tr = ab_leaf8!(tr, done.last().copied());
22386 done.push((tr, m_tr));
22387 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
22388 done.push((bl, m_bot));
22389 }
22390 PARTITION_HORZ_B => {
22391 let m_top = ab_strip!(tl, 16, 8, None);
22392 done.push((tl, m_top));
22393 let m_bl = ab_leaf8!(bl, done.last().copied());
22394 done.push((bl, m_bl));
22395 let m_br = ab_leaf8!(br, done.last().copied());
22396 done.push((br, m_br));
22397 }
22398 PARTITION_VERT_A => {
22399 let m_tl = ab_leaf8!(tl, done.last().copied());
22400 done.push((tl, m_tl));
22401 let m_bl = ab_leaf8!(bl, done.last().copied());
22402 done.push((bl, m_bl));
22403 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
22404 done.push((tr, m_right));
22405 }
22406 _ => {
22407 let m_left = ab_strip!(tl, 8, 16, None);
22408 done.push((tl, m_left));
22409 let m_tr = ab_leaf8!(tr, done.last().copied());
22410 done.push((tr, m_tr));
22411 let m_br = ab_leaf8!(br, done.last().copied());
22412 done.push((br, m_br));
22413 }
22414 }
22415 // Same coarse-slot write-back the real SPLIT path takes: the
22416 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
22417 // sub-block on the parent's bottom / right edge (the mi-exact map
22418 // above wins wherever it has an entry).
22419 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
22420 continue;
22421 }
22422 if part16 == PARTITION_HORZ {
22423 hit!(HORZ_VERT_INTRA_HITS);
22424 let (mi_row0, mi_col0) = (
22425 sr as u32 * SUB_MI,
22426 sc as u32 * SUB_MI,
22427 );
22428 let top = (mi_row0 as usize, mi_col0 as usize);
22429 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
22430 let mode_top = decode_leaf_rect(
22431 &mut dec,
22432 &mut cdfs,
22433 &mut neighbours,
22434 at16,
22435 top,
22436 16,
22437 8,
22438 None,
22439 &mut y,
22440 &mut u,
22441 &mut v,
22442 enable_filter_intra,
22443 allow_screen_content_tools,
22444 base_q_idx,
22445 tx_select,
22446 reduced_tx_set, fctx,
22447 )?;
22448 let mode_bot = decode_leaf_rect(
22449 &mut dec,
22450 &mut cdfs,
22451 &mut neighbours,
22452 at16,
22453 bot,
22454 16,
22455 8,
22456 Some((top, mode_top)),
22457 &mut y,
22458 &mut u,
22459 &mut v,
22460 enable_filter_intra,
22461 allow_screen_content_tools,
22462 base_q_idx,
22463 tx_select,
22464 reduced_tx_set, fctx,
22465 )?;
22466 neighbours.above_mode[sc] = mode_bot;
22467 neighbours.left_mode[sr] = mode_bot;
22468 continue;
22469 }
22470 if part16 == PARTITION_VERT {
22471 hit!(HORZ_VERT_INTRA_HITS);
22472 let (mi_row0, mi_col0) = (
22473 sr as u32 * SUB_MI,
22474 sc as u32 * SUB_MI,
22475 );
22476 let left = (mi_row0 as usize, mi_col0 as usize);
22477 let right = (mi_row0 as usize, mi_col0 as usize + 2);
22478 let mode_left = decode_leaf_rect(
22479 &mut dec,
22480 &mut cdfs,
22481 &mut neighbours,
22482 at16,
22483 left,
22484 8,
22485 16,
22486 None,
22487 &mut y,
22488 &mut u,
22489 &mut v,
22490 enable_filter_intra,
22491 allow_screen_content_tools,
22492 base_q_idx,
22493 tx_select,
22494 reduced_tx_set, fctx,
22495 )?;
22496 let mode_right = decode_leaf_rect(
22497 &mut dec,
22498 &mut cdfs,
22499 &mut neighbours,
22500 at16,
22501 right,
22502 8,
22503 16,
22504 Some((left, mode_left)),
22505 &mut y,
22506 &mut u,
22507 &mut v,
22508 enable_filter_intra,
22509 allow_screen_content_tools,
22510 base_q_idx,
22511 tx_select,
22512 reduced_tx_set, fctx,
22513 )?;
22514 neighbours.above_mode[sc] = mode_right;
22515 neighbours.left_mode[sr] = mode_right;
22516 continue;
22517 }
22518 if part16 == PARTITION_HORZ_4
22519 || part16 == PARTITION_VERT_4
22520 {
22521 decode_rect4_16(
22522 &mut dec,
22523 &mut cdfs,
22524 &mut neighbours,
22525 at16,
22526 part16 == PARTITION_HORZ_4,
22527 &mut y,
22528 &mut u,
22529 &mut v,
22530 enable_filter_intra,
22531 allow_screen_content_tools,
22532 base_q_idx,
22533 tx_select,
22534 reduced_tx_set, fctx,
22535 )?;
22536 continue;
22537 }
22538 // lane-r14 r2 (verifier note): every
22539 // one of the 10 symbols this CDF can
22540 // produce is handled above, so SPLIT
22541 // is the only value that reaches
22542 // here -- the refusal that used to
22543 // stand here was unreachable and is
22544 // gone from `refusal_inventory`.
22545 debug_assert_eq!(part16, PARTITION_SPLIT);
22546 // A real (non-straddle) SPLIT of a
22547 // whole 16x16 into four 8x8 leaves --
22548 // the same recursion the straddle
22549 // path below already runs when the
22550 // true frame edge forces it, just
22551 // over all four positions instead of
22552 // the one or two the edge leaves.
22553 let (mi_row0, mi_col0) =
22554 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22555 // Each 8x8 leaf's intra-mode context
22556 // must see its own siblings: the
22557 // bottom-left leaf's ABOVE neighbour
22558 // is leaf 0, not the previously
22559 // decoded leaf 1 (and the bottom-right
22560 // leaf's above is leaf 1, while
22561 // `prev_leaf` only ever carried the
22562 // immediately preceding one). The
22563 // coarse `above_mode`/`left_mode`
22564 // arrays hold one slot per 16x16, so
22565 // the sibling modes are swapped in
22566 // around each leaf call and restored
22567 // after; the loop tail writes the last
22568 // leaf's mode as before.
22569 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22570 for i in 0..4 {
22571 let (mr, mc) =
22572 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
22573 let leaf_mi = (mr as usize, mc as usize);
22574 let li = i as usize;
22575 let saved_modes =
22576 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22577 if li >= 2 {
22578 if let Some((below, _)) = sib_modes[li - 2] {
22579 neighbours.above_mode[sc] = below;
22580 }
22581 }
22582 if li % 2 == 1 {
22583 if let Some((_, right)) = sib_modes[li - 1] {
22584 neighbours.left_mode[sr] = right;
22585 }
22586 }
22587 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22588 let part8 =
22589 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22590 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22591 eprintln!(
22592 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
22593 );
22594 }
22595 let leaf_mode = if part8 == PARTITION_NONE {
22596 decode_leaf8(
22597 &mut dec,
22598 &mut cdfs,
22599 &mut neighbours,
22600 at16,
22601 leaf_mi,
22602 (&scan8, &scan4),
22603 None,
22604 &mut y,
22605 &mut u,
22606 &mut v,
22607 base_q_idx,
22608 enable_filter_intra,
22609 allow_screen_content_tools,
22610 allow_intrabc,
22611 tx_select,
22612 reduced_tx_set, fctx,
22613 ).map(|m| (m, m))?
22614 } else if part8 == PARTITION_SPLIT {
22615 decode_leaf_split4(
22616 &mut dec,
22617 &mut cdfs,
22618 &mut neighbours,
22619 at16,
22620 leaf_mi,
22621 &scan4,
22622 None,
22623 &mut y,
22624 &mut u,
22625 &mut v,
22626 base_q_idx,
22627 enable_filter_intra,
22628 allow_intrabc,
22629 reduced_tx_set, fctx,
22630 )?
22631 } else if part8 == PARTITION_HORZ
22632 || part8 == PARTITION_VERT
22633 {
22634 decode_leaf_rect8(
22635 &mut dec,
22636 &mut cdfs,
22637 &mut neighbours,
22638 at16,
22639 leaf_mi,
22640 part8 == PARTITION_VERT,
22641 &scan4,
22642 &mut y,
22643 &mut u,
22644 &mut v,
22645 base_q_idx,
22646 enable_filter_intra,
22647 allow_intrabc,
22648 tx_select,
22649 reduced_tx_set, fctx,
22650 )?
22651 } else {
22652 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
22653 };
22654 neighbours.above_mode[sc] = saved_modes.0;
22655 neighbours.left_mode[sr] = saved_modes.1;
22656 sib_modes[li] = Some(leaf_mode);
22657 }
22658 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
22659 neighbours.above_mode[sc] = below;
22660 }
22661 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
22662 neighbours.left_mode[sr] = right;
22663 }
22664 continue;
22665 }
22666 // The true edge falls inside this 16x16
22667 // leaf itself (mod-32==8 target sizes,
22668 // lane-av1-rect): one axis only -- an 8x8
22669 // leaf never itself straddles, so the
22670 // block splits cleanly along whichever
22671 // axis is short.
22672 // lane-edgeboth r1: when the true frame
22673 // edge cuts BOTH axes libaom's
22674 // `decode_partition` takes
22675 // `else if (!has_rows && !has_cols)
22676 // partition = PARTITION_SPLIT;` -- no
22677 // symbol of any kind is read, and the four
22678 // 8x8 children are then visited by the
22679 // same loop below, whose
22680 // `mr < mi_rows && mc < mi_cols` filter IS
22681 // libaom's own
22682 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
22683 // early return, so the three out-of-frame
22684 // quadrants get no neighbour or tx-grid
22685 // write.
22686 if !has_cols16 && !has_rows16 {
22687 bump_edge_both_cut(0);
22688 } else {
22689 // lane-golomb r1 (class
22690 // `parsed-then-discarded`): the gathered
22691 // bit IS the partition -- 0 names
22692 // PARTITION_HORZ (resp. VERT), only 1 is
22693 // SPLIT (libaom `ec_read_partition_impl`).
22694 // This path can only walk the four SPLIT
22695 // leaves, so a 0 refuses by name instead
22696 // of desyncing.
22697 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
22698 let edge_split = if has_cols16 {
22699 dec.symbol_fixed(&gather(
22700 &cdfs.partition_w16[ctx16],
22701 VERT_ALIKE,
22702 ))
22703 } else {
22704 dec.symbol_fixed(&gather(
22705 &cdfs.partition_w16[ctx16],
22706 HORZ_ALIKE,
22707 ))
22708 };
22709 // lane-hgkf r1: slots 2/3 of
22710 // [`EDGE_PART_HITS`], the gate's proof the
22711 // non-SPLIT edge arm actually decoded.
22712 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
22713 if edge_split == 0 {
22714 // lane-oddh r1: the strip IS decodable
22715 // -- libaom's `decode_partition` codes
22716 // only the FIRST half of an edge
22717 // HORZ/VERT (the second call is
22718 // guarded by the same has_rows/
22719 // has_cols test that made the
22720 // partition non-square), so one
22721 // 16x8 (resp. 8x16) strip covers the
22722 // whole visible band of a frame whose
22723 // height (resp. width) is 8 mod 16 --
22724 // the user's 3840x1608 film.
22725 hit!(HORZ_VERT_INTRA_HITS);
22726 hit!(EDGE_RECT_STRIP_HITS);
22727 let (mi_row0, mi_col0) =
22728 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22729 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
22730 let mode = decode_leaf_rect(
22731 &mut dec,
22732 &mut cdfs,
22733 &mut neighbours,
22734 at16,
22735 (mi_row0 as usize, mi_col0 as usize),
22736 bw,
22737 bh,
22738 None,
22739 &mut y,
22740 &mut u,
22741 &mut v,
22742 enable_filter_intra,
22743 allow_screen_content_tools,
22744 base_q_idx,
22745 tx_select,
22746 reduced_tx_set, fctx,
22747 )?;
22748 neighbours.above_mode[sc] = mode;
22749 neighbours.left_mode[sr] = mode;
22750 continue;
22751 }
22752 }
22753 let (mi_row0, mi_col0) =
22754 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22755 let leaf_positions: Vec<(u32, u32)> = (0..4)
22756 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
22757 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
22758 .collect();
22759 // See the sibling-mode note in the clean
22760 // SPLIT path above.
22761 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22762 for (mr, mc) in leaf_positions {
22763 let leaf_mi = (mr as usize, mc as usize);
22764 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
22765 as usize;
22766 let saved_modes =
22767 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22768 if li >= 2 {
22769 if let Some((below, _)) = sib_modes[li - 2] {
22770 neighbours.above_mode[sc] = below;
22771 }
22772 }
22773 if li % 2 == 1 {
22774 if let Some((_, right)) = sib_modes[li - 1] {
22775 neighbours.left_mode[sr] = right;
22776 }
22777 }
22778 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22779 let pre8 = dec.debug_state().0;
22780 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22781 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22782 eprintln!(
22783 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
22784 );
22785 }
22786 let leaf_mode = if part8 == PARTITION_NONE {
22787 decode_leaf8(
22788 &mut dec,
22789 &mut cdfs,
22790 &mut neighbours,
22791 at16,
22792 leaf_mi,
22793 (&scan8, &scan4),
22794 None,
22795 &mut y,
22796 &mut u,
22797 &mut v,
22798 base_q_idx,
22799 enable_filter_intra,
22800 allow_screen_content_tools,
22801 allow_intrabc,
22802 tx_select,
22803 reduced_tx_set, fctx,
22804 ).map(|m| (m, m))?
22805 } else if part8 == PARTITION_SPLIT {
22806 decode_leaf_split4(
22807 &mut dec,
22808 &mut cdfs,
22809 &mut neighbours,
22810 at16,
22811 leaf_mi,
22812 &scan4,
22813 None,
22814 &mut y,
22815 &mut u,
22816 &mut v,
22817 base_q_idx,
22818 enable_filter_intra,
22819 allow_intrabc,
22820 reduced_tx_set, fctx,
22821 )?
22822 } else if part8 == PARTITION_HORZ
22823 || part8 == PARTITION_VERT
22824 {
22825 decode_leaf_rect8(
22826 &mut dec,
22827 &mut cdfs,
22828 &mut neighbours,
22829 at16,
22830 leaf_mi,
22831 part8 == PARTITION_VERT,
22832 &scan4,
22833 &mut y,
22834 &mut u,
22835 &mut v,
22836 base_q_idx,
22837 enable_filter_intra,
22838 allow_intrabc,
22839 tx_select,
22840 reduced_tx_set, fctx,
22841 )?
22842 } else {
22843 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
22844 };
22845 neighbours.above_mode[sc] = saved_modes.0;
22846 neighbours.left_mode[sr] = saved_modes.1;
22847 sib_modes[li] = Some(leaf_mode);
22848 }
22849 // `record()`'s `above_mode`/`left_mode`
22850 // write is a no-op at an 8x8 leaf's own
22851 // side, so force the write once the whole
22852 // 16x16 slot's leaves are done, from the
22853 // last leaf (mirrors the writer's r15
22854 // fix).
22855 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
22856 neighbours.above_mode[sc] = below;
22857 }
22858 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
22859 neighbours.left_mode[sr] = right;
22860 }
22861 }
22862 }
22863 PARTITION_HORZ => {
22864 // lane-intradisp r1: two true 32x16 strips.
22865 decode_block_rect(
22866 &mut dec,
22867 &mut cdfs,
22868 &mut neighbours,
22869 at32,
22870 32,
22871 16,
22872 &mut y,
22873 &mut u,
22874 &mut v,
22875 enable_filter_intra,
22876 allow_screen_content_tools,
22877 base_q_idx,
22878 tx_select,
22879 reduced_tx_set, fctx,
22880 )?;
22881 if !has_rows32 {
22882 bump_edge32(2);
22883 }
22884 // lane-hgkf r1: at the frame edge only the first half of the strip is
22885 // coded (libaom `decode_partition` guards the second half with the same
22886 // test that made this partition non-square).
22887 if has_rows32 {
22888 decode_block_rect(
22889 &mut dec,
22890 &mut cdfs,
22891 &mut neighbours,
22892 (at32.0 + 1, at32.1),
22893 32,
22894 16,
22895 &mut y,
22896 &mut u,
22897 &mut v,
22898 enable_filter_intra,
22899 allow_screen_content_tools,
22900 base_q_idx,
22901 tx_select,
22902 reduced_tx_set, fctx,
22903 )?;
22904 }
22905 }
22906 PARTITION_VERT => {
22907 // lane-intradisp r1: mirror of PARTITION_HORZ
22908 // above with width/height swapped.
22909 decode_block_rect(
22910 &mut dec,
22911 &mut cdfs,
22912 &mut neighbours,
22913 at32,
22914 16,
22915 32,
22916 &mut y,
22917 &mut u,
22918 &mut v,
22919 enable_filter_intra,
22920 allow_screen_content_tools,
22921 base_q_idx,
22922 tx_select,
22923 reduced_tx_set, fctx,
22924 )?;
22925 if !has_cols32 {
22926 bump_edge32(3);
22927 }
22928 // lane-hgkf r1: at the frame edge only the first half of the strip is
22929 // coded (libaom `decode_partition` guards the second half with the same
22930 // test that made this partition non-square).
22931 if has_cols32 {
22932 decode_block_rect(
22933 &mut dec,
22934 &mut cdfs,
22935 &mut neighbours,
22936 (at32.0, at32.1 + 1),
22937 16,
22938 32,
22939 &mut y,
22940 &mut u,
22941 &mut v,
22942 enable_filter_intra,
22943 allow_screen_content_tools,
22944 base_q_idx,
22945 tx_select,
22946 reduced_tx_set, fctx,
22947 )?;
22948 }
22949 }
22950 PARTITION_HORZ_A => {
22951 // lane-part32 r1: two 16x16 squares on top +
22952 // a true 32x16 strip below (mirrors
22953 // decode_inter_block's cd6cb6d HORZ_A: TL,
22954 // TR, bottom strip).
22955 hit!(INTRA_HORZ_A_HITS);
22956 decode_block(
22957 &mut dec,
22958 &mut cdfs,
22959 &mut neighbours,
22960 at32,
22961 SUB,
22962 TxbSet::Luma16,
22963 TxbSet::Chroma8,
22964 TX16,
22965 TX8,
22966 (&scan16, &scan8),
22967 true,
22968 &mut y,
22969 &mut u,
22970 &mut v,
22971 base_q_idx,
22972 enable_filter_intra,
22973 allow_screen_content_tools,
22974 allow_intrabc,
22975 &scan32,
22976 &scan16,
22977 &scan8,
22978 &scan4,
22979 tx_select,
22980 reduced_tx_set, fctx,
22981 )?;
22982 decode_block(
22983 &mut dec,
22984 &mut cdfs,
22985 &mut neighbours,
22986 (at32.0, at32.1 + 1),
22987 SUB,
22988 TxbSet::Luma16,
22989 TxbSet::Chroma8,
22990 TX16,
22991 TX8,
22992 (&scan16, &scan8),
22993 true,
22994 &mut y,
22995 &mut u,
22996 &mut v,
22997 base_q_idx,
22998 enable_filter_intra,
22999 allow_screen_content_tools,
23000 allow_intrabc,
23001 &scan32,
23002 &scan16,
23003 &scan8,
23004 &scan4,
23005 tx_select,
23006 reduced_tx_set, fctx,
23007 )?;
23008 decode_block_rect(
23009 &mut dec,
23010 &mut cdfs,
23011 &mut neighbours,
23012 (at32.0 + 1, at32.1),
23013 32,
23014 16,
23015 &mut y,
23016 &mut u,
23017 &mut v,
23018 enable_filter_intra,
23019 allow_screen_content_tools,
23020 base_q_idx,
23021 tx_select,
23022 reduced_tx_set, fctx,
23023 )?;
23024 }
23025 PARTITION_HORZ_B => {
23026 // lane-part32 r1: a true 32x16 strip on top +
23027 // two 16x16 squares below (mirrors HORZ_A
23028 // with the strip/squares order flipped, same
23029 // shape as libaom decode_partition's HORZ_B).
23030 hit!(INTRA_HORZ_B_HITS);
23031 decode_block_rect(
23032 &mut dec,
23033 &mut cdfs,
23034 &mut neighbours,
23035 at32,
23036 32,
23037 16,
23038 &mut y,
23039 &mut u,
23040 &mut v,
23041 enable_filter_intra,
23042 allow_screen_content_tools,
23043 base_q_idx,
23044 tx_select,
23045 reduced_tx_set, fctx,
23046 )?;
23047 decode_block(
23048 &mut dec,
23049 &mut cdfs,
23050 &mut neighbours,
23051 (at32.0 + 1, at32.1),
23052 SUB,
23053 TxbSet::Luma16,
23054 TxbSet::Chroma8,
23055 TX16,
23056 TX8,
23057 (&scan16, &scan8),
23058 true,
23059 &mut y,
23060 &mut u,
23061 &mut v,
23062 base_q_idx,
23063 enable_filter_intra,
23064 allow_screen_content_tools,
23065 allow_intrabc,
23066 &scan32,
23067 &scan16,
23068 &scan8,
23069 &scan4,
23070 tx_select,
23071 reduced_tx_set, fctx,
23072 )?;
23073 decode_block(
23074 &mut dec,
23075 &mut cdfs,
23076 &mut neighbours,
23077 (at32.0 + 1, at32.1 + 1),
23078 SUB,
23079 TxbSet::Luma16,
23080 TxbSet::Chroma8,
23081 TX16,
23082 TX8,
23083 (&scan16, &scan8),
23084 true,
23085 &mut y,
23086 &mut u,
23087 &mut v,
23088 base_q_idx,
23089 enable_filter_intra,
23090 allow_screen_content_tools,
23091 allow_intrabc,
23092 &scan32,
23093 &scan16,
23094 &scan8,
23095 &scan4,
23096 tx_select,
23097 reduced_tx_set, fctx,
23098 )?;
23099 }
23100 PARTITION_VERT_A => {
23101 // lane-part32 r1: mirror of HORZ_A with
23102 // width/height swapped (TL, BL, right 16x32
23103 // strip).
23104 hit!(INTRA_VERT_A_HITS);
23105 let _vert_ab = crate::encode::Reach::vert_ab_partition();
23106 decode_block(
23107 &mut dec,
23108 &mut cdfs,
23109 &mut neighbours,
23110 at32,
23111 SUB,
23112 TxbSet::Luma16,
23113 TxbSet::Chroma8,
23114 TX16,
23115 TX8,
23116 (&scan16, &scan8),
23117 true,
23118 &mut y,
23119 &mut u,
23120 &mut v,
23121 base_q_idx,
23122 enable_filter_intra,
23123 allow_screen_content_tools,
23124 allow_intrabc,
23125 &scan32,
23126 &scan16,
23127 &scan8,
23128 &scan4,
23129 tx_select,
23130 reduced_tx_set, fctx,
23131 )?;
23132 decode_block(
23133 &mut dec,
23134 &mut cdfs,
23135 &mut neighbours,
23136 (at32.0 + 1, at32.1),
23137 SUB,
23138 TxbSet::Luma16,
23139 TxbSet::Chroma8,
23140 TX16,
23141 TX8,
23142 (&scan16, &scan8),
23143 true,
23144 &mut y,
23145 &mut u,
23146 &mut v,
23147 base_q_idx,
23148 enable_filter_intra,
23149 allow_screen_content_tools,
23150 allow_intrabc,
23151 &scan32,
23152 &scan16,
23153 &scan8,
23154 &scan4,
23155 tx_select,
23156 reduced_tx_set, fctx,
23157 )?;
23158 decode_block_rect(
23159 &mut dec,
23160 &mut cdfs,
23161 &mut neighbours,
23162 (at32.0, at32.1 + 1),
23163 16,
23164 32,
23165 &mut y,
23166 &mut u,
23167 &mut v,
23168 enable_filter_intra,
23169 allow_screen_content_tools,
23170 base_q_idx,
23171 tx_select,
23172 reduced_tx_set, fctx,
23173 )?;
23174 }
23175 PARTITION_VERT_B => {
23176 // lane-part32 r1: a true 16x32 strip on the
23177 // left + two 16x16 squares on the right
23178 // (libaom decode_partition VERT_B: left
23179 // strip, TR, BR).
23180 hit!(INTRA_VERT_B_HITS);
23181 let _vert_ab = crate::encode::Reach::vert_ab_partition();
23182 decode_block_rect(
23183 &mut dec,
23184 &mut cdfs,
23185 &mut neighbours,
23186 at32,
23187 16,
23188 32,
23189 &mut y,
23190 &mut u,
23191 &mut v,
23192 enable_filter_intra,
23193 allow_screen_content_tools,
23194 base_q_idx,
23195 tx_select,
23196 reduced_tx_set, fctx,
23197 )?;
23198 decode_block(
23199 &mut dec,
23200 &mut cdfs,
23201 &mut neighbours,
23202 (at32.0, at32.1 + 1),
23203 SUB,
23204 TxbSet::Luma16,
23205 TxbSet::Chroma8,
23206 TX16,
23207 TX8,
23208 (&scan16, &scan8),
23209 true,
23210 &mut y,
23211 &mut u,
23212 &mut v,
23213 base_q_idx,
23214 enable_filter_intra,
23215 allow_screen_content_tools,
23216 allow_intrabc,
23217 &scan32,
23218 &scan16,
23219 &scan8,
23220 &scan4,
23221 tx_select,
23222 reduced_tx_set, fctx,
23223 )?;
23224 decode_block(
23225 &mut dec,
23226 &mut cdfs,
23227 &mut neighbours,
23228 (at32.0 + 1, at32.1 + 1),
23229 SUB,
23230 TxbSet::Luma16,
23231 TxbSet::Chroma8,
23232 TX16,
23233 TX8,
23234 (&scan16, &scan8),
23235 true,
23236 &mut y,
23237 &mut u,
23238 &mut v,
23239 base_q_idx,
23240 enable_filter_intra,
23241 allow_screen_content_tools,
23242 allow_intrabc,
23243 &scan32,
23244 &scan16,
23245 &scan8,
23246 &scan4,
23247 tx_select,
23248 reduced_tx_set, fctx,
23249 )?;
23250 }
23251 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
23252 // lane-tx64x16 r3: the 1:4 pair at the 32x32
23253 // level -- four 32x8 (or 8x32) strips in
23254 // raster order, `quarter_step` = 2 mi, with
23255 // libaom `decode_partition`'s own `i > 0`
23256 // frame-edge break.
23257 let horz = part32 == PARTITION_HORZ_4;
23258 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
23259 let mut prev: Option<((usize, usize), usize)> = None;
23260 for i in 0..4 {
23261 let strip_mi = if horz {
23262 (base_mi.0 + i * 2, base_mi.1)
23263 } else {
23264 (base_mi.0, base_mi.1 + i * 2)
23265 };
23266 if i > 0
23267 && (strip_mi.0 >= mi_rows as usize
23268 || strip_mi.1 >= mi_cols as usize)
23269 {
23270 break;
23271 }
23272 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
23273 let (mode, _uv) = decode_block_rect4(
23274 &mut dec,
23275 &mut cdfs,
23276 &mut neighbours,
23277 strip_mi,
23278 bw,
23279 bh,
23280 prev,
23281 &mut y,
23282 &mut u,
23283 &mut v,
23284 enable_filter_intra,
23285 allow_screen_content_tools,
23286 base_q_idx,
23287 tx_select, fctx,
23288 )?;
23289 prev = Some((strip_mi, mode));
23290 }
23291 }
23292 _ => {
23293 return Err(unsupported(format!(
23294 "a 32x32 partition type this decoder does not code (value={part32})"
23295 )));
23296 }
23297 }
23298 }
23299 }
23300 PARTITION_HORZ => {
23301 // lane-sbpart r2: two true 64x32 strips.
23302 decode_block_rect64(
23303 &mut dec,
23304 &mut cdfs,
23305 &mut neighbours,
23306 at,
23307 64,
23308 32,
23309 &mut y,
23310 &mut u,
23311 &mut v,
23312 enable_filter_intra,
23313 allow_screen_content_tools,
23314 base_q_idx,
23315 tx_select,
23316 reduced_tx_set, fctx,
23317 )?;
23318 if !has_rows {
23319 bump_edge32(6);
23320 }
23321 // lane-golomb r1: at the frame edge only the first half of the
23322 // strip is coded (libaom `decode_partition` guards the second
23323 // with the same has_rows test that made this partition non-square).
23324 if has_rows {
23325 decode_block_rect64(
23326 &mut dec,
23327 &mut cdfs,
23328 &mut neighbours,
23329 (at.0 + 2, at.1),
23330 64,
23331 32,
23332 &mut y,
23333 &mut u,
23334 &mut v,
23335 enable_filter_intra,
23336 allow_screen_content_tools,
23337 base_q_idx,
23338 tx_select,
23339 reduced_tx_set, fctx,
23340 )?;
23341 }
23342 }
23343 PARTITION_VERT => {
23344 // lane-sbpart r2: mirror of PARTITION_HORZ above with
23345 // width/height swapped.
23346 decode_block_rect64(
23347 &mut dec,
23348 &mut cdfs,
23349 &mut neighbours,
23350 at,
23351 32,
23352 64,
23353 &mut y,
23354 &mut u,
23355 &mut v,
23356 enable_filter_intra,
23357 allow_screen_content_tools,
23358 base_q_idx,
23359 tx_select,
23360 reduced_tx_set, fctx,
23361 )?;
23362 if !has_cols {
23363 bump_edge32(7);
23364 }
23365 // lane-golomb r1: at the frame edge only the first half of the
23366 // strip is coded (libaom `decode_partition` guards the second
23367 // with the same has_cols test that made this partition non-square).
23368 if has_cols {
23369 decode_block_rect64(
23370 &mut dec,
23371 &mut cdfs,
23372 &mut neighbours,
23373 (at.0, at.1 + 2),
23374 32,
23375 64,
23376 &mut y,
23377 &mut u,
23378 &mut v,
23379 enable_filter_intra,
23380 allow_screen_content_tools,
23381 base_q_idx,
23382 tx_select,
23383 reduced_tx_set, fctx,
23384 )?;
23385 }
23386 }
23387 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
23388 // lane-part32 r4: the four superblock-level AB arms, each
23389 // two 32x32 squares plus one 64x32/32x64 strip, in
23390 // libaom's own `decode_partition` order (decodeframe.c:
23391 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
23392 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
23393 // TR, BR). The pieces are exactly the ones already proven
23394 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
23395 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
23396 hit_do! {
23397 SB_AB_HITS.with(|c| {
23398 let mut h = c.get();
23399 h[part - PARTITION_HORZ_A] += 1;
23400 c.set(h);
23401 });
23402 }
23403 // lane-part32 r5: only the two VERTICAL arms reorder the
23404 // square sub-blocks (TL, BL, TR, BR), so only they switch
23405 // libaom's `has_tr`/`has_bl` tables.
23406 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
23407 .then(crate::encode::Reach::vert_ab_partition);
23408 macro_rules! square32 {
23409 ($at:expr) => {
23410 decode_block(
23411 &mut dec,
23412 &mut cdfs,
23413 &mut neighbours,
23414 $at,
23415 BLOCK,
23416 TxbSet::Luma32,
23417 TxbSet::Chroma16,
23418 TX32,
23419 TX16,
23420 (&scan32, &scan16),
23421 true,
23422 &mut y,
23423 &mut u,
23424 &mut v,
23425 base_q_idx,
23426 enable_filter_intra,
23427 allow_screen_content_tools,
23428 allow_intrabc,
23429 &scan32,
23430 &scan16,
23431 &scan8,
23432 &scan4,
23433 tx_select,
23434 reduced_tx_set, fctx,
23435 )?
23436 };
23437 }
23438 macro_rules! strip64 {
23439 ($at:expr, $bw:expr, $bh:expr) => {
23440 decode_block_rect64(
23441 &mut dec,
23442 &mut cdfs,
23443 &mut neighbours,
23444 $at,
23445 $bw,
23446 $bh,
23447 &mut y,
23448 &mut u,
23449 &mut v,
23450 enable_filter_intra,
23451 allow_screen_content_tools,
23452 base_q_idx,
23453 tx_select,
23454 reduced_tx_set, fctx,
23455 )?
23456 };
23457 }
23458 let (br, bc) = (at.0 + 2, at.1 + 2);
23459 match part {
23460 PARTITION_HORZ_A => {
23461 square32!(at);
23462 square32!((at.0, bc));
23463 strip64!((br, at.1), 64, 32);
23464 }
23465 PARTITION_HORZ_B => {
23466 strip64!(at, 64, 32);
23467 square32!((br, at.1));
23468 square32!((br, bc));
23469 }
23470 PARTITION_VERT_A => {
23471 square32!(at);
23472 square32!((br, at.1));
23473 strip64!((at.0, bc), 32, 64);
23474 }
23475 _ => {
23476 strip64!(at, 32, 64);
23477 square32!((at.0, bc));
23478 square32!((br, bc));
23479 }
23480 }
23481 }
23482 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
23483 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
23484 // 16x64) strips in raster order. `decode_partition`
23485 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
23486 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
23487 // frame edge for `i > 0`, so a partial superblock codes
23488 // only the strips whose origin is inside the frame.
23489 let horz = part == PARTITION_HORZ_4;
23490 for i in 0..4 {
23491 let step_mi = i * (SB_MI as usize / 4);
23492 let (this_r_mi, this_c_mi) = if horz {
23493 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
23494 } else {
23495 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
23496 };
23497 if i > 0
23498 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
23499 {
23500 break;
23501 }
23502 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
23503 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
23504 decode_block_rect64(
23505 &mut dec,
23506 &mut cdfs,
23507 &mut neighbours,
23508 strip_at,
23509 bw,
23510 bh,
23511 &mut y,
23512 &mut u,
23513 &mut v,
23514 enable_filter_intra,
23515 allow_screen_content_tools,
23516 base_q_idx,
23517 tx_select,
23518 reduced_tx_set, fctx,
23519 )?;
23520 }
23521 }
23522 _ => {
23523 return Err(unsupported(
23524 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
23525 ));
23526 }
23527 }
23528 }
23529 }
23530 if waving {
23531 wave_submit(fctx, wave_job.0, wave_job.1);
23532 }
23533 // lane-timeline: this tile's last symbol is read here; its wavefront
23534 // workers are drained by `_wave`'s drop at the end of the iteration.
23535 crate::timeline::tile_done();
23536 flush_recon(fctx, &mut y, &mut u, &mut v);
23537
23538 if tile_num == tile_info.context_update_tile_id {
23539 result_cdfs = cdfs;
23540 }
23541 }
23542 crate::timeline::recon_done();
23543
23544 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
23545 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
23546 // that isolate whether a decode-order frame's mismatch already exists
23547 // in reconstruction (this dump) vs is introduced by the loop filter
23548 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
23549 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE la

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