forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB682c080Tahinli2 months ago2434 commits

decode.rs23586 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).
8277fn 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).
8285fn 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 let (cw, ch) = (bw / 2, bh / 2);
9047 let mut ac = vec![0i32; cw * ch];
9048 let mut sum = 0i32;
9049 for cy in 0..ch {
9050 for cx in 0..cw {
9051 let (lx, ly) = (px + cx * 2, py + cy * 2);
9052 let q3 = (i32::from(y.data[ly * y.width + lx])
9053 + i32::from(y.data[ly * y.width + lx + 1])
9054 + i32::from(y.data[(ly + 1) * y.width + lx])
9055 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
9056 << 1;
9057 ac[cy * cw + cx] = q3;
9058 sum += q3;
9059 }
9060 }
9061 let num_pel = (cw * ch) as i32;
9062 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
9063 ac.iter_mut().for_each(|v| *v -= avg);
9064 ac
9065}
9066
9067/// Everything a rect strip already read out of the stream before its luma
9068/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9069/// (nine values that would otherwise be nine more parameters).
9070struct RectStripModes {
9071 skip: bool,
9072 mode: usize,
9073 angle_delta_y: i32,
9074 uv_predict_mode: usize,
9075 angle_delta_uv: i32,
9076 alpha: Option<(i32, i32)>,
9077 filter_intra: Option<usize>,
9078 smooth_neighbor: bool,
9079 smooth_neighbor_uv: bool,
9080 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9081 /// mapped through the colour table), sliced per transform unit below --
9082 /// palette prediction reads no edge pixels, so a unit's slice of the
9083 /// whole-block map IS its prediction. Without this a palette strip whose
9084 /// transform splits predicted DC and came out flat grey while the entropy
9085 /// stream stayed in sync (the coefficients are read either way).
9086 palette_y: Option<Vec<u16>>,
9087 /// As `palette_y`, for the un-split chroma transform (U, V).
9088 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9089}
9090
9091/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9092/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9093/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9094/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9095/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9096/// TX_32X16`) and only the second reaches a square -- the reason
9097/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9098/// already square) mis-tiled 1:4 strips.
9099fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
9100 let (mut w, mut h) = (bw.min(64), bh.min(64));
9101 for _ in 0..depth {
9102 match w.cmp(&h) {
9103 std::cmp::Ordering::Greater => w /= 2,
9104 std::cmp::Ordering::Less => h /= 2,
9105 std::cmp::Ordering::Equal => {
9106 w /= 2;
9107 h /= 2;
9108 }
9109 }
9110 }
9111 (w, h)
9112}
9113
9114/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9115/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9116/// rect path here refused by name until now ("per-unit rect prediction is not
9117/// ported").
9118///
9119/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9120/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9121/// strip the very first step already lands on a SQUARE transform
9122/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9123/// every further step halves a square) -- so each unit is square and reads
9124/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9125/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9126/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9127/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9128/// split by luma's depth.
9129///
9130/// Each unit predicts off whatever the earlier units of this same block
9131/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9132/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9133/// what predicting the whole strip in one shot got wrong.
9134#[allow(clippy::too_many_arguments)]
9135fn decode_rect_split(
9136 dec: &mut SymbolDecoder,
9137 cdfs: &mut Cdfs,
9138 neighbours: &mut Neighbours,
9139 at_mi: (usize, usize),
9140 bw: usize,
9141 bh: usize,
9142 // The transform unit's own width and height in pixels. Square for every
9143 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9144 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9145 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9146 tx_w: usize,
9147 tx_h: usize,
9148 m: &RectStripModes,
9149 y: &mut PlaneBuf<'static>,
9150 u: &mut PlaneBuf<'static>,
9151 v: &mut PlaneBuf<'static>,
9152 base_q_idx: u8,
9153 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9154) -> Result<()> {
9155 let (mi_r, mi_c) = at_mi;
9156 let (px, py) = (mi_c * MI, mi_r * MI);
9157 let (cpx, cpy) = (px / 2, py / 2);
9158 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9159 // The chroma transform is picked before any symbol is read, so an
9160 // unsupported chroma shape refuses before this strip desyncs the tile.
9161 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9162 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9163 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9164 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9165 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9166 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9167 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9168 // squares a rect transform down to a CDF set by
9169 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9170 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9171 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9172 // paths already prove for these same shapes.
9173 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9174 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9175 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9176 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9177 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9178 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9179 _ => None,
9180 };
9181 if !m.skip {
9182 if let Some(i) = match (chroma_w, chroma_h) {
9183 (32, 8) => Some(0),
9184 (8, 32) => Some(1),
9185 (8, 4) => Some(2),
9186 (4, 8) => Some(3),
9187 _ => None,
9188 } {
9189 hit_do! {
9190 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9191 let mut hits = c.get();
9192 hits[i] += 1;
9193 c.set(hits);
9194 });
9195 }
9196 }
9197 if chroma.is_none() {
9198 // Diagnostic for the next caller that lands here (class
9199 // refusal-names-a-correlate: the message names the tool, not the
9200 // shape); the refusal below keeps its inventory-pinned wording.
9201 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9202 }
9203 }
9204 // lane-rectsplit r2 (verifier finding): with both callers wired
9205 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9206 // 64x32/32x64) every shape that reaches here has a table above, so this
9207 // arm is UNREACHABLE today. It stays as the shape guard for the next
9208 // caller -- a new strip size would otherwise hit the `expect` below and
9209 // panic instead of refusing by name -- and so stays in
9210 // `refusal_inventory::REFUSALS`.
9211 if !m.skip && chroma.is_none() {
9212 return Err(unsupported(
9213 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9214 ));
9215 }
9216 hit!(RECT_SPLIT_TX_HITS);
9217 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9218 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9219 }
9220 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9221 // A square unit reads through the ordinary square [`read_plane`]; a rect
9222 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9223 // the very tables the unsplit 16x8/32x16 paths use.
9224 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9225 (w, h) if w == h => None,
9226 (16, 8) | (8, 16) => Some((
9227 if reduced_tx_set {
9228 TxbSet::LumaRect16x8
9229 } else {
9230 TxbSet::LumaRect16x8Set1
9231 },
9232 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9233 )),
9234 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9235 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9236 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9237 // strip, read through the `luma_64corner` arm below instead of a rect
9238 // table -- a 64-length axis codes only its low 32 coefficients
9239 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9240 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9241 // depth-0 arm already reads on the key-frame path.
9242 //
9243 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9244 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9245 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9246 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9247 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9248 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9249 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9250 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9251 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9252 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9253 (64, 32) | (32, 64) => None,
9254 _ => {
9255 return Err(unsupported(format!(
9256 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9257 coefficient tables for that shape here)"
9258 )))
9259 }
9260 };
9261 // The `None` above that is NOT the square arm.
9262 let luma_64corner = tx_w != tx_h;
9263 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9264 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9265 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9266 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9267 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9268 // per-unit rect walk stay wired above/below; the round that finds that
9269 // defect deletes this refusal and nothing else.
9270 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9271 let luma_scan = default_scan(tx_w.min(tx_h));
9272 let zero_tu = vec![0i32; tx_w * tx_h];
9273 // The strip's OWN edge availability, the fallback for a transform unit
9274 // whose top-right/bottom-left pixels fall outside the strip.
9275 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9276 for tu_row in 0..bh / tx_h {
9277 for tu_col in 0..bw / tx_w {
9278 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9279 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9280 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9281 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9282 // libaom clips `av1_foreach_transformed_block_in_plane` to
9283 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9284 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9285 // TOP-LEFT sample falls outside the frame is never coded. We read
9286 // coefficients for those phantom units and desynced the stream at
9287 // the very next symbol.
9288 if tu_px >= y.true_width || tu_py >= y.true_height {
9289 continue;
9290 }
9291 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9292 // transform unit INSIDE a block, which is a different rule from
9293 // the standalone-block table [`Reach::of`] applies -- and the
9294 // reason a depth-2 superblock strip came out one sample off
9295 // before this: `Reach::of(tx, ..)` answered as if the unit were
9296 // its own block at that superblock position.
9297 // * top-right: if the unit's right neighbour is still inside the
9298 // strip the pixels are already reconstructed (`col_off +
9299 // tx_wide < plane_bw`); otherwise only the strip's own top row
9300 // of units can reach past it, through the block-level answer.
9301 // * bottom-left: a unit that is not in the strip's left column
9302 // has none (`col_off > 0` returns 0); inside the strip
9303 // (`row_off + tx_high < plane_bh`) they are the left
9304 // neighbour's, already reconstructed; the last row falls back
9305 // to the block-level answer.
9306 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9307 // The unit's own window on the block's palette prediction.
9308 if let Some(buf) = &m.palette_y {
9309 let tu_buf: Vec<u16> = (0..tx_h)
9310 .flat_map(|i| {
9311 let base = (row_off + i) * bw + col_off;
9312 buf[base..base + tx_w].iter().copied()
9313 })
9314 .collect();
9315 set_palette_pred(tu_buf, fctx);
9316 }
9317 if m.skip {
9318 push_intra_rect(0,
9319 tu_px,
9320 tu_py,
9321 tx_w,
9322 tx_h,
9323 m.mode,
9324 m.angle_delta_y,
9325 tu_reach,
9326 &zero_tu,
9327 None,
9328 m.filter_intra,
9329 m.smooth_neighbor, fctx,
9330 );
9331 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9332 } else if luma_64corner && luma_rect.is_none() {
9333 // The un-split 64-level luma transform: `read_coeffs` on the
9334 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9335 // and the real rect shape passed through for
9336 // `av1_nz_map_ctx_offset` -- byte for byte
9337 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9338 // 64-level strip gate already proves. `tx_type` is not coded
9339 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9340 // the square-up size is TX_64X64), and this unit covers its
9341 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9342 if crate::envflags::env_flag!("EC_RECT64TU") {
9343 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9344 }
9345 hit_do! {
9346 RECT64_CORNER_TU_HITS.with(|c| {
9347 let mut v = c.get();
9348 v[usize::from(tx_h > tx_w)] += 1;
9349 c.set(v);
9350 });
9351 }
9352 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9353 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
9354 let (corner, tu_tx_type) = read_coeffs(
9355 dec,
9356 &mut coding,
9357 default_scan(TX32),
9358 0,
9359 dc_sign_ctx(tu_around.2),
9360 TxType::DctDct,
9361 Some((tx_w, tx_h)),
9362 )?;
9363 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
9364 let mut tu_grid = vec![0i32; tx_w * tx_h];
9365 for row in 0..ch {
9366 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
9367 }
9368 let residual = dequant_and_inverse_typed_wh(
9369 &tu_grid,
9370 tx_w,
9371 tx_h,
9372 crate::decode::bit_depth(fctx),
9373 block_q_idx(fctx),
9374 plane_q_delta(0, fctx).0,
9375 plane_q_delta(0, fctx).1,
9376 tu_tx_type,
9377 );
9378 push_intra_rect(0,
9379 tu_px,
9380 tu_py,
9381 tx_w,
9382 tx_h,
9383 m.mode,
9384 m.angle_delta_y,
9385 tu_reach,
9386 &residual,
9387 None,
9388 m.filter_intra,
9389 m.smooth_neighbor, fctx,
9390 );
9391 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9392 } else if let Some((rect_set, rect_scan)) = luma_rect {
9393 // The rect-unit twin of the square arm below: same contexts,
9394 // same order, through the rect coefficient reader. The
9395 // `tx_type` CDF row of a filter-intra block is
9396 // `fimode_to_intradir[filter_intra_mode]`, never the block's
9397 // own (always DC_PRED) mode -- [`read_plane`] applies that
9398 // for the square arm, so this one must too.
9399 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9400 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
9401 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
9402 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
9403 // neighbour-magnitude table is for a unit SMALLER than its
9404 // block. [`decode_block_rect`]'s own unsplit read passes a
9405 // literal 0 for the same reason; this arm applied the table
9406 // unconditionally and desynced every depth-0 rect strip that
9407 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
9408 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
9409 0
9410 } else {
9411 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
9412 };
9413 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
9414 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9415 dec,
9416 &mut coding,
9417 rect_scan,
9418 tx_w,
9419 tx_h,
9420 tu_skip_ctx,
9421 dc_sign_ctx(tu_around.2),
9422 TxType::DctDct,
9423 )?;
9424 let residual = dequant_and_inverse_typed_wh(
9425 &tu_grid,
9426 tx_w,
9427 tx_h,
9428 crate::decode::bit_depth(fctx),
9429 block_q_idx(fctx),
9430 plane_q_delta(0, fctx).0,
9431 plane_q_delta(0, fctx).1,
9432 tu_tx_type,
9433 );
9434 push_intra_rect(0,
9435 tu_px,
9436 tu_py,
9437 tx_w,
9438 tx_h,
9439 m.mode,
9440 m.angle_delta_y,
9441 tu_reach,
9442 &residual,
9443 None,
9444 m.filter_intra,
9445 m.smooth_neighbor, fctx,
9446 );
9447 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9448 } else {
9449 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9450 // This unit is smaller than the block it sits in, so
9451 // `txb_skip_ctx` is the neighbour-magnitude table, not the
9452 // lone-TU 0 (spec `get_txb_ctx_general`).
9453 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9454 let tu_grid = read_plane(
9455 dec,
9456 cdfs,
9457 luma_set,
9458 &luma_scan,
9459 0,
9460 tu_around,
9461 m.mode,
9462 m.mode,
9463 m.angle_delta_y,
9464 tu_reach,
9465 y,
9466 tu_px,
9467 tu_py,
9468 tx_w,
9469 tx_w,
9470 base_q_idx,
9471 None,
9472 m.filter_intra,
9473 Some(tu_skip_ctx),
9474 m.smooth_neighbor, fctx,
9475 )?;
9476 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9477 }
9478 }
9479 }
9480 // CHROMA: one un-split rect transform for the whole strip.
9481 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9482 let reach = block_reach;
9483 let (u_grid, v_grid) = if m.skip {
9484 let zero = Grid::Zero(chroma_w * chroma_h);
9485 if let Some((ub, _)) = &m.palette_uv {
9486 set_palette_pred(ub.clone(), fctx);
9487 }
9488 push_intra_rect(1,
9489 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9490 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
9491 );
9492 if let Some((_, vb)) = &m.palette_uv {
9493 set_palette_pred(vb.clone(), fctx);
9494 }
9495 push_intra_rect(2,
9496 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9497 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
9498 );
9499 (zero.clone(), zero)
9500 } else {
9501 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
9502 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
9503 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
9504 // so only the 16x8/8x16 pair takes the mode-indexed default.
9505 let default_tx = if chroma_w.max(chroma_h) >= 32 {
9506 TxType::DctDct
9507 } else {
9508 default_intra_tx_type(m.uv_predict_mode as u8)
9509 };
9510 let around = neighbours.around_mi_rect(at_mi, bw, bh);
9511 let mut grids: Vec<Grid> = Vec::with_capacity(2);
9512 for plane_idx in 1..=2 {
9513 let skip_ctx =
9514 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
9515 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
9516 let (levels, tx_type) = read_coeffs_rect(
9517 dec,
9518 &mut coding,
9519 chroma_scan,
9520 chroma_w,
9521 chroma_h,
9522 skip_ctx,
9523 dc_sign_ctx(around[plane_idx].2),
9524 default_tx,
9525 )?;
9526 // The same delta_q proof the unsplit rect64 path records
9527 // (lane-rectsplit r4: lifting the split-transform refusal moved
9528 // superblock strips onto this path, so only counting there would
9529 // leave the delta_q gate's counter silent for them).
9530 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
9531 hit!(RECT64_QIDX_DRIFT_HITS);
9532 }
9533 let residual = dequant_and_inverse_typed_wh(
9534 &levels,
9535 chroma_w,
9536 chroma_h,
9537 crate::decode::bit_depth(fctx),
9538 fctx.current_q_idx.with(|c| c.get()),
9539 plane_q_delta(plane_idx, fctx).0,
9540 plane_q_delta(plane_idx, fctx).1,
9541 tx_type,
9542 );
9543 let cfl = m
9544 .alpha
9545 .zip(ac)
9546 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
9547 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9548 if let Some((ub, vb)) = &m.palette_uv {
9549 let buf = if plane_idx == 1 { ub } else { vb };
9550 set_palette_pred(buf.clone(), fctx);
9551 }
9552 push_intra_rect(plane_idx,
9553 cpx,
9554 cpy,
9555 chroma_w,
9556 chroma_h,
9557 m.uv_predict_mode,
9558 m.angle_delta_uv,
9559 reach,
9560 &residual,
9561 cfl,
9562 None,
9563 m.smooth_neighbor_uv, fctx,
9564 );
9565 grids.push(levels);
9566 }
9567 let mut it = grids.into_iter();
9568 (it.next().unwrap(), it.next().unwrap())
9569 };
9570 neighbours.record_split_luma_rect_mi(
9571 at_mi,
9572 bw,
9573 bh,
9574 m.mode,
9575 m.uv_predict_mode,
9576 [&u_grid, &v_grid],
9577 );
9578 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
9579 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
9580 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9581 let (rng, _) = dec.debug_state();
9582 eprintln!(
9583 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
9584 tx={tx_w}x{tx_h} rng={rng}"
9585 );
9586 }
9587 Ok(())
9588}
9589
9590/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
9591/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
9592/// because it predicts squares only. Every pixel here goes through the rect
9593/// machinery the key-frame paths already prove: [`decode_rect_split`], which
9594/// at `depth == 0` is the unsplit strip as a single transform unit and
9595/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9596///
9597/// What is genuinely different from [`decode_block_rect`] is the mode
9598/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9599/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9600/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9601/// intra-in-inter arm's own reads at the rect footprint, including its
9602/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9603/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9604/// square and this arm) and a nonzero luma angle delta refused by name.
9605///
9606/// The strip's own neighbour records (luma per transform unit, chroma, skip
9607/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9608/// inter-side bands and the mi map.
9609#[allow(clippy::too_many_arguments)]
9610/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9611/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9612/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9613/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9614/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9615/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
9616/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
9617/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
9618/// table here rather than a shift of `bw.min(bh)`.
9619fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
9620 Some(match (bw.min(bh), bw.max(bh)) {
9621 (8, 16) => (1usize, 1usize),
9622 (16, 32) => (2, 2),
9623 (32, 64) => (3, 3),
9624 (8, 32) => (1, 2),
9625 (16, 64) => (2, 3),
9626 _ => return None,
9627 })
9628}
9629
9630/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
9631/// block path"): the shapes that can reach that arm, enumerated against the
9632/// MEASURED domain of the inter block path
9633/// ([`INTER_BLOCK_SHAPES`], the census the gate
9634/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
9635/// fills from three real streams).
9636///
9637/// [`decode_intra_rect_in_inter`] is called from one site, under
9638/// `write_w != side || write_h != side`, and only after two earlier arms have
9639/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
9640/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
9641/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
9642/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
9643/// and each of those has a row, so the refusal names a shape no measured
9644/// stream can present.
9645#[test]
9646fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
9647 let mut checked = 0;
9648 for &(side, w, h) in &INTER_BLOCK_SHAPES {
9649 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
9650 continue;
9651 }
9652 assert!(
9653 intra_in_inter_size_row(w, h).is_some(),
9654 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
9655 the \"no size-group/tx-category row\" refusal"
9656 );
9657 checked += 1;
9658 }
9659 assert_eq!(
9660 checked, 10,
9661 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
9662 lookup, not the 10 this claim was measured over"
9663 );
9664}
9665
9666/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
9667/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
9668/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
9669/// matched before the square arm's `log2` shortcut).
9670///
9671/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
9672/// row here"; the enumeration below is what proves no conformant block can
9673/// reach it.
9674pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
9675 Some(match (write_w, write_h) {
9676 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
9677 // below maps 128 to row 4 (BLOCK_16X32).
9678 (64, 128) => 14,
9679 (128, 64) => 15,
9680 (128, 128) => 16,
9681 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
9682 (16, 32) => 4,
9683 (32, 16) => 5,
9684 (32, 64) => 6,
9685 (64, 32) => 7,
9686 (8, 32) => 8,
9687 (32, 8) => 9,
9688 (16, 64) => 10,
9689 (64, 16) => 11,
9690 // lane-inter4 r3: the 16x16-level rect inter leaves.
9691 (8, 16) => 12,
9692 (16, 8) => 13,
9693 _ => return None,
9694 })
9695}
9696
9697/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
9698/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
9699/// `block_size_wide`/`block_size_high`).
9700#[cfg(test)]
9701const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
9702 (4, 4),
9703 (4, 8),
9704 (8, 4),
9705 (8, 8),
9706 (8, 16),
9707 (16, 8),
9708 (16, 16),
9709 (16, 32),
9710 (32, 16),
9711 (32, 32),
9712 (32, 64),
9713 (64, 32),
9714 (64, 64),
9715 (64, 128),
9716 (128, 64),
9717 (128, 128),
9718 (4, 16),
9719 (16, 4),
9720 (8, 32),
9721 (32, 8),
9722 (16, 64),
9723 (64, 16),
9724];
9725
9726/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
9727/// shape with no CDF row here" names a shape no conformant stream can present.
9728///
9729/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
9730/// whose `write_w.min(write_h) >= 8` clause is libaom's
9731/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
9732/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
9733/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
9734/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
9735/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
9736/// clause rejects before the lookup.
9737#[test]
9738fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
9739 let mut rows = std::collections::BTreeSet::new();
9740 let mut excluded = 0;
9741 for (w, h) in BLOCK_SIZES_ALL_WH {
9742 if w.min(h) < 8 {
9743 excluded += 1;
9744 assert!(
9745 w == 4 || h == 4,
9746 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
9747 );
9748 continue;
9749 }
9750 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
9751 panic!(
9752 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
9753 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
9754 )
9755 });
9756 assert!(
9757 row < 17,
9758 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
9759 );
9760 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
9761 }
9762 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
9763 assert_eq!(
9764 rows.len(),
9765 17,
9766 "17 eligible footprints must fill all 17 rows of the motion_mode table"
9767 );
9768}
9769
9770fn decode_intra_rect_in_inter(
9771 dec: &mut SymbolDecoder,
9772 cdfs: &mut Cdfs,
9773 neighbours: &mut Neighbours,
9774 at: (usize, usize),
9775 bw: usize,
9776 bh: usize,
9777 skip: bool,
9778 allow_screen_content_tools: bool,
9779 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
9780 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
9781 strip16: Option<(bool, bool)>,
9782 y: &mut PlaneBuf<'static>,
9783 u: &mut PlaneBuf<'static>,
9784 v: &mut PlaneBuf<'static>,
9785 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
9786) -> Result<()> {
9787 // `at` is in MI units (the inter path's own unit since lane-inter4);
9788 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
9789 // below are still keyed by.
9790 let (mi_r, mi_c) = at;
9791 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9792 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
9793 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
9794 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
9795 // finding -- the category is NOT the same for every strip size).
9796 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
9797 // it is refused by name rather than read from the wrong CDF row.
9798 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
9799 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
9800 // tx-depth category is 1 -- but nothing here has to know either, because
9801 // the strip decodes through the very body the KEY FRAME path proves for
9802 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
9803 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
9804 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
9805 // inter-frame difference is the mode-info read, which
9806 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
9807 // `y_mode[0]` plus the `skip` this caller already read.
9808 if let Some((horz, has_chroma)) = strip16 {
9809 // lane-t900 r22: the screen-content refusal here was STALE (class
9810 // stale-premise): [`decode_rect4_16_strip`] takes
9811 // `allow_screen_content_tools` and reads the whole palette syntax
9812 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
9813 // pair) -- the key frame proves that body. Lifted with the 10-bit
9814 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
9815 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
9816 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
9817 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
9818 let res = decode_rect4_16_strip(
9819 dec,
9820 cdfs,
9821 neighbours,
9822 (mi_r, mi_c),
9823 horz,
9824 has_chroma,
9825 // The inter strips of the same partition publish their own
9826 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
9827 // has nothing to add here.
9828 None,
9829 y,
9830 u,
9831 v,
9832 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9833 allow_screen_content_tools,
9834 base_q_idx,
9835 fctx.tx_select_inter.with(std::cell::Cell::get),
9836 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9837 );
9838 fctx.intra_in_inter_mode.with(|c| c.set(None));
9839 let (mode, uv, (tx_w, tx_h)) = res?;
9840 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
9841 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
9842 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
9843 // block of an inter frame, intra ones included, and
9844 // `txfm_partition_update` for the var-tx context. The key-frame body
9845 // writes neither (a key frame has no var-tx tree and its own readers
9846 // use the deblock grid), so the block AFTER this strip read a stale
9847 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
9848 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
9849 // 16x16 row.
9850 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9851 for i in 0..bw / MI {
9852 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
9853 *cell = tx_w as u8;
9854 }
9855 }
9856 for i in 0..bh / MI {
9857 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
9858 *cell = tx_h as u8;
9859 }
9860 }
9861 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
9862 // coarse 16-px cell holds one entry for the whole 16x16 and the last
9863 // block to write it wins).
9864 neighbours.above_mode[c] = mode;
9865 neighbours.left_mode[r] = mode;
9866 if let Some(uvm) = uv {
9867 neighbours.above_uv_mode[c] = uvm;
9868 neighbours.left_uv_mode[r] = uvm;
9869 }
9870 neighbours.above_side[c] = bw;
9871 neighbours.left_side[r] = bh;
9872 if crate::envflags::env_flag!("EC_INTRA16X4") {
9873 eprintln!(
9874 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
9875 mi_c * MI,
9876 mi_r * MI
9877 );
9878 }
9879 hit_do! {
9880 INTRA16X4_IN_INTER_HITS.with(|h| {
9881 let mut v = h.get();
9882 v[usize::from(!horz)] += 1;
9883 v[2] += usize::from(has_chroma);
9884 h.set(v);
9885 });
9886 }
9887 return Ok(());
9888 }
9889 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
9890 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
9891 // puts BLOCK_128X64/64X128/128X128 in group 3 and
9892 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
9893 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
9894 // block decodes through the very body the KEY FRAME path proves for this
9895 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
9896 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
9897 // `Reach` rule and the frame-edge write clip). The only inter-frame
9898 // differences live inside that body: the mode-info read
9899 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
9900 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
9901 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
9902 // palette (>64) do not exist at this size and are refused by name there.
9903 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
9904 // `intra128_in_inter_witness2.obu` (gate
9905 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
9906 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
9907 // all 15 frames, so the hits are counted out of exact frames (class
9908 // `counter-from-refused-stream`). What r16/r17 could not find, and what
9909 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
9910 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
9911 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
9912 // where the frame EDGE forces it: a partial last superblock row has
9913 // `has_rows128 == false`, so the 128x64 top half is implied, and a
9914 // partial last column implies the 64x128 left half. Put content no
9915 // reference holds (a fresh smooth ramp) in exactly those two bands of an
9916 // inter frame and the encoder codes those forced halves INTRA.
9917 if bw.max(bh) == 128 {
9918 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
9919 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
9920 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
9921 // palette_syntax`), so a 128-root half consumes no palette syntax and
9922 // a screen-content frame's half is syntactically identical to the
9923 // non-screen one this arm already decodes byte-exact.
9924 if coeff_trace_on() {
9925 // lane-t900 r16: which decode-order frame this arm fires in --
9926 // interleaved with the `EC_COEFF_FRAME` markers, this is what
9927 // proves the hit is counted out of a frame that compares exact
9928 // (class `counter-from-refused-stream`).
9929 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
9930 }
9931 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
9932 let res = decode_block_128rect(
9933 dec,
9934 cdfs,
9935 neighbours,
9936 (r, c),
9937 bw,
9938 bh,
9939 y,
9940 u,
9941 v,
9942 base_q_idx,
9943 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9944 allow_screen_content_tools,
9945 fctx.tx_select_inter.with(std::cell::Cell::get),
9946 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9947 );
9948 fctx.intra_in_inter_mode.with(|c| c.set(None));
9949 return res;
9950 }
9951 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
9952 if crate::envflags::env_flag!("EC_OBMCREC") {
9953 eprintln!(
9954 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
9955 );
9956 }
9957 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
9958 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
9959 // can arrive here are enumerated against the measured block-shape
9960 // census ([`INTER_BLOCK_SHAPES`]) by
9961 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
9962 // -- every one of them has a row, so this arm names a shape no stream
9963 // has been able to present.
9964 return Err(unsupported(format!(
9965 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
9966 )));
9967 };
9968 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
9969 // screen-content frame ("palette syntax is consumed for square blocks
9970 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
9971 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
9972 // it, while the 2:1 reader inlined further down now codes the same syntax
9973 // itself. A real `--tune-content=screen` inter stream reached this refusal
9974 // on 8x16 / 16x8 strips (gate
9975 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
9976 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
9977 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
9978 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
9979 // luma/chroma transform tables, the per-unit split walk and the strip's
9980 // own neighbour records). The ONLY difference on an inter frame is the
9981 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
9982 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
9983 // this caller already read. `tx_cat` above is the same category those
9984 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
9985 // `decode_block_rect64`), asserted here so a future shape cannot drift.
9986 if bw.max(bh) == 4 * bw.min(bh) {
9987 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
9988 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
9989 let res = if bw.max(bh) == 64 {
9990 decode_block_rect64(
9991 dec,
9992 cdfs,
9993 neighbours,
9994 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
9995 bw,
9996 bh,
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),
10004 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10005 )
10006 } else {
10007 decode_block_rect4(
10008 dec,
10009 cdfs,
10010 neighbours,
10011 (mi_r, mi_c),
10012 bw,
10013 bh,
10014 None,
10015 y,
10016 u,
10017 v,
10018 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10019 allow_screen_content_tools,
10020 base_q_idx,
10021 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10022 )
10023 .map(|_| ())
10024 };
10025 fctx.intra_in_inter_mode.with(|c| c.set(None));
10026 res?;
10027 let shape = match (bw, bh) {
10028 (64, 16) => 0,
10029 (16, 64) => 1,
10030 (32, 8) => 2,
10031 _ => 3,
10032 };
10033 hit_do! {
10034 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10035 let mut v = h.get();
10036 v[shape] += 1;
10037 h.set(v);
10038 });
10039 }
10040 return Ok(());
10041 }
10042 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10043 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10044 // own, so a cross-decoder bisection could only see the block's first
10045 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10046 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10047 if step_trace {
10048 eprintln!(
10049 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10050 dec.debug_state().0
10051 );
10052 }
10053 if mode >= 13 {
10054 return Err(unsupported(
10055 "an intra mode this decoder does not code (round 2)",
10056 ));
10057 }
10058 // lane-angleinter (merged on main for the square intra-in-inter arm):
10059 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10060 // directional predictor; this arm refused a nonzero one before the merge.
10061 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10062 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10063 } else {
10064 0
10065 };
10066 if angle_delta_y != 0 {
10067 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10068 }
10069 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10070 // superblock-level strip reads the no-CFL alphabet -- the same split
10071 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10072 let cfl_allowed = bw.max(bh) <= 32;
10073 let uv_mode = if cfl_allowed {
10074 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10075 } else {
10076 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10077 };
10078 if step_trace {
10079 eprintln!(
10080 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10081 u8::from(cfl_allowed),
10082 dec.debug_state().0
10083 );
10084 }
10085 if (9..=12).contains(&uv_mode) {
10086 hit!(SMOOTH_UV_HITS);
10087 }
10088 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10089 Some(read_cfl_alphas(dec, cdfs))
10090 } else {
10091 None
10092 };
10093 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10094 DC_PRED
10095 } else {
10096 uv_mode
10097 };
10098 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10099 hit!(DIRECTIONAL_UV_HITS);
10100 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10101 } else {
10102 0
10103 };
10104 if angle_delta_uv != 0 {
10105 hit!(UV_ANGLE_DELTA_HITS);
10106 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10107 }
10108 // `read_palette_mode_info` (spec 5.11.13), in the position
10109 // `read_intra_block_mode_info` writes it: after the chroma mode and
10110 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10111 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10112 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10113 // skipping the syntax here desynced the tile at the strip's own symbol.
10114 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10115 // context and colour cache at its own mi position, and the two
10116 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10117 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10118 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10119 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10120 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10121 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10122 if allow_screen_content_tools
10123 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10124 {
10125 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10126 let use_palette_y =
10127 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10128 if use_palette_y {
10129 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10130 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10131 }
10132 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10133 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10134 let use_palette_uv =
10135 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10136 if crate::envflags::env_flag!("EC_PALSYN") {
10137 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);
10138 }
10139 if use_palette_uv {
10140 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10141 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10142 palette_uv_pending = Some((n, u_colors, v_colors));
10143 }
10144 }
10145 // lane-fiinter (merged on main for the square intra-in-inter arm):
10146 // `read_filter_intra_mode_info` is the tail of
10147 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10148 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10149 // 2:1 strips with both sides <= 32 -- their own CDF rows
10150 // ([`filter_intra_size_class_rect`]).
10151 let mut filter_intra = None;
10152 if mode == DC_PRED
10153 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10154 // `av1_filter_intra_allowed` excludes a palette-Y block.
10155 && palette_y_pending.is_none()
10156 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10157 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10158 {
10159 hit!(FILTER_INTRA_HITS);
10160 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10161 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10162 }
10163 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10164 let palette_y = palette_y_pending.map(|(n, colors)| {
10165 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
10166 hit!(PALETTE_HITS);
10167 hit!(PALETTE_RECT_HITS);
10168 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10169 PaletteY { size: n, colors, map }
10170 });
10171 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10172 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10173 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
10174 hit!(PALETTE_UV_HITS);
10175 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10176 PaletteUv { size: n, u_colors, v_colors, map }
10177 });
10178 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10179 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10180 // chroma ones -- [`decode_block_rect`]'s own pair.
10181 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10182 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10183 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10184 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10185 // one exactly as [`decode_leaf8`] already does (class
10186 // context-read-from-one-cell).
10187 let coarse_pair = neighbours.modes_above_left(r, c);
10188 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10189 if (nb_above_mode, nb_left_mode) != coarse_pair {
10190 hit!(EDGE_FILTER_MI_FIX_HITS);
10191 }
10192 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10193 if smooth_neighbor {
10194 hit!(SMOOTH_LUMA_HITS);
10195 }
10196 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10197 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10198 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
10199 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
10200 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10201 let d = match tx_cat {
10202 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10203 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10204 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10205 };
10206 if step_trace {
10207 eprintln!(
10208 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10209 dec.debug_state().0
10210 );
10211 }
10212 d
10213 } else {
10214 0
10215 };
10216 if depth != 0 {
10217 hit!(TX_DEPTH_HITS);
10218 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10219 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10220 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10221 hit_do! {
10222 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10223 let mut v = h.get();
10224 v[depth.min(2)] += 1;
10225 h.set(v);
10226 });
10227 }
10228 }
10229 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10230 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10231 // the two are indistinguishable when the diagnostic fires on splits alone.
10232 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10233 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10234 }
10235 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10236 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10237 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10238 // of an inter frame, intra ones included -- with the skip term 0 it
10239 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10240 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10241 // wrote neither, so the next block's var-tx `txfm_partition` context read
10242 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10243 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10244 // mi(16,0) and desyncing the tile at that symbol.
10245 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10246 let modes = RectStripModes {
10247 skip,
10248 mode,
10249 angle_delta_y,
10250 uv_predict_mode,
10251 angle_delta_uv,
10252 alpha,
10253 filter_intra,
10254 smooth_neighbor,
10255 smooth_neighbor_uv,
10256 palette_y: palette_y
10257 .as_ref()
10258 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10259 palette_uv: palette_uv.as_ref().map(|p| {
10260 (
10261 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10262 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10263 )
10264 }),
10265 };
10266 decode_rect_split(
10267 dec,
10268 cdfs,
10269 neighbours,
10270 (mi_r, mi_c),
10271 bw,
10272 bh,
10273 tx_w,
10274 tx_h,
10275 &modes,
10276 y,
10277 u,
10278 v,
10279 base_q_idx,
10280 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10281 )?;
10282 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
10283 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
10284 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
10285 // left column over its height. This arm wrote neither before lane-intrasplit
10286 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
10287 // context across the strip's footprint.
10288 for i in 0..bw / MI {
10289 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10290 *cell = tx_w as u8;
10291 }
10292 }
10293 for i in 0..bh / MI {
10294 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10295 *cell = tx_h as u8;
10296 }
10297 }
10298 // The strip's own palette state into the mi-granular neighbour bands, so
10299 // the next block's colour cache and `palette_y_mode` context are libaom's.
10300 record_strip_palette(
10301 neighbours,
10302 (mi_r, mi_c),
10303 bw,
10304 bh,
10305 palette_y.as_ref().map_or(0, |p| p.size),
10306 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
10307 palette_uv.as_ref().map_or(0, |p| p.size),
10308 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
10309 );
10310 let class = match bw.max(bh) {
10311 64 => 0,
10312 32 => 1,
10313 _ => 2,
10314 };
10315 hit_do! {
10316 INTRA_RECT_IN_INTER_HITS.with(|h| {
10317 let mut v = h.get();
10318 v[class] += 1;
10319 h.set(v);
10320 });
10321 }
10322 Ok(())
10323}
10324
10325/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
10326/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
10327/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
10328/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
10329/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
10330/// has no rectangular-transform coefficient reader, and a chroma plane here
10331/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
10332/// with no depth-based square-tiling escape the way luma's own resolved
10333/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
10334/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
10335#[allow(clippy::too_many_arguments)]
10336fn decode_block_rect(
10337 dec: &mut SymbolDecoder,
10338 cdfs: &mut Cdfs,
10339 neighbours: &mut Neighbours,
10340 at: (usize, usize),
10341 bw: usize,
10342 bh: usize,
10343 y: &mut PlaneBuf<'static>,
10344 u: &mut PlaneBuf<'static>,
10345 v: &mut PlaneBuf<'static>,
10346 enable_filter_intra: bool,
10347 allow_screen_content_tools: bool,
10348 base_q_idx: u8,
10349 tx_select: bool,
10350 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10351) -> Result<()> {
10352 let (r, c) = at;
10353 let (px, py) = (c * SUB, r * SUB);
10354 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10355 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10356 let palette_uv_cache = neighbours.palette_uv_cache(at);
10357 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10358 read_intra_mode_rect(
10359 dec,
10360 cdfs,
10361 nb_above_mode,
10362 nb_left_mode,
10363 true,
10364 true,
10365 bw,
10366 bh,
10367 enable_filter_intra,
10368 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10369 allow_screen_content_tools,
10370 Some((palette_ctx, &palette_cache)),
10371 &palette_uv_cache,
10372 r * (SUB / MI),
10373 c * (SUB / MI), fctx,
10374 )?;
10375 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10376 if smooth_neighbor {
10377 hit!(SMOOTH_LUMA_HITS);
10378 }
10379 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
10380 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
10381 // `uv_mode`, not the luma one.
10382 let smooth_neighbor_uv =
10383 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10384 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
10385 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
10386 // rectangle just as happily), so a `use_filter_intra` strip at this level
10387 // predicts instead of refusing. The below-16x16 leaf arm
10388 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
10389 if filter_intra.is_some() {
10390 hit!(FILTER_INTRA_RECT_HITS);
10391 }
10392 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10393 DC_PRED
10394 } else {
10395 uv_mode
10396 };
10397 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10398 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
10399 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
10400 // one did not, so with `--enable-tx-size-search=0` -- which several gate
10401 // recipes use -- the decoder consumed a symbol the encoder never wrote and
10402 // desynced the tile from that point on. That is why both strips of the
10403 // pinned HORZ quadrant were wrong from their very first pixel, and why our
10404 // range after the read equalled the oracle's range for the whole block.
10405 let depth = if tx_select {
10406 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10407 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10408 // the 16x4 intra-in-inter strips already do); the key frame's
10409 // deblock-grid approximation is only right where those bands were never
10410 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10411 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10412 // `tx_size_cat2` row 1 where libaom reads row 2.
10413 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10414 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10415 } else {
10416 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10417 };
10418 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10419 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10420 eprintln!(
10421 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10422 dec.debug_state().0
10423 );
10424 }
10425 d
10426 } else {
10427 0
10428 };
10429 if depth != 0 {
10430 hit!(TX_DEPTH_HITS);
10431 // lane-rectsplit r1: a split transform is predicted and reconstructed
10432 // per transform unit, each unit taking its edges from the previous
10433 // unit's reconstruction inside this same strip (spec 5.11.36) --
10434 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10435 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10436 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10437 eprintln!(
10438 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10439 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10440 angle_y={angle_delta_y}"
10441 );
10442 }
10443 let modes = RectStripModes {
10444 skip,
10445 mode,
10446 angle_delta_y,
10447 uv_predict_mode,
10448 angle_delta_uv,
10449 alpha,
10450 filter_intra,
10451 smooth_neighbor,
10452 smooth_neighbor_uv,
10453 palette_y: palette_y
10454 .as_ref()
10455 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10456 palette_uv: palette_uv.as_ref().map(|p| {
10457 (
10458 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10459 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10460 )
10461 }),
10462 };
10463 if palette_y.is_some() || palette_uv.is_some() {
10464 hit!(PALETTE_SPLIT_TX_HITS);
10465 }
10466 decode_rect_split(
10467 dec,
10468 cdfs,
10469 neighbours,
10470 (mi_r, mi_c),
10471 bw,
10472 bh,
10473 tx_w,
10474 tx_h,
10475 &modes,
10476 y,
10477 u,
10478 v,
10479 base_q_idx,
10480 reduced_tx_set, fctx,
10481 )?;
10482 // This early return skips this fn's own tail, so the palette
10483 // neighbour state has to be stamped HERE too: without it a split-tx
10484 // strip left the above/left palette arrays holding a DEAD block's
10485 // colours, and the next block's colour cache
10486 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
10487 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
10488 // and only those pixels were wrong (lane-palette2 r10).
10489 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10490 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10491 let (puv_size, puv_colors) =
10492 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10493 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10494 hit!(RECT_PARTITION_HITS);
10495 return Ok(());
10496 }
10497 let (tx_w, tx_h) = (bw, bh);
10498 let (cpx, cpy) = (px / 2, py / 2);
10499 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10500 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10501 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10502 let (rng, _) = dec.debug_state();
10503 eprintln!(
10504 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
10505 skip={} tx={depth} rng={rng}",
10506 skip as i32
10507 );
10508 }
10509 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
10510 // block's prediction is the reconstructed colour-index map, set fresh
10511 // right before each `reconstruct_rect` call below (lane-palette2 r4).
10512 if let Some(ref pyv) = palette_y {
10513 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10514 set_palette_pred(buf, fctx);
10515 }
10516 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10517 (
10518 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10519 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10520 )
10521 });
10522 if skip {
10523 push_intra_rect(0,
10524 px,
10525 py,
10526 bw,
10527 bh,
10528 mode,
10529 angle_delta_y,
10530 reach,
10531 &ZERO_RESIDUAL[..bw * bh],
10532 None,
10533 filter_intra,
10534 smooth_neighbor, fctx,
10535 );
10536 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10537 if let Some((ub, _)) = &palette_uv_bufs {
10538 set_palette_pred(ub.clone(), fctx);
10539 }
10540 push_intra_rect(1,
10541 cpx,
10542 cpy,
10543 chroma_w,
10544 chroma_h,
10545 uv_predict_mode,
10546 angle_delta_uv,
10547 reach,
10548 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10549 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10550 None,
10551 smooth_neighbor_uv, fctx,
10552 );
10553 if let Some((_, vb)) = &palette_uv_bufs {
10554 set_palette_pred(vb.clone(), fctx);
10555 }
10556 push_intra_rect(2,
10557 cpx,
10558 cpy,
10559 chroma_w,
10560 chroma_h,
10561 uv_predict_mode,
10562 angle_delta_uv,
10563 reach,
10564 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10565 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10566 None,
10567 smooth_neighbor_uv, fctx,
10568 );
10569 neighbours.record_rect(
10570 at,
10571 bw,
10572 bh,
10573 mode,
10574 uv_predict_mode,
10575 &[
10576 &ZERO_RESIDUAL[..bw * bh],
10577 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10578 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10579 ],
10580 );
10581 } else {
10582 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
10583 // reduces both size pairs to their square-up CDF sets
10584 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
10585 // doc comments); the scan order and 2D context tables are the real
10586 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
10587 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
10588 (&SCAN_32X16, &SCAN_16X8)
10589 } else {
10590 (&SCAN_16X32, &SCAN_8X16)
10591 };
10592 // lane-rectwire r3: real coefficients desync a pixel-exact gate
10593 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
10594 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
10595 // pixel (not a subtle context-table off-by-one), while the sibling
10596 // non-rect quadrants of the same frame match. Range-ladder bisection
10597 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
10598 // but the intra key-frame path has no traced symbol between the
10599 // partition read and the first coefficient block (mode/skip/tx_depth
10600 // reads are all untraced in libaom's decodeframe.c intra path, unlike
10601 // the inter EC_TRACE_MODE this round added), so a same-length range
10602 // comparison wasn't reachable within budget -- see
10603 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10604 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10605 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10606 // libaom and match). lane-rectwire r4: range-ladder against the
10607 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10608 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10609 // both confirmed in sync -- rng=58692 on both sides right after
10610 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10611 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10612 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10613 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
10614 // its own tx_size read) unless oracle's tx symbol is a near-certainty
10615 // CDF that barely narrows the range -- i.e. this decoder's
10616 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
10617 // a 32x16/16x32 strip is the first diverging symbol, not the
10618 // coefficient-context math r3 already cleared. Not confirmed byte-
10619 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
10620 // `read_tx_size`'s own rng, not attempted this round -- budget), so
10621 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
10622 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
10623 // it unconditionally where both square paths gate on `tx_select`. With
10624 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
10625 // decoder consumed one that was never there.
10626 {
10627 let around = neighbours.around_rect(at, bw, bh);
10628 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
10629 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10630 dec,
10631 &mut luma_coding,
10632 luma_scan,
10633 bw,
10634 bh,
10635 0,
10636 dc_sign_ctx(around[0].2),
10637 TxType::DctDct,
10638 )?;
10639 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10640 let (rng, _) = dec.debug_state();
10641 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10642 }
10643 let luma_residual = dequant_and_inverse_typed_wh(
10644 &luma_levels,
10645 bw,
10646 bh,
10647 crate::decode::bit_depth(fctx),
10648 block_q_idx(fctx),
10649 plane_q_delta(0, fctx).0,
10650 plane_q_delta(0, fctx).1,
10651 luma_tx_type,
10652 );
10653 push_intra_rect(0,
10654 px,
10655 py,
10656 bw,
10657 bh,
10658 mode,
10659 angle_delta_y,
10660 reach,
10661 &luma_residual,
10662 None,
10663 filter_intra,
10664 smooth_neighbor, fctx,
10665 );
10666 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10667 if let Some((ub, _)) = &palette_uv_bufs {
10668 set_palette_pred(ub.clone(), fctx);
10669 }
10670 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10671 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10672 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10673 let (u_levels, u_tx_type) = read_coeffs_rect(
10674 dec,
10675 &mut u_coding,
10676 chroma_scan,
10677 chroma_w,
10678 chroma_h,
10679 u_skip_ctx,
10680 dc_sign_ctx(around[1].2),
10681 u_default_tx,
10682 )?;
10683 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10684 let (rng, _) = dec.debug_state();
10685 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10686 }
10687 let u_residual = dequant_and_inverse_typed_wh(
10688 &u_levels,
10689 chroma_w,
10690 chroma_h,
10691 crate::decode::bit_depth(fctx),
10692 block_q_idx(fctx),
10693 plane_q_delta(1, fctx).0,
10694 plane_q_delta(1, fctx).1,
10695 u_tx_type,
10696 );
10697 push_intra_rect(1,
10698 cpx,
10699 cpy,
10700 chroma_w,
10701 chroma_h,
10702 uv_predict_mode,
10703 angle_delta_uv,
10704 reach,
10705 &u_residual,
10706 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10707 None,
10708 smooth_neighbor_uv, fctx,
10709 );
10710 if let Some((_, vb)) = &palette_uv_bufs {
10711 set_palette_pred(vb.clone(), fctx);
10712 }
10713 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10714 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10715 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10716 let (v_levels, v_tx_type) = read_coeffs_rect(
10717 dec,
10718 &mut v_coding,
10719 chroma_scan,
10720 chroma_w,
10721 chroma_h,
10722 v_skip_ctx,
10723 dc_sign_ctx(around[2].2),
10724 v_default_tx,
10725 )?;
10726 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10727 let (rng, _) = dec.debug_state();
10728 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10729 }
10730 let v_residual = dequant_and_inverse_typed_wh(
10731 &v_levels,
10732 chroma_w,
10733 chroma_h,
10734 crate::decode::bit_depth(fctx),
10735 block_q_idx(fctx),
10736 plane_q_delta(2, fctx).0,
10737 plane_q_delta(2, fctx).1,
10738 v_tx_type,
10739 );
10740 push_intra_rect(2,
10741 cpx,
10742 cpy,
10743 chroma_w,
10744 chroma_h,
10745 uv_predict_mode,
10746 angle_delta_uv,
10747 reach,
10748 &v_residual,
10749 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10750 None,
10751 smooth_neighbor_uv, fctx,
10752 );
10753 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
10754 hit!(RECT_COEFF_HITS);
10755 }
10756 }
10757 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10758 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10759 let (puv_size, puv_colors) =
10760 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10761 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10762 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10763 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10764 hit!(RECT_PARTITION_HITS);
10765 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10766 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
10767 }
10768 Ok(())
10769}
10770
10771/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
10772/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
10773/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
10774/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
10775/// the second strip of a HORZ/VERT split sits offset by half the 16x16
10776/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
10777/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
10778/// previous strip is directly above (same column, `mi_h` rows up) or
10779/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
10780/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
10781/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
10782/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
10783/// this strip's real position, never the coarse `record_rect` (which the
10784/// caller uses once, after both strips, exactly like the `VERT_B` arm next
10785/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
10786/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
10787/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
10788/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
10789#[allow(clippy::too_many_arguments)]
10790fn decode_leaf_rect(
10791 dec: &mut SymbolDecoder,
10792 cdfs: &mut Cdfs,
10793 neighbours: &mut Neighbours,
10794 outer_at: (usize, usize),
10795 leaf_mi: (usize, usize),
10796 bw: usize,
10797 bh: usize,
10798 prev_leaf: Option<((usize, usize), usize)>,
10799 y: &mut PlaneBuf<'static>,
10800 u: &mut PlaneBuf<'static>,
10801 v: &mut PlaneBuf<'static>,
10802 enable_filter_intra: bool,
10803 allow_screen_content_tools: bool,
10804 base_q_idx: u8,
10805 tx_select: bool,
10806 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10807) -> Result<usize> {
10808 let _ = base_q_idx;
10809 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10810 eprintln!(
10811 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
10812 dec.debug_state().0
10813 );
10814 }
10815 let (r, c) = outer_at;
10816 let mut above_mode = neighbours.above_mode[c];
10817 let mut left_mode = neighbours.left_mode[r];
10818 let (mi_w, mi_h) = (bw / MI, bh / MI);
10819 if let Some(((pr, pc), pmode)) = prev_leaf {
10820 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
10821 above_mode = pmode;
10822 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
10823 left_mode = pmode;
10824 }
10825 }
10826 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
10827 // cannot hold the modes a split (or a pair of strips) leaves behind, so
10828 // when the map holds the block at exactly this strip's above/left mi it
10829 // is the neighbour libaom's `above_mi`/`left_mi` reads.
10830 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
10831 // availability-correct -- four 16x8 strips share one coarse 16x16
10832 // `left_mode` cell too, so the fallback must not stand in for an absent
10833 // tile-edge neighbour.
10834 let (above_mode, left_mode) =
10835 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
10836 let smooth_neighbor =
10837 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10838 if smooth_neighbor {
10839 hit!(SMOOTH_LUMA_HITS);
10840 }
10841 // The palette-Y mode CDF row is picked by the neighbours' palette use
10842 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
10843 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
10844 // a palette narrows the wrong interval and desyncs the tile even when the
10845 // decoded bit is the same. The cell is the 16px-SUB cell containing the
10846 // leaf (the palette neighbour arrays have no finer granularity).
10847 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
10848 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
10849 // exclusion and the neighbour palette lookup itself are mi-granular
10850 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
10851 let pal_at = leaf_mi;
10852 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
10853 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
10854 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10855 read_intra_mode_rect(
10856 dec,
10857 cdfs,
10858 above_mode,
10859 left_mode,
10860 true,
10861 true,
10862 bw,
10863 bh,
10864 enable_filter_intra,
10865 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
10866 allow_screen_content_tools,
10867 Some((palette_ctx, &palette_cache)),
10868 &palette_uv_cache,
10869 leaf_mi.0,
10870 leaf_mi.1, fctx,
10871 )?;
10872 // lane-kf900 r4: palette prediction on this shape, the same colour-index
10873 // map -> base colours buffer [`decode_block_rect`] hands each
10874 // `reconstruct_rect` through [`set_palette_pred`].
10875 if palette_y.is_some() || palette_uv.is_some() {
10876 hit!(RECT4_PALETTE_HITS);
10877 }
10878 let palette_y_buf: Option<Vec<u16>> = palette_y
10879 .as_ref()
10880 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
10881 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
10882 (
10883 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10884 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10885 )
10886 });
10887 let (pal_y_size, pal_y_colors) =
10888 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10889 let (pal_uv_size, pal_uv_colors) =
10890 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10891 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10892 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
10893 }
10894 if filter_intra.is_some() {
10895 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
10896 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
10897 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
10898 // below already makes; this refusal was square-only prose.
10899 hit!(FILTER_INTRA_RECT_HITS);
10900 hit!(FILTER_INTRA_RECT_SUB16_HITS);
10901 }
10902 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
10903 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
10904 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
10905 // a constant `false`.
10906 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
10907 let depth = if tx_select {
10908 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
10909 // every other rect reader now does -- a no-op on a key frame.
10910 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10911 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
10912 } else {
10913 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
10914 };
10915 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
10916 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
10917 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
10918 // count (3), different CDF row: a wrong-table read of a real symbol,
10919 // the class that cost lane-rectsplit r1 its 64x32 depth.
10920 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
10921 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
10922 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
10923 // function also decodes) sit at depth 2, so they read
10924 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
10925 // while `tx_size_cat2` belongs to the 32-level shapes
10926 // ([`decode_block_rect`]). Both tables carry three symbols, so the
10927 // wrong one decodes a plausible depth from the wrong probabilities:
10928 // the range diverges silently at the first such leaf and every later
10929 // symbol in the tile is read from the wrong place (class
10930 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
10931 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
10932 } else {
10933 0
10934 };
10935 if depth != 0 {
10936 // The same per-transform-unit walk the bigger strips take
10937 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
10938 // depth 2), addressed at this leaf's own mi position.
10939 hit!(TX_DEPTH_HITS);
10940 hit!(SUB16_SPLIT_HITS);
10941 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10942 let modes = RectStripModes {
10943 skip,
10944 mode,
10945 angle_delta_y,
10946 uv_predict_mode,
10947 angle_delta_uv,
10948 alpha,
10949 filter_intra,
10950 smooth_neighbor,
10951 // lane-rectsplitx r3: the split arm hard-coded `false` here while
10952 // the unsplit arm below passes the real neighbour answer -- chroma
10953 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
10954 smooth_neighbor_uv,
10955 palette_y: palette_y_buf.clone(),
10956 palette_uv: palette_uv_bufs.clone(),
10957 };
10958 if palette_y.is_some() || palette_uv.is_some() {
10959 hit!(PALETTE_SPLIT_TX_HITS);
10960 }
10961 decode_rect_split(
10962 dec,
10963 cdfs,
10964 neighbours,
10965 leaf_mi,
10966 bw,
10967 bh,
10968 tx_w,
10969 tx_h,
10970 &modes,
10971 y,
10972 u,
10973 v,
10974 base_q_idx,
10975 reduced_tx_set, fctx,
10976 )?;
10977 record_strip_palette(
10978 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10979 );
10980 return Ok(mode);
10981 }
10982 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
10983 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10984 let (cpx, cpy) = (px / 2, py / 2);
10985 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10986 let (luma_levels, u_levels, v_levels);
10987 if skip {
10988 luma_levels = Grid::Zero(bw * bh);
10989 u_levels = Grid::Zero(chroma_w * chroma_h);
10990 v_levels = Grid::Zero(chroma_w * chroma_h);
10991 if let Some(b) = &palette_y_buf {
10992 set_palette_pred(b.clone(), fctx);
10993 }
10994 push_intra_rect(0,
10995 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
10996 smooth_neighbor, fctx,
10997 );
10998 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10999 if let Some((ub, _)) = &palette_uv_bufs {
11000 set_palette_pred(ub.clone(), fctx);
11001 }
11002 push_intra_rect(1,
11003 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
11004 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11005 );
11006 if let Some((_, vb)) = &palette_uv_bufs {
11007 set_palette_pred(vb.clone(), fctx);
11008 }
11009 push_intra_rect(2,
11010 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
11011 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11012 );
11013 } else {
11014 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
11015 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
11016 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
11017 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
11018 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
11019 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
11020 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
11021 (&SCAN_16X8, &SCAN_8X4)
11022 } else {
11023 (&SCAN_8X16, &SCAN_4X8)
11024 };
11025 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
11026 let luma_set = if reduced_tx_set {
11027 TxbSet::LumaRect16x8
11028 } else {
11029 TxbSet::LumaRect16x8Set1
11030 };
11031 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
11032 let (l_levels, luma_tx_type) = read_coeffs_rect(
11033 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
11034 )?;
11035 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11036 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
11037 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
11038 }
11039 luma_levels = l_levels;
11040 let luma_residual = dequant_and_inverse_typed_wh(
11041 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
11042 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
11043 );
11044 if let Some(b) = &palette_y_buf {
11045 set_palette_pred(b.clone(), fctx);
11046 }
11047 push_intra_rect(0,
11048 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
11049 smooth_neighbor, fctx,
11050 );
11051 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11052 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11053 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11054 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11055 let (u_l, u_tx_type) = read_coeffs_rect(
11056 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11057 dc_sign_ctx(around[1].2), u_default_tx,
11058 )?;
11059 u_levels = u_l;
11060 let u_residual = dequant_and_inverse_typed_wh(
11061 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11062 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
11063 );
11064 if let Some((ub, _)) = &palette_uv_bufs {
11065 set_palette_pred(ub.clone(), fctx);
11066 }
11067 push_intra_rect(1,
11068 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
11069 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11070 );
11071 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11072 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11073 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11074 let (v_l, v_tx_type) = read_coeffs_rect(
11075 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11076 dc_sign_ctx(around[2].2), v_default_tx,
11077 )?;
11078 v_levels = v_l;
11079 let v_residual = dequant_and_inverse_typed_wh(
11080 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11081 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
11082 );
11083 if let Some((_, vb)) = &palette_uv_bufs {
11084 set_palette_pred(vb.clone(), fctx);
11085 }
11086 push_intra_rect(2,
11087 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
11088 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11089 );
11090 hit!(RECT_LEAF_COEFF_HITS);
11091 }
11092 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11093 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
11094 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11095 // The leaf's own palette state (`0` clears, as this site always did
11096 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
11097 // AXIS only until the pair's closing leaf: the coarse cell holds one
11098 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
11099 // real left neighbour leaf 1 reads (lane-kf900 r4).
11100 record_strip_palette(
11101 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11102 );
11103 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
11104 // rows -- record the whole span, not one cell.
11105 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
11106 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
11107 Ok(mode)
11108}
11109
11110/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
11111/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
11112/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
11113/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
11114/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
11115/// strip's mode so this one's mode context sees its true above/left
11116/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
11117///
11118/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
11119/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
11120/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
11121/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
11122/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
11123/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
11124/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
11125///
11126/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
11127/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
11128/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
11129/// unexamined.
11130#[allow(clippy::too_many_arguments)]
11131fn decode_block_rect4(
11132 dec: &mut SymbolDecoder,
11133 cdfs: &mut Cdfs,
11134 neighbours: &mut Neighbours,
11135 strip_mi: (usize, usize),
11136 bw: usize,
11137 bh: usize,
11138 prev_strip: Option<((usize, usize), usize)>,
11139 y: &mut PlaneBuf<'static>,
11140 u: &mut PlaneBuf<'static>,
11141 v: &mut PlaneBuf<'static>,
11142 enable_filter_intra: bool,
11143 allow_screen_content_tools: bool,
11144 base_q_idx: u8,
11145 tx_select: bool, fctx: &crate::decode::FrameCtx,
11146) -> Result<(usize, usize)> {
11147 let _ = base_q_idx;
11148 let (mi_r, mi_c) = strip_mi;
11149 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11150 let (mi_w, mi_h) = (bw / MI, bh / MI);
11151 let mut above_mode = neighbours.above_mode[c];
11152 let mut left_mode = neighbours.left_mode[r];
11153 if let Some(((pr, pc), pmode)) = prev_strip {
11154 if pc == mi_c && mi_r == pr + mi_h {
11155 above_mode = pmode;
11156 } else if pr == mi_r && mi_c == pc + mi_w {
11157 left_mode = pmode;
11158 }
11159 }
11160 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
11161 // availability-correct neighbour modes (see
11162 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
11163 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
11164 let (above_mode, left_mode) =
11165 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
11166 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
11167 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
11168 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
11169 // wrong interval, so a screen-content tile desynced at the first strip
11170 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
11171 let pal_at = (mi_r, mi_c);
11172 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11173 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11174 let (
11175 skip,
11176 mode,
11177 angle_delta_y,
11178 uv_mode,
11179 angle_delta_uv,
11180 alpha,
11181 filter_intra,
11182 palette_y,
11183 palette_uv,
11184 ) = read_intra_mode_rect(
11185 dec,
11186 cdfs,
11187 above_mode,
11188 left_mode,
11189 true,
11190 true,
11191 bw,
11192 bh,
11193 enable_filter_intra,
11194 neighbours.skip_txfm_ctx(mi_r, mi_c),
11195 allow_screen_content_tools,
11196 Some((palette_ctx, &palette_cache)),
11197 &palette_uv_cache,
11198 mi_r,
11199 mi_c, fctx,
11200 )?;
11201 // lane-kf900 r4: palette prediction on this shape, exactly as
11202 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
11203 // mapped through the base colours IS the prediction (it reads no edge
11204 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
11205 if palette_y.is_some() || palette_uv.is_some() {
11206 hit!(RECT4_PALETTE_HITS);
11207 }
11208 let palette_y_buf: Option<Vec<u16>> = palette_y
11209 .as_ref()
11210 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11211 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11212 (
11213 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11214 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11215 )
11216 });
11217 let (pal_y_size, pal_y_colors) =
11218 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11219 let (pal_uv_size, pal_uv_colors) =
11220 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11221 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11222 if smooth_neighbor {
11223 hit!(SMOOTH_LUMA_HITS);
11224 }
11225 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
11226 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
11227 // `r * (SUB / MI)` names a different mi column and the chroma
11228 // edge-filter strength was read from the wrong neighbour (measured:
11229 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
11230 // with luma bit-exact).
11231 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11232 if filter_intra.is_some() {
11233 hit!(FILTER_INTRA_RECT_HITS);
11234 if bw > bh {
11235 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
11236 } else {
11237 hit!(FILTER_INTRA_RECT4_VERT_HITS);
11238 }
11239 }
11240 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11241 DC_PRED
11242 } else {
11243 uv_mode
11244 };
11245 let depth = if tx_select {
11246 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11247 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11248 // the 16x4 intra-in-inter strips already do); the key frame's
11249 // deblock-grid approximation is only right where those bands were never
11250 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11251 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11252 // `tx_size_cat2` row 1 where libaom reads row 2.
11253 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11254 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11255 } else {
11256 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11257 };
11258 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11259 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11260 eprintln!(
11261 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11262 dec.debug_state().0
11263 );
11264 }
11265 d
11266 } else {
11267 0
11268 };
11269 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11270 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11271 publish_txfm_bands_if_in_inter(
11272 neighbours,
11273 (mi_r, mi_c),
11274 depth_to_tx_wh(bw, bh, depth),
11275 (bw, bh), fctx,
11276 );
11277 if depth != 0 {
11278 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
11279 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
11280 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
11281 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
11282 // both interleave in every real stream.
11283 hit!(TX_DEPTH_HITS);
11284 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11285 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
11286 // predicted -- depth 1 fires FIRST in every attempt that splits at
11287 // all, so a depth-2-only lift could never be gated. The r1 mismatch
11288 // was never the rect unit: it was the neighbour MODE the strip reads
11289 // (see `modes_above_left_mi`).
11290 let which = if depth == 1 {
11291 &RECT4_SPLIT_DEPTH1_HITS
11292 } else {
11293 &RECT4_SPLIT_DEPTH2_HITS
11294 };
11295 hit_do! { which.with(|c| c.set(c.get() + 1)); }
11296 let modes = RectStripModes {
11297 skip,
11298 mode,
11299 angle_delta_y,
11300 uv_predict_mode,
11301 angle_delta_uv,
11302 alpha,
11303 filter_intra,
11304 smooth_neighbor,
11305 smooth_neighbor_uv,
11306 palette_y: palette_y_buf.clone(),
11307 palette_uv: palette_uv_bufs.clone(),
11308 };
11309 if palette_y.is_some() || palette_uv.is_some() {
11310 hit!(PALETTE_SPLIT_TX_HITS);
11311 }
11312 decode_rect_split(
11313 dec,
11314 cdfs,
11315 neighbours,
11316 (mi_r, mi_c),
11317 bw,
11318 bh,
11319 tx_w,
11320 tx_h,
11321 &modes,
11322 y,
11323 u,
11324 v,
11325 base_q_idx,
11326 false, fctx,
11327 )?;
11328 record_strip_palette(
11329 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11330 pal_uv_colors,
11331 );
11332 if bw > bh {
11333 hit!(RECT4_32_HORZ_HITS);
11334 } else {
11335 hit!(RECT4_32_VERT_HITS);
11336 }
11337 if !skip {
11338 hit!(RECT4_COEFF_HITS);
11339 }
11340 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11341 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11342 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11343 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11344 // transform size in both TXFM_CONTEXT bands. Without it the next block
11345 // reads the row's stale value.
11346 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11347 return Ok((mode, uv_predict_mode));
11348 }
11349 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
11350 // that is 8 px tall, so each strip stamps every cell it touches and the
11351 // LAST strip wins -- which is the right answer for the block below/right
11352 // of the 32x32, the only reader outside it. Written after this strip's
11353 // own context read above, never before.
11354 for cell in 0..bw.div_ceil(SUB) {
11355 neighbours.above_mode[c + cell] = mode;
11356 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
11357 neighbours.above_side[c + cell] = bw;
11358 }
11359 for cell in 0..bh.div_ceil(SUB) {
11360 neighbours.left_mode[r + cell] = mode;
11361 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
11362 neighbours.left_side[r + cell] = bh;
11363 }
11364 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
11365 // [`decode_leaf_rect`] does (the split arm above records these through
11366 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
11367 // `sub8_mode_row` holding the previous block, and the next 32x32's
11368 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
11369 // fixture).
11370 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
11371 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
11372 let (px, py) = (mi_c * MI, mi_r * MI);
11373 let (cpx, cpy) = (px / 2, py / 2);
11374 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11375 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11376 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
11377 (&SCAN_32X8, &SCAN_16X4)
11378 } else {
11379 (&SCAN_8X32, &SCAN_4X16)
11380 };
11381 let (luma_levels, u_levels, v_levels) = if skip {
11382 (
11383 vec![0i32; bw * bh],
11384 vec![0i32; chroma_w * chroma_h],
11385 vec![0i32; chroma_w * chroma_h],
11386 )
11387 } else {
11388 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11389 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
11390 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11391 dec,
11392 &mut luma_coding,
11393 luma_scan,
11394 bw,
11395 bh,
11396 0,
11397 dc_sign_ctx(around[0].2),
11398 TxType::DctDct,
11399 )?;
11400 let mut planes = Vec::with_capacity(2);
11401 for plane in 1..3 {
11402 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11403 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11404 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11405 let (levels, tx_type) = read_coeffs_rect(
11406 dec,
11407 &mut coding,
11408 chroma_scan,
11409 chroma_w,
11410 chroma_h,
11411 skip_ctx,
11412 dc_sign_ctx(around[plane].2),
11413 default_tx,
11414 )?;
11415 planes.push((levels, tx_type));
11416 }
11417 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11418 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11419 hit!(RECT4_COEFF_HITS);
11420 let luma_residual = dequant_and_inverse_typed_wh(
11421 &luma_levels,
11422 bw,
11423 bh,
11424 crate::decode::bit_depth(fctx),
11425 block_q_idx(fctx),
11426 plane_q_delta(0, fctx).0,
11427 plane_q_delta(0, fctx).1,
11428 luma_tx_type,
11429 );
11430 if let Some(b) = &palette_y_buf {
11431 set_palette_pred(b.clone(), fctx);
11432 }
11433 push_intra_rect(0,
11434 px,
11435 py,
11436 bw,
11437 bh,
11438 mode,
11439 angle_delta_y,
11440 reach,
11441 &luma_residual,
11442 None,
11443 filter_intra,
11444 smooth_neighbor, fctx,
11445 );
11446 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11447 for (plane, _buf, levels, tx_type) in [
11448 (1usize, &mut *u, &u_levels, u_tx_type),
11449 (2, &mut *v, &v_levels, v_tx_type),
11450 ] {
11451 let residual = dequant_and_inverse_typed_wh(
11452 levels,
11453 chroma_w,
11454 chroma_h,
11455 crate::decode::bit_depth(fctx),
11456 block_q_idx(fctx),
11457 plane_q_delta(plane, fctx).0,
11458 plane_q_delta(plane, fctx).1,
11459 tx_type,
11460 );
11461 if let Some((ub, vb)) = &palette_uv_bufs {
11462 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11463 }
11464 push_intra_rect(plane,
11465 cpx,
11466 cpy,
11467 chroma_w,
11468 chroma_h,
11469 uv_predict_mode,
11470 angle_delta_uv,
11471 reach,
11472 &residual,
11473 alpha
11474 .zip(ac)
11475 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11476 None,
11477 smooth_neighbor_uv, fctx,
11478 );
11479 }
11480 neighbours.record_mi_rect(
11481 (mi_r, mi_c),
11482 bw,
11483 bh,
11484 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
11485 );
11486 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11487 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11488 record_strip_palette(
11489 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11490 pal_uv_colors,
11491 );
11492 if bw > bh {
11493 hit!(RECT4_32_HORZ_HITS);
11494 } else {
11495 hit!(RECT4_32_VERT_HITS);
11496 }
11497 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11498 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11499 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11500 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11501 // transform size in both TXFM_CONTEXT bands. Without it the next block
11502 // reads the row's stale value.
11503 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11504 return Ok((mode, uv_predict_mode));
11505 };
11506 if let Some(b) = &palette_y_buf {
11507 set_palette_pred(b.clone(), fctx);
11508 }
11509 push_intra_rect(0,
11510 px,
11511 py,
11512 bw,
11513 bh,
11514 mode,
11515 angle_delta_y,
11516 reach,
11517 &luma_levels,
11518 None,
11519 filter_intra,
11520 smooth_neighbor, fctx,
11521 );
11522 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11523 if let Some((ub, _)) = &palette_uv_bufs {
11524 set_palette_pred(ub.clone(), fctx);
11525 }
11526 push_intra_rect(1,
11527 cpx,
11528 cpy,
11529 chroma_w,
11530 chroma_h,
11531 uv_predict_mode,
11532 angle_delta_uv,
11533 reach,
11534 &u_levels,
11535 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11536 None,
11537 smooth_neighbor_uv, fctx,
11538 );
11539 if let Some((_, vb)) = &palette_uv_bufs {
11540 set_palette_pred(vb.clone(), fctx);
11541 }
11542 push_intra_rect(2,
11543 cpx,
11544 cpy,
11545 chroma_w,
11546 chroma_h,
11547 uv_predict_mode,
11548 angle_delta_uv,
11549 reach,
11550 &v_levels,
11551 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11552 None,
11553 smooth_neighbor_uv, fctx,
11554 );
11555 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11556 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11557 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11558 record_strip_palette(
11559 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11560 );
11561 if bw > bh {
11562 hit!(RECT4_32_HORZ_HITS);
11563 } else {
11564 hit!(RECT4_32_VERT_HITS);
11565 }
11566 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11567 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11568 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11569 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11570 // transform size in both TXFM_CONTEXT bands. Without it the next block
11571 // reads the row's stale value.
11572 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11573 Ok((mode, uv_predict_mode))
11574}
11575
11576/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
11577/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
11578/// down, and the first shape here whose luma block is a single mi row (or
11579/// column).
11580///
11581/// What is new at this size is CHROMA. `is_chroma_reference`
11582/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
11583/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
11584/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
11585/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
11586/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
11587/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
11588/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
11589///
11590/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
11591/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
11592/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
11593/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
11594/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
11595/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
11596/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
11597/// shape's own CDF row.
11598///
11599/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
11600/// refuses by name rather than guess-decode.
11601#[allow(clippy::too_many_arguments)]
11602fn decode_rect4_16(
11603 dec: &mut SymbolDecoder,
11604 cdfs: &mut Cdfs,
11605 neighbours: &mut Neighbours,
11606 at16: (usize, usize),
11607 horz: bool,
11608 y: &mut PlaneBuf<'static>,
11609 u: &mut PlaneBuf<'static>,
11610 v: &mut PlaneBuf<'static>,
11611 enable_filter_intra: bool,
11612 allow_screen_content_tools: bool,
11613 base_q_idx: u8,
11614 tx_select: bool,
11615 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11616) -> Result<()> {
11617 let (r, c) = at16;
11618 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
11619 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
11620 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
11621 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11622 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11623 let mut prev: Option<((usize, usize), usize)> = None;
11624 let mut last_mode = DC_PRED;
11625 let mut last_uv_mode = DC_PRED;
11626 for i in 0..4usize {
11627 let lmi = if horz {
11628 (mi_row0 + i, mi_col0)
11629 } else {
11630 (mi_row0, mi_col0 + i)
11631 };
11632 let has_chroma = i % 2 == 1;
11633 let (mode, uv, _tx) = decode_rect4_16_strip(
11634 dec,
11635 cdfs,
11636 neighbours,
11637 lmi,
11638 horz,
11639 has_chroma,
11640 prev,
11641 y,
11642 u,
11643 v,
11644 enable_filter_intra,
11645 allow_screen_content_tools,
11646 base_q_idx,
11647 tx_select,
11648 reduced_tx_set, fctx,
11649 )?;
11650 if let Some(m) = uv {
11651 last_uv_mode = m;
11652 }
11653 last_mode = mode;
11654 prev = Some((lmi, mode));
11655 }
11656 // The coarse 16-px cell holds one entry for the whole 16x16: the last
11657 // strip is what a block below (right) sees through it, the mi-exact maps
11658 // above answering everything finer.
11659 neighbours.above_mode[c] = last_mode;
11660 neighbours.left_mode[r] = last_mode;
11661 neighbours.above_uv_mode[c] = last_uv_mode;
11662 neighbours.left_uv_mode[r] = last_uv_mode;
11663 neighbours.above_side[c] = bw;
11664 neighbours.left_side[r] = bh;
11665 Ok(())
11666}
11667
11668/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
11669/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
11670/// block path can decode a SINGLE intra strip of a partition whose other
11671/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
11672/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
11673/// every strip publishes its own mi-exact mode). Returns
11674/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
11675#[allow(clippy::too_many_arguments)]
11676fn decode_rect4_16_strip(
11677 dec: &mut SymbolDecoder,
11678 cdfs: &mut Cdfs,
11679 neighbours: &mut Neighbours,
11680 lmi: (usize, usize),
11681 horz: bool,
11682 has_chroma: bool,
11683 prev: Option<((usize, usize), usize)>,
11684 y: &mut PlaneBuf<'static>,
11685 u: &mut PlaneBuf<'static>,
11686 v: &mut PlaneBuf<'static>,
11687 enable_filter_intra: bool,
11688 allow_screen_content_tools: bool,
11689 base_q_idx: u8,
11690 tx_select: bool,
11691 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11692) -> Result<(usize, Option<usize>, (usize, usize))> {
11693 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
11694 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
11695 let (mi_w, mi_h) = (bw / MI, bh / MI);
11696 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11697 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11698 let mut last_uv_mode: Option<usize> = None;
11699 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
11700 // aliases all four strips onto one entry, so the mi-exact map wins and
11701 // the previous strip stands in on the split axis.
11702 let mut above_mode = neighbours.above_mode[c];
11703 let mut left_mode = neighbours.left_mode[r];
11704 if let Some(((pr, pc), pmode)) = prev {
11705 if pc == lmi.1 && lmi.0 == pr + mi_h {
11706 above_mode = pmode;
11707 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
11708 left_mode = pmode;
11709 }
11710 }
11711 let (above_mode, left_mode) =
11712 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
11713 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
11714 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
11715 // off CDF row 0 and every cache hit off an empty cache.
11716 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
11717 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
11718 let (
11719 skip,
11720 mode,
11721 angle_delta_y,
11722 uv_mode,
11723 angle_delta_uv,
11724 alpha,
11725 filter_intra,
11726 palette_y,
11727 palette_uv,
11728 ) = read_intra_mode_rect(
11729 dec,
11730 cdfs,
11731 above_mode,
11732 left_mode,
11733 true,
11734 has_chroma,
11735 bw,
11736 bh,
11737 enable_filter_intra,
11738 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
11739 allow_screen_content_tools,
11740 Some((palette_ctx, &palette_cache)),
11741 &palette_uv_cache,
11742 lmi.0,
11743 lmi.1, fctx,
11744 )?;
11745 if palette_y.is_some() || palette_uv.is_some() {
11746 hit!(RECT4_PALETTE_HITS);
11747 }
11748 // The colour-index map through the base colours IS the prediction.
11749 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
11750 // chroma transform this closing strip codes.
11751 let palette_y_buf: Option<Vec<u16>> = palette_y
11752 .as_ref()
11753 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11754 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11755 (
11756 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11757 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11758 )
11759 });
11760 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11761 if smooth_neighbor {
11762 hit!(SMOOTH_LUMA_HITS);
11763 }
11764 if filter_intra.is_some() {
11765 hit!(FILTER_INTRA_RECT_HITS);
11766 }
11767 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
11768 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
11769 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
11770 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
11771 let depth = if tx_select {
11772 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
11773 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
11774 // the 2:1 intra-in-inter strip already does); the key frame's
11775 // deblock-grid approximation is only right where those bands were
11776 // never written.
11777 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11778 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
11779 } else {
11780 tx_size_context_rect(neighbours, lmi, bw, bh)
11781 };
11782 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
11783 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11784 eprintln!(
11785 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
11786 lmi.0,
11787 lmi.1,
11788 dec.debug_state().0
11789 );
11790 }
11791 d
11792 } else {
11793 0
11794 };
11795 if depth != 0 {
11796 hit!(TX_DEPTH_HITS);
11797 hit!(RECT4_16_SPLIT_HITS);
11798 }
11799 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11800 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11801 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11802 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
11803 if depth != 0 {
11804 // [`decode_rect_split`]'s per-unit walk, inlined because the
11805 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
11806 // the strip (that function codes one chroma transform per block).
11807 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
11808 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
11809 // unit predicts off the units before it in raster order.
11810 let rect_unit = tx_w != tx_h;
11811 let zero_tu = vec![0i32; tx_w * tx_h];
11812 for tu_row in 0..bh / tx_h {
11813 for tu_col in 0..bw / tx_w {
11814 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
11815 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11816 let tu_reach = Reach::of_tu(
11817 bw,
11818 bh,
11819 tu_col * tx_w,
11820 tu_row * tx_h,
11821 tx_w,
11822 tx_h,
11823 reach,
11824 );
11825 if let Some(b) = &palette_y_buf {
11826 let tu_buf: Vec<u16> = (0..tx_h)
11827 .flat_map(|i| {
11828 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
11829 b[base..base + tx_w].iter().copied()
11830 })
11831 .collect();
11832 set_palette_pred(tu_buf, fctx);
11833 }
11834 if skip {
11835 push_intra_rect(0,
11836 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
11837 None, filter_intra, smooth_neighbor, fctx,
11838 );
11839 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11840 } else if rect_unit {
11841 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
11842 // 32 coded positions and the `TX_4X4` `tx_type` row:
11843 // exactly [`TxbSet::LumaRect4x8`].
11844 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11845 let tu_skip_ctx =
11846 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
11847 let set = if reduced_tx_set {
11848 TxbSet::LumaRect4x8
11849 } else {
11850 TxbSet::LumaRect4x8Set1
11851 };
11852 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
11853 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11854 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11855 dec,
11856 &mut coding,
11857 tu_scan,
11858 tx_w,
11859 tx_h,
11860 tu_skip_ctx,
11861 dc_sign_ctx(tu_around.2),
11862 TxType::DctDct,
11863 )?;
11864 let residual = dequant_and_inverse_typed_wh(
11865 &tu_grid,
11866 tx_w,
11867 tx_h,
11868 crate::decode::bit_depth(fctx),
11869 block_q_idx(fctx),
11870 plane_q_delta(0, fctx).0,
11871 plane_q_delta(0, fctx).1,
11872 tu_tx_type,
11873 );
11874 push_intra_rect(0,
11875 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
11876 None, filter_intra, smooth_neighbor, fctx,
11877 );
11878 if tu_grid.iter().any(|&l| l != 0) {
11879 hit!(RECT4_16_COEFF_HITS);
11880 }
11881 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11882 } else {
11883 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
11884 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
11885 let tu_grid = read_plane(
11886 dec,
11887 cdfs,
11888 txbset_for(tx_w, reduced_tx_set),
11889 default_scan(tx_w),
11890 0,
11891 tu_around,
11892 mode,
11893 mode,
11894 angle_delta_y,
11895 tu_reach,
11896 y,
11897 tu_px,
11898 tu_py,
11899 tx_w,
11900 tx_w,
11901 base_q_idx,
11902 None,
11903 filter_intra,
11904 Some(tu_skip_ctx),
11905 smooth_neighbor, fctx,
11906 )?;
11907 if tu_grid.iter().any(|&l| l != 0) {
11908 hit!(RECT4_16_COEFF_HITS);
11909 }
11910 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
11911 }
11912 }
11913 }
11914 } else {
11915 let levels = if skip {
11916 let zeros = Grid::Zero(bw * bh);
11917 if let Some(b) = &palette_y_buf {
11918 set_palette_pred(b.clone(), fctx);
11919 }
11920 push_intra_rect(0,
11921 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
11922 smooth_neighbor, fctx,
11923 );
11924 zeros
11925 } else {
11926 // The strip's luma TU *is* the strip (`plane_bsize ==
11927 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
11928 // `txb_skip_ctx` at 0.
11929 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
11930 let set = if reduced_tx_set {
11931 TxbSet::LumaRect16x4
11932 } else {
11933 TxbSet::LumaRect16x4Set1
11934 };
11935 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11936 let (levels, tx_type) = read_coeffs_rect(
11937 dec,
11938 &mut coding,
11939 scan,
11940 bw,
11941 bh,
11942 0,
11943 dc_sign_ctx(around.2),
11944 TxType::DctDct,
11945 )?;
11946 let residual = dequant_and_inverse_typed_wh(
11947 &levels,
11948 bw,
11949 bh,
11950 crate::decode::bit_depth(fctx),
11951 block_q_idx(fctx),
11952 plane_q_delta(0, fctx).0,
11953 plane_q_delta(0, fctx).1,
11954 tx_type,
11955 );
11956 if let Some(b) = &palette_y_buf {
11957 set_palette_pred(b.clone(), fctx);
11958 }
11959 push_intra_rect(0,
11960 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
11961 smooth_neighbor, fctx,
11962 );
11963 hit!(RECT4_16_COEFF_HITS);
11964 levels
11965 };
11966 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
11967 }
11968 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
11969 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
11970 // `update_partition_context` writes `partition_context_lookup[
11971 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
11972 // the left (mirrored under VERT_4).
11973 for cell in 0..mi_w {
11974 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
11975 *slot = bw as u8;
11976 }
11977 }
11978 for cell in 0..mi_h {
11979 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
11980 *slot = bh as u8;
11981 }
11982 }
11983 if has_chroma {
11984 hit!(RECT4_16_CHROMA_HITS);
11985 let pair_mi = if horz {
11986 (lmi.0 - 1, lmi.1)
11987 } else {
11988 (lmi.0, lmi.1 - 1)
11989 };
11990 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
11991 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
11992 let (cpx, cpy) = (ppx / 2, ppy / 2);
11993 let (cw, ch) = (pw / 2, ph / 2);
11994 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11995 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
11996 hit!(RECT4_16_CHROMA_DIR_HITS);
11997 }
11998 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
11999 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
12000 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
12001 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
12002 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
12003 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
12004 // the pair's top-left luma mi, never this leaf's odd row/column.
12005 // Reading `lmi` here named the leaf directly above (a non-chroma
12006 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
12007 // SMOOTH neighbour: filt_type 0 instead of 1 turned
12008 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
12009 // directional chroma strip, moving 4 samples by 1.
12010 let smooth_neighbor_uv =
12011 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
12012 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
12013 {
12014 hit!(RECT4_16_UV_PAIR_FILT_HITS);
12015 }
12016 let (u_levels, v_levels) = if skip {
12017 let zeros = Grid::Zero(cw * ch);
12018 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
12019 // ~1000) predicts EVERY plane and only guards the residual on
12020 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
12021 // DC + alpha * luma-AC. Dropping the CfL term here left a
12022 // chroma-only bounded box on ReelC's key frames.
12023 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12024 if alpha.is_some() {
12025 hit!(CHROMA_SKIP_CFL_HITS);
12026 }
12027 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
12028 if let Some((ub, vb)) = &palette_uv_bufs {
12029 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12030 }
12031 push_intra_rect(plane,
12032 cpx,
12033 cpy,
12034 cw,
12035 ch,
12036 uv_predict_mode,
12037 angle_delta_uv,
12038 pair_reach,
12039 &zeros,
12040 alpha
12041 .zip(ac)
12042 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12043 None,
12044 smooth_neighbor_uv, fctx,
12045 );
12046 }
12047 (zeros.clone(), zeros)
12048 } else {
12049 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
12050 let mut planes = Vec::with_capacity(2);
12051 for plane in 1..3 {
12052 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12053 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12054 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12055 let (levels, tx_type) = read_coeffs_rect(
12056 dec,
12057 &mut coding,
12058 chroma_scan,
12059 cw,
12060 ch,
12061 skip_ctx,
12062 dc_sign_ctx(around[plane].2),
12063 default_tx,
12064 )?;
12065 planes.push((levels, tx_type));
12066 }
12067 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12068 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12069 // CfL averages the luma of the WHOLE pair, the region this one
12070 // chroma transform covers.
12071 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12072 for (plane, _buf, levels, tx_type) in [
12073 (1usize, &mut *u, &u_levels, u_tx_type),
12074 (2, &mut *v, &v_levels, v_tx_type),
12075 ] {
12076 let residual = dequant_and_inverse_typed_wh(
12077 levels,
12078 cw,
12079 ch,
12080 crate::decode::bit_depth(fctx),
12081 block_q_idx(fctx),
12082 plane_q_delta(plane, fctx).0,
12083 plane_q_delta(plane, fctx).1,
12084 tx_type,
12085 );
12086 if let Some((ub, vb)) = &palette_uv_bufs {
12087 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12088 }
12089 push_intra_rect(plane,
12090 cpx,
12091 cpy,
12092 cw,
12093 ch,
12094 uv_predict_mode,
12095 angle_delta_uv,
12096 pair_reach,
12097 &residual,
12098 alpha
12099 .zip(ac)
12100 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12101 None,
12102 smooth_neighbor_uv, fctx,
12103 );
12104 }
12105 (u_levels, v_levels)
12106 };
12107 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
12108 // The chroma planes' coefficient context, over the PAIR's mi span
12109 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
12110 // the luma one rounded up to its 4x4 unit).
12111 let u_state = neighbour_state(&u_levels);
12112 let v_state = neighbour_state(&v_levels);
12113 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12114 let bound_h = round_up_even(neighbours.mi_rows);
12115 let bound_w = round_up_even(neighbours.mi_cols);
12116 for cell in 0..(ph / MI) {
12117 if pair_mi.0 + cell < bound_h
12118 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
12119 {
12120 slot[1] = u_state;
12121 slot[2] = v_state;
12122 }
12123 }
12124 for cell in 0..(pw / MI) {
12125 if pair_mi.1 + cell < bound_w
12126 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
12127 {
12128 slot[1] = u_state;
12129 slot[2] = v_state;
12130 }
12131 }
12132 last_uv_mode = Some(uv_predict_mode);
12133 }
12134 if horz {
12135 hit!(RECT4_16_HORZ_HITS);
12136 } else {
12137 hit!(RECT4_16_VERT_HITS);
12138 }
12139 let (pal_y_size, pal_y_colors) =
12140 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12141 let (pal_uv_size, pal_uv_colors) =
12142 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12143 record_strip_palette(
12144 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12145 );
12146 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12147 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12148 // frame): the above row records `tx_size_wide` over the block's width and
12149 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12150 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12151 // and it published neither band -- so the block after a 64x16 strip read
12152 // the row's init value 64 as its left transform height and took
12153 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12154 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12155 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12156 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
12157 Ok((mode, last_uv_mode, (tx_w, tx_h)))
12158}
12159
12160
12161/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
12162/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
12163/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
12164/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
12165/// cap, so LUMA needs the same corner truncation [`decode_block`] already
12166/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
12167/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
12168/// this function's own charter/report), so both strips read a real 32x32
12169/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
12170/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
12171/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
12172/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
12173/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
12174/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
12175/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
12176/// that function, only the single-transform-unit (`tx_depth == 0`) case is
12177/// supported: a split transform refuses by name rather than guess-decode.
12178#[allow(clippy::too_many_arguments)]
12179fn decode_block_rect64(
12180 dec: &mut SymbolDecoder,
12181 cdfs: &mut Cdfs,
12182 neighbours: &mut Neighbours,
12183 at: (usize, usize),
12184 bw: usize,
12185 bh: usize,
12186 y: &mut PlaneBuf<'static>,
12187 u: &mut PlaneBuf<'static>,
12188 v: &mut PlaneBuf<'static>,
12189 enable_filter_intra: bool,
12190 allow_screen_content_tools: bool,
12191 base_q_idx: u8,
12192 tx_select: bool,
12193 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12194) -> Result<()> {
12195 let (r, c) = at;
12196 let (px, py) = (c * SUB, r * SUB);
12197 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12198 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12199 let palette_uv_cache = neighbours.palette_uv_cache(at);
12200 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12201 read_intra_mode_rect(
12202 dec,
12203 cdfs,
12204 nb_above_mode,
12205 nb_left_mode,
12206 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
12207 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
12208 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
12209 // correct), CFL must never be offered here -- passing `true`
12210 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
12211 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
12212 // from this block's very first symbol (lane-sbpart r3 bisect).
12213 false,
12214 true,
12215 bw,
12216 bh,
12217 enable_filter_intra,
12218 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12219 allow_screen_content_tools,
12220 Some((palette_ctx, &palette_cache)),
12221 &palette_uv_cache,
12222 r * (SUB / MI),
12223 c * (SUB / MI), fctx,
12224 )?;
12225 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
12226 // lane-t900 r34: a non-skip palette block on a superblock-level strip
12227 // -- counted so its gate cannot go vacuous (this was a refusal until
12228 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
12229 // decodes_pixel_exact`).
12230 hit!(PALETTE_SB_STRIP_HITS);
12231 }
12232 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12233 if smooth_neighbor {
12234 hit!(SMOOTH_LUMA_HITS);
12235 }
12236 let smooth_neighbor_uv =
12237 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
12238 if filter_intra.is_some() {
12239 // `filter_intra_size_class_rect` already returns `None` for both
12240 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
12241 // 32 on both axes), so this symbol is never read at this level --
12242 // kept only as the same defensive refusal [`decode_block_rect`] has.
12243 return Err(unsupported(
12244 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
12245 av1_filter_intra_allowed_bsize caps at 32x32)",
12246 ));
12247 }
12248 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12249 DC_PRED
12250 } else {
12251 uv_mode
12252 };
12253 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12254 let depth = if tx_select {
12255 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
12256 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
12257 // the 16x4 intra-in-inter strips already do); the key frame's
12258 // deblock-grid approximation is only right where those bands were never
12259 // written. Measured on the 10-bit 1920x792 128-superblock stream,
12260 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12261 // `tx_size_cat2` row 1 where libaom reads row 2.
12262 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12263 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
12264 } else {
12265 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12266 };
12267 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
12268 // counts `sub_tx_size_map` steps from the block's own max rect
12269 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
12270 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
12271 // steps, so this level's category is 3 (the same one a 64x64 square
12272 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
12273 // here was a wrong-table read of a real symbol.
12274 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
12275 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12276 eprintln!(
12277 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
12278 dec.debug_state().0
12279 );
12280 }
12281 d
12282 } else {
12283 0
12284 };
12285 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12286 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12287 publish_txfm_bands_if_in_inter(
12288 neighbours,
12289 (mi_r, mi_c),
12290 depth_to_tx_wh(bw, bh, depth),
12291 (bw, bh), fctx,
12292 );
12293 if depth != 0 {
12294 hit!(TX_DEPTH_HITS);
12295 // lane-rectsplit r1/r4: the superblock-level strip splits its
12296 // transform through the very same per-unit path as its 32x32-level
12297 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
12298 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
12299 // measured the old square formula mis-tiling exactly that strip).
12300 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
12301 if bw.max(bh) / bw.min(bh) == 4 {
12302 let which = if depth == 1 {
12303 &RECT4_SPLIT_DEPTH1_HITS
12304 } else {
12305 &RECT4_SPLIT_DEPTH2_HITS
12306 };
12307 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12308 }
12309 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12310 eprintln!(
12311 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12312 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12313 angle_y={angle_delta_y}"
12314 );
12315 }
12316 let modes = RectStripModes {
12317 skip,
12318 mode,
12319 angle_delta_y,
12320 uv_predict_mode,
12321 angle_delta_uv,
12322 alpha,
12323 filter_intra,
12324 smooth_neighbor,
12325 smooth_neighbor_uv,
12326 palette_y: palette_y
12327 .as_ref()
12328 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12329 palette_uv: palette_uv.as_ref().map(|p| {
12330 (
12331 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12332 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12333 )
12334 }),
12335 };
12336 if palette_y.is_some() || palette_uv.is_some() {
12337 hit!(PALETTE_SPLIT_TX_HITS);
12338 }
12339 decode_rect_split(
12340 dec,
12341 cdfs,
12342 neighbours,
12343 (mi_r, mi_c),
12344 bw,
12345 bh,
12346 tx_w,
12347 tx_h,
12348 &modes,
12349 y,
12350 u,
12351 v,
12352 base_q_idx,
12353 reduced_tx_set, fctx,
12354 )?;
12355 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
12356 // (lane-palette2 r10): this return skips the fn's own tail, so a
12357 // split-tx superblock strip would otherwise leave the above/left
12358 // palette arrays holding a dead block's colours.
12359 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12360 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12361 let (puv_size, puv_colors) =
12362 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12363 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12364 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
12365 // return skips the fn's own tail, so a SPLIT superblock-level strip
12366 // published no TXFM_CONTEXT band and the next block read the row's init
12367 // value 64 as its left transform height. Measured on the 10-bit
12368 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
12369 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
12370 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
12371 // bands carry the SPLIT unit's size, not the block's.
12372 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12373 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
12374 hit!(RECT_PARTITION_HITS);
12375 return Ok(());
12376 }
12377 let (tx_w, tx_h) = (bw, bh);
12378 let (cpx, cpy) = (px / 2, py / 2);
12379 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12380 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12381 if let Some(ref pyv) = palette_y {
12382 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12383 set_palette_pred(buf, fctx);
12384 }
12385 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12386 (
12387 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12388 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12389 )
12390 });
12391 if skip {
12392 push_intra_rect(0,
12393 px,
12394 py,
12395 bw,
12396 bh,
12397 mode,
12398 angle_delta_y,
12399 reach,
12400 &ZERO_RESIDUAL[..bw * bh],
12401 None,
12402 filter_intra,
12403 smooth_neighbor, fctx,
12404 );
12405 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12406 if let Some((ub, _)) = &palette_uv_bufs {
12407 set_palette_pred(ub.clone(), fctx);
12408 }
12409 push_intra_rect(1,
12410 cpx,
12411 cpy,
12412 chroma_w,
12413 chroma_h,
12414 uv_predict_mode,
12415 angle_delta_uv,
12416 reach,
12417 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12418 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12419 None,
12420 smooth_neighbor_uv, fctx,
12421 );
12422 if let Some((_, vb)) = &palette_uv_bufs {
12423 set_palette_pred(vb.clone(), fctx);
12424 }
12425 push_intra_rect(2,
12426 cpx,
12427 cpy,
12428 chroma_w,
12429 chroma_h,
12430 uv_predict_mode,
12431 angle_delta_uv,
12432 reach,
12433 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12434 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12435 None,
12436 smooth_neighbor_uv, fctx,
12437 );
12438 neighbours.record_rect(
12439 at,
12440 bw,
12441 bh,
12442 mode,
12443 uv_predict_mode,
12444 &[
12445 &ZERO_RESIDUAL[..bw * bh],
12446 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12447 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12448 ],
12449 );
12450 } else {
12451 let around = neighbours.around_rect(at, bw, bh);
12452 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
12453 // (see this function's own doc comment). A 64-length axis codes only
12454 // its low 32 coefficients, so the corner is `min(bw, 32)` x
12455 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
12456 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
12457 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
12458 let scan32 = default_scan(TX32);
12459 if coeff_trace_on() {
12460 let (rng, _) = dec.debug_state();
12461 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
12462 }
12463 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
12464 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
12465 read_coeffs(
12466 dec,
12467 &mut luma_coding,
12468 &scan32,
12469 0,
12470 dc_sign_ctx(around[0].2),
12471 TxType::DctDct,
12472 Some((bw, bh)),
12473 )?
12474 } else {
12475 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
12476 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
12477 // (`scan.c`) gives both the very same `default_scan_32x16` /
12478 // `default_scan_16x32` the 2:1 sizes use ("Half of the
12479 // coefficients of tx64 at higher frequencies are set to zeros. So
12480 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
12481 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
12482 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
12483 // 512-position eob group) -- BOTH identical to TX_32X16, so the
12484 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
12485 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
12486 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
12487 // what `base_ctx_rect` computes at (32, 16).
12488 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
12489 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
12490 read_coeffs_rect(
12491 dec,
12492 &mut luma_coding,
12493 luma_scan,
12494 luma_cw,
12495 luma_ch,
12496 0,
12497 dc_sign_ctx(around[0].2),
12498 TxType::DctDct,
12499 )?
12500 };
12501 if coeff_trace_on() {
12502 let (rng, _) = dec.debug_state();
12503 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
12504 }
12505 let mut luma_levels = vec![0i32; bw * bh];
12506 for row in 0..luma_ch {
12507 luma_levels[row * bw..][..luma_cw]
12508 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
12509 }
12510 {
12511 let cur = block_q_idx(fctx);
12512 if cur != i32::from(base_q_idx) {
12513 hit!(RECT64_QIDX_DRIFT_HITS);
12514 }
12515 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12516 eprintln!(
12517 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
12518 );
12519 }
12520 }
12521 let luma_residual = dequant_and_inverse_typed_wh(
12522 &luma_levels,
12523 bw,
12524 bh,
12525 crate::decode::bit_depth(fctx),
12526 block_q_idx(fctx),
12527 plane_q_delta(0, fctx).0,
12528 plane_q_delta(0, fctx).1,
12529 luma_tx_type,
12530 );
12531 push_intra_rect(0,
12532 px,
12533 py,
12534 bw,
12535 bh,
12536 mode,
12537 angle_delta_y,
12538 reach,
12539 &luma_residual,
12540 None,
12541 filter_intra,
12542 smooth_neighbor, fctx,
12543 );
12544 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12545 let leftcol: Vec<u16> = if px > 0 {
12546 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
12547 } else {
12548 vec![]
12549 };
12550 eprintln!(
12551 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
12552 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
12553 luma_corner.iter().any(|&v| v != 0),
12554 &y.data[py * y.width + px..][..bw],
12555 leftcol,
12556 );
12557 }
12558 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
12559 // corner crop needed (see doc comment).
12560 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12561 // The chroma plane is never truncated (both axes <= 32 after
12562 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
12563 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
12564 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
12565 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
12566 // set, and only the scan is new (lane-tx64x16).
12567 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
12568 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
12569 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
12570 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12571 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12572 };
12573 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12574 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12575 if coeff_trace_on() {
12576 let (rng, _) = dec.debug_state();
12577 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12578 }
12579 let (u_levels, u_tx_type) = read_coeffs_rect(
12580 dec,
12581 &mut u_coding,
12582 chroma_scan,
12583 chroma_w,
12584 chroma_h,
12585 u_skip_ctx,
12586 dc_sign_ctx(around[1].2),
12587 TxType::DctDct,
12588 )?;
12589 if coeff_trace_on() {
12590 let (rng, _) = dec.debug_state();
12591 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
12592 }
12593 {
12594 let cur = block_q_idx(fctx);
12595 if cur != i32::from(base_q_idx) {
12596 hit!(RECT64_QIDX_DRIFT_HITS);
12597 }
12598 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12599 eprintln!(
12600 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
12601 );
12602 }
12603 }
12604 let u_residual = dequant_and_inverse_typed_wh(
12605 &u_levels,
12606 chroma_w,
12607 chroma_h,
12608 crate::decode::bit_depth(fctx),
12609 block_q_idx(fctx),
12610 plane_q_delta(1, fctx).0,
12611 plane_q_delta(1, fctx).1,
12612 u_tx_type,
12613 );
12614 // lane-t900 r34: the UV-palette prediction override, exactly as the
12615 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
12616 // set-then-take, so it must be filled again right before each plane's
12617 // own reconstruct; leaving this out of the non-skip arm predicted a
12618 // palette block's chroma off its block edges (measured: testsrc2
12619 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
12620 // luma exact, both chroma planes wrong over its whole 16x32).
12621 if let Some((ub, _)) = &palette_uv_bufs {
12622 set_palette_pred(ub.clone(), fctx);
12623 }
12624 push_intra_rect(1,
12625 cpx,
12626 cpy,
12627 chroma_w,
12628 chroma_h,
12629 uv_predict_mode,
12630 angle_delta_uv,
12631 reach,
12632 &u_residual,
12633 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12634 None,
12635 smooth_neighbor_uv, fctx,
12636 );
12637 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12638 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12639 if coeff_trace_on() {
12640 let (rng, _) = dec.debug_state();
12641 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12642 }
12643 let (v_levels, v_tx_type) = read_coeffs_rect(
12644 dec,
12645 &mut v_coding,
12646 chroma_scan,
12647 chroma_w,
12648 chroma_h,
12649 v_skip_ctx,
12650 dc_sign_ctx(around[2].2),
12651 TxType::DctDct,
12652 )?;
12653 if coeff_trace_on() {
12654 let (rng, _) = dec.debug_state();
12655 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
12656 }
12657 {
12658 let cur = block_q_idx(fctx);
12659 if cur != i32::from(base_q_idx) {
12660 hit!(RECT64_QIDX_DRIFT_HITS);
12661 }
12662 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12663 eprintln!(
12664 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
12665 );
12666 }
12667 }
12668 let v_residual = dequant_and_inverse_typed_wh(
12669 &v_levels,
12670 chroma_w,
12671 chroma_h,
12672 crate::decode::bit_depth(fctx),
12673 block_q_idx(fctx),
12674 plane_q_delta(2, fctx).0,
12675 plane_q_delta(2, fctx).1,
12676 v_tx_type,
12677 );
12678 if let Some((_, vb)) = &palette_uv_bufs {
12679 set_palette_pred(vb.clone(), fctx);
12680 }
12681 push_intra_rect(2,
12682 cpx,
12683 cpy,
12684 chroma_w,
12685 chroma_h,
12686 uv_predict_mode,
12687 angle_delta_uv,
12688 reach,
12689 &v_residual,
12690 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12691 None,
12692 smooth_neighbor_uv, fctx,
12693 );
12694 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12695 hit!(RECT_COEFF_HITS);
12696 }
12697 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12698 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12699 let (puv_size, puv_colors) =
12700 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12701 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12702 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12703 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12704 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12705 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12706 // frame): the above row records `tx_size_wide` over the block's width and
12707 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12708 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12709 // and it published neither band -- so the block after a 64x16 strip read
12710 // the row's init value 64 as its left transform height and took
12711 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12712 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12713 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12714 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12715 hit!(SB_RECT_HITS);
12716 match (bw, bh) {
12717 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
12718 (16, 64) => hit!(SB_RECT4_VERT_HITS),
12719 _ => {}
12720 }
12721 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12722 let (rng, _) = dec.debug_state();
12723 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
12724 }
12725 Ok(())
12726}
12727
12728/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
12729/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
12730/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
12731/// it lands away from zero, for gate tests to prove a real stream fired one.
12732fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
12733 let symbol = dec.symbol(cdf);
12734 if symbol != ANGLE_DELTA_ZERO {
12735 hit!(ANGLE_DELTA_HITS);
12736 }
12737 symbol as i32 - ANGLE_DELTA_ZERO as i32
12738}
12739
12740#[allow(clippy::too_many_arguments)]
12741fn read_intra_mode(
12742 dec: &mut SymbolDecoder,
12743 cdfs: &mut Cdfs,
12744 above_mode: usize,
12745 left_mode: usize,
12746 cfl: bool,
12747 side: usize,
12748 enable_filter_intra: bool,
12749 skip_ctx: usize,
12750 allow_screen_content_tools: bool,
12751 allow_intrabc: bool,
12752 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
12753 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
12754 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
12755 // `None` at the excluded call sites (the 8x8-leaf path), which still read
12756 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
12757 // decoder reads either way -- but refuse by name the moment it fires,
12758 // exactly the old behaviour.
12759 palette: Option<(usize, &[u16])>,
12760 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
12761 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
12762 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
12763 // `use_palette_y`, not a neighbour lookup).
12764 palette_uv_cache: &[u16],
12765 mi_r: usize,
12766 mi_c: usize, fctx: &crate::decode::FrameCtx,
12767) -> Result<(
12768 bool,
12769 usize,
12770 i32,
12771 usize,
12772 i32,
12773 Option<(i32, i32)>,
12774 Option<usize>,
12775 Option<PaletteY>,
12776 Option<PaletteUv>,
12777)> {
12778 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
12779 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
12780 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
12781 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
12782 // line against the instrumented aomdec, not just `tell()`.
12783 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
12784 if ec_istep {
12785 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
12786 // (decodemv.c:818), printed at the same point: before the first
12787 // mode-info symbol of the block, so a cross-decoder range ladder can
12788 // be keyed on the BLOCK, not just on the symbol sequence.
12789 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
12790 }
12791 macro_rules! istep {
12792 ($name:literal, $val:expr) => {
12793 if ec_istep {
12794 let (rng, _) = dec.debug_state();
12795 eprintln!(
12796 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
12797 $name, $val
12798 );
12799 }
12800 };
12801 }
12802 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
12803 // point every square caller routes through (see `read_intra_mode_rect`).
12804 let cfl = if cfl && side > 32 {
12805 hit!(NOCFL_UV_MODE_HITS);
12806 false
12807 } else {
12808 cfl
12809 };
12810 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
12811 // `skip` when `SegIdPreSkip`, and after it otherwise.
12812 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
12813 if seg_id_pre_skip(fctx) {
12814 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
12815 }
12816 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
12817 if trace {
12818 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
12819 }
12820 istep!("skip", skip as i32);
12821 if !seg_id_pre_skip(fctx) {
12822 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
12823 }
12824 // spec order (see the comment below on `read_intrabc_info`): `skip`,
12825 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
12826 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
12827 istep!("cdef", 0);
12828 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
12829 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
12830 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
12831 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
12832 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12833 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12834 istep!("dq", 0);
12835 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
12836 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
12837 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
12838 // intra frame whose header set `allow_intrabc`. Actual intra block copy
12839 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
12840 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
12841 // draws the line at consuming this one flag symbol and refusing by name
12842 // when it fires, so the arithmetic decoder still resyncs for a stream
12843 // that merely allows (but never uses) intrabc.
12844 if allow_intrabc {
12845 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
12846 if trace {
12847 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
12848 }
12849 if use_intrabc {
12850 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
12851 if trace {
12852 eprintln!("TRACE intrabc dv={dv:?}");
12853 }
12854 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
12855 hit!(INTRABC_HITS);
12856 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
12857 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
12858 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
12859 // `DC_PRED` (which is also what the neighbour mode contexts and
12860 // the loop filter then see).
12861 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
12862 }
12863 }
12864 let above_ctx = INTRA_MODE_CTX[above_mode];
12865 let left_ctx = INTRA_MODE_CTX[left_mode];
12866 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
12867 if trace {
12868 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
12869 }
12870 istep!("mode", mode as i32);
12871 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
12872 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
12873 if trace {
12874 eprintln!(
12875 "TRACE angle_delta value={}",
12876 delta + ANGLE_DELTA_ZERO as i32
12877 );
12878 }
12879 delta
12880 } else {
12881 0
12882 };
12883 istep!("angle_y", angle_delta_y);
12884 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
12885 // here so every `decode_block` caller (64x64 and 128x128 roots included)
12886 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
12887 let cfl = cfl && side <= 32;
12888 let uv_mode = if cfl {
12889 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
12890 } else {
12891 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
12892 };
12893 if trace {
12894 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
12895 }
12896 istep!("uv_mode", uv_mode as i32);
12897 let alpha = if cfl && uv_mode == UV_CFL_PRED {
12898 Some(read_cfl_alphas(dec, cdfs))
12899 } else {
12900 None
12901 };
12902 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
12903 // from this lane's directional chroma: a corner block with neither
12904 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
12905 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
12906 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
12907 // bug in that fallback this lane's own scope does not cover. Keep it
12908 // refused here rather than ship a silently-wrong decode.
12909 if (9..=12).contains(&uv_mode) {
12910 hit!(SMOOTH_UV_HITS);
12911 }
12912 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
12913 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
12914 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
12915 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
12916 // the `else` branch below and never reads one either way.
12917 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
12918 hit!(DIRECTIONAL_UV_HITS);
12919 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
12920 } else {
12921 0
12922 };
12923 istep!("angle_uv", angle_delta_uv);
12924 if angle_delta_uv != 0 {
12925 hit!(UV_ANGLE_DELTA_HITS);
12926 }
12927 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
12928 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
12929 // gated by `av1_allow_palette` (blockd.h -- size bound only,
12930 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
12931 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
12932 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
12933 // read the same CDF row whenever every neighbour really is non-palette).
12934 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
12935 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
12936 // neighbour lookup at all), so it is exact even at the excluded call
12937 // sites once Y decodes real syntax there too.
12938 //
12939 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
12940 // inline from `read_palette_mode_info` -- it runs later, from
12941 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
12942 // after the WHOLE mode-info read for the block, including UV palette
12943 // mode_info (`read_palette_mode_info`'s own second half, right below)
12944 // and `read_filter_intra_mode_info`. So this branch now only reads
12945 // mode/size/colours for both planes (deferring the two colour-index-map
12946 // decodes to after `filter_intra`, below) -- r6's range trace pinned
12947 // this exact ordering bug (`compare-range-not-tell`: ranges matched
12948 // bit-for-bit through the Y colours, diverged only at the old inline
12949 // `decode_color_index_map` call).
12950 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
12951 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
12952 if allow_screen_content_tools
12953 && let Some(bsize_ctx) = palette_bsize_ctx(side)
12954 {
12955 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
12956 if mode == DC_PRED {
12957 if trace {
12958 let (rng, _) = dec.debug_state();
12959 eprintln!(
12960 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
12961 );
12962 }
12963 }
12964 let use_palette_y =
12965 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
12966 if mode == DC_PRED && trace {
12967 let (rng, _) = dec.debug_state();
12968 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
12969 }
12970 if use_palette_y {
12971 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
12972 if trace {
12973 let (rng, _) = dec.debug_state();
12974 eprintln!("TRACE palette_y_size n={n} rng={rng}");
12975 }
12976 let colors = read_palette_colors_y(dec, n, cache, fctx);
12977 if trace {
12978 let (rng, _) = dec.debug_state();
12979 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
12980 }
12981 palette_y_pending = Some((n, colors));
12982 }
12983 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
12984 // unconditionally at this bit position whenever `uv_mode ==
12985 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
12986 // scope always reconstructs chroma alongside luma (`decode_block`
12987 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
12988 // is always true here and does not need threading in.
12989 let palette_uv_mode_ctx = usize::from(use_palette_y);
12990 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
12991 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
12992 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
12993 palette_uv_pending = Some((n, u_colors, v_colors));
12994 }
12995 }
12996 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
12997 // `use_filter_intra` symbol this decoder never read at all until
12998 // lane-av1real r10 -- silently skipping it left every bit past a
12999 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
13000 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
13001 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
13002 // symbol's bits were never consumed).
13003 let mut filter_intra = None;
13004 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
13005 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
13006 // `use_filter_intra` symbol for a Y-palette block, and reading one here
13007 // desynced every screen-content stream from the first palette block on
13008 // (it surfaced as a bogus "partition below 8x8" refusal further down the
13009 // tile).
13010 if mode == DC_PRED
13011 && enable_filter_intra
13012 && palette_y_pending.is_none()
13013 && let Some(class) = filter_intra_size_class(side)
13014 {
13015 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
13016 if trace {
13017 eprintln!(
13018 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
13019 use_filter_intra as i32
13020 );
13021 }
13022 istep!("use_filter_intra", use_filter_intra as i32);
13023 if use_filter_intra {
13024 hit!(FILTER_INTRA_HITS);
13025 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13026 if trace {
13027 eprintln!("TRACE filter_intra_mode value={fi_mode}");
13028 }
13029 istep!("filter_intra_mode", fi_mode as i32);
13030 filter_intra = Some(fi_mode);
13031 }
13032 }
13033 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
13034 // shared U/V map) -- the same order libaom's own loop visits them in.
13035 let palette_y = palette_y_pending.map(|(n, colors)| {
13036 let map = decode_color_index_map(dec, cdfs, n, side, false);
13037 hit!(PALETTE_HITS);
13038 if trace {
13039 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
13040 }
13041 PaletteY { size: n, colors, map }
13042 });
13043 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13044 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
13045 hit!(PALETTE_UV_HITS);
13046 if trace {
13047 eprintln!(
13048 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
13049 &u_colors[..n],
13050 &v_colors[..n]
13051 );
13052 }
13053 PaletteUv { size: n, u_colors, v_colors, map }
13054 });
13055 Ok((
13056 skip,
13057 mode,
13058 angle_delta_y,
13059 uv_mode,
13060 angle_delta_uv,
13061 alpha,
13062 filter_intra,
13063 palette_y,
13064 palette_uv,
13065 ))
13066}
13067
13068/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
13069/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
13070/// intra modes.
13071const UV_CFL_PRED: usize = 13;
13072
13073/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
13074/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
13075/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
13076/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
13077/// joint sign the same way. Returns each plane's final signed `alpha_q3`
13078/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
13079fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
13080 hit!(CFL_BLOCK_HITS);
13081 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
13082 let sign_u = ((joint_sign + 1) * 11) >> 5;
13083 let sign_v = (joint_sign + 1) - 3 * sign_u;
13084 let alpha_u = if sign_u == 0 {
13085 0
13086 } else {
13087 let ctx_u = (joint_sign + 1 - 3) as usize;
13088 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
13089 if sign_u == 2 { mag } else { -mag }
13090 };
13091 let alpha_v = if sign_v == 0 {
13092 0
13093 } else {
13094 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
13095 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
13096 if sign_v == 2 { mag } else { -mag }
13097 };
13098 (alpha_u, alpha_v)
13099}
13100
13101/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
13102/// the reconstructed luma samples under a `side`-square block, subsampled
13103/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
13104/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13105/// to give the AC values [`cfl_scaled`] scales by alpha.
13106fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13107 let cside = side / 2;
13108 let mut ac = vec![0i32; cside * cside];
13109 let mut sum = 0i32;
13110 for cy in 0..cside {
13111 for cx in 0..cside {
13112 let (lx, ly) = (px + cx * 2, py + cy * 2);
13113 let q3 = (i32::from(y.data[ly * y.width + lx])
13114 + i32::from(y.data[ly * y.width + lx + 1])
13115 + i32::from(y.data[(ly + 1) * y.width + lx])
13116 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
13117 << 1;
13118 ac[cy * cside + cx] = q3;
13119 sum += q3;
13120 }
13121 }
13122 let num_pel = (cside * cside) as i32;
13123 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13124 ac.iter_mut().for_each(|v| *v -= avg);
13125 ac
13126}
13127
13128/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13129/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13130/// ties away from zero on the shifted-out sign).
13131fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13132 let v = alpha_q3 * ac_q3;
13133 if v >= 0 {
13134 (v + 32) >> 6
13135 } else {
13136 -((-v + 32) >> 6)
13137 }
13138}
13139
13140/// One plane's reconstruction buffer, `width * height` samples, and the
13141/// prediction/residual reads and writes into it — the decode-side twin of
13142/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
13143/// (own-edge and reach clamps both), passing what it gathers straight to
13144/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
13145/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
13146/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
13147/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
13148/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
13149/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
13150/// lane-mc64 r1: the decode-order index the stage dumps below key their file
13151/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
13152/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
13153/// without this every frame overwrote `.f0` and a per-frame bisection silently
13154/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
13155#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
13156fn stage_dump_idx() -> usize {
13157 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
13158}
13159
13160fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
13161 use std::io::Write;
13162 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
13163 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
13164 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
13165 // not be read out at all.
13166 if let Ok(path) = crate::envflags::var(var)
13167 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13168 {
13169 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))] {
13170 for row in 0..h {
13171 let mut bytes = Vec::with_capacity(w * 2);
13172 for &s in &p.data[row * p.width..][..w] {
13173 bytes.extend_from_slice(&s.to_le_bytes());
13174 }
13175 let _ = f.write_all(&bytes);
13176 }
13177 }
13178 }
13179}
13180
13181/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
13182/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
13183/// every frame overwrote the previous one and only the LAST frame survived,
13184/// which silently defeats any per-frame filter-stage bisection.
13185fn dump_stage_idx(var: &str) -> usize {
13186 use std::collections::HashMap;
13187 use std::sync::{Mutex, OnceLock};
13188 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
13189 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
13190 let e = m.entry(var.to_string()).or_insert(0);
13191 let i = *e;
13192 *e += 1;
13193 i
13194}
13195
13196fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
13197 use std::io::Write;
13198 if let Ok(path) = crate::envflags::var(var)
13199 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13200 {
13201 for p in [y, u, v] {
13202 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
13203 let _ = f.write_all(&narrow);
13204 }
13205 }
13206}
13207
13208/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
13209/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
13210/// at most 4095), so a decode that hashes identically under the flag proves
13211/// the output does not depend on the plane buffer's initial content.
13212const PLANE_SENTINEL: u16 = 0xDEAD;
13213
13214/// A frame plane's own backing store, `n` samples, UNINITIALISED.
13215///
13216/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
13217/// by the tile walk's reconstruction before anything reads it, so the
13218/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
13219/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
13220/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
13221/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
13222/// ways (see the lane report) and the two agree, which is the proof that no
13223/// unwritten sample reaches the output.
13224fn fresh_plane(n: usize) -> Vec<u16> {
13225 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
13226 return vec![PLANE_SENTINEL; n];
13227 }
13228 let mut v: Vec<u16> = Vec::with_capacity(n);
13229 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
13230 // capacity was just reserved, so the vector owns `n` initialised-or-not
13231 // `u16` slots. Every one is written by reconstruction before it is read
13232 // (proven by the sentinel gate above).
13233 #[allow(unsafe_code)]
13234 unsafe {
13235 v.set_len(n);
13236 }
13237 v
13238}
13239
13240#[derive(Clone)]
13241struct PlaneBuf<'a> {
13242 data: std::borrow::Cow<'a, [u16]>,
13243 width: usize,
13244 height: usize,
13245 /// The frame's true, decodable extent in this plane's own units — past
13246 /// this, samples are the padded coding surface's invented tail, never a
13247 /// real decoder's edge or reach reads.
13248 true_width: usize,
13249 true_height: usize,
13250 /// This plane's own tile's top-left pixel origin (spec: intra prediction
13251 /// never reaches across a tile boundary even though an earlier-decoded
13252 /// tile's real pixels sit right there in the shared buffer) — set via
13253 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
13254 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
13255 /// is threaded (the two-tile column-split stage 1 fixture's tile always
13256 /// ends at the frame's own right/bottom edge); a non-last tile's own
13257 /// right/bottom reach bound is still open, tracked in the report.
13258 tile_x0: usize,
13259 tile_y0: usize,
13260 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
13261 /// (exclusive) -- a non-last tile column/row's own reach must stop at
13262 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
13263 /// full padded extent) for the single-tile/last-tile case, matching the
13264 /// old unclipped behaviour exactly.
13265 tile_x1: usize,
13266 tile_y1: usize,
13267}
13268
13269/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
13270/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
13271/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
13272/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13273/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13274/// `ALTREF2`/`ALTREF`).
13275
13276impl PlaneBuf<'_> {
13277 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
13278 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
13279 /// are already in this plane's own units (luma pixels for `y`, chroma
13280 /// pixels — halved — for `u`/`v`).
13281 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
13282 self.tile_x0 = x0;
13283 self.tile_y0 = y0;
13284 self.tile_x1 = x1;
13285 self.tile_y1 = y1;
13286 }
13287
13288 fn edges(
13289 &self,
13290 x: usize,
13291 y: usize,
13292 side: usize,
13293 reach: Reach,
13294 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13295 let own_across = x + side.min(self.true_width.saturating_sub(x));
13296 let across = if reach.above_right {
13297 own_across + side.min(self.true_width.saturating_sub(own_across))
13298 } else {
13299 own_across
13300 }
13301 .min(self.width)
13302 .min(self.tile_x1);
13303 let own_down = y + side.min(self.true_height.saturating_sub(y));
13304 let down = if reach.below_left {
13305 own_down + side.min(self.true_height.saturating_sub(own_down))
13306 } else {
13307 own_down
13308 }
13309 .min(self.height)
13310 .min(self.tile_y1);
13311 let above = (y > self.tile_y0 && across > x)
13312 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13313 let left = (x > self.tile_x0 && down > y).then(|| {
13314 (y..down)
13315 .map(|row| self.data[row * self.width + x - 1])
13316 .collect::<Vec<_>>()
13317 });
13318 let corner =
13319 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13320 (above, left, corner)
13321 }
13322
13323 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
13324 /// the above/left reach each extend by their OWN axis (`bw` across,
13325 /// `bh` down), not one shared `side`.
13326 fn edges_rect(
13327 &self,
13328 x: usize,
13329 y: usize,
13330 bw: usize,
13331 bh: usize,
13332 reach: Reach,
13333 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13334 let own_across = x + bw.min(self.true_width.saturating_sub(x));
13335 let across = if reach.above_right {
13336 own_across + bw.min(self.true_width.saturating_sub(own_across))
13337 } else {
13338 own_across
13339 }
13340 .min(self.width)
13341 .min(self.tile_x1);
13342 let own_down = y + bh.min(self.true_height.saturating_sub(y));
13343 let down = if reach.below_left {
13344 own_down + bh.min(self.true_height.saturating_sub(own_down))
13345 } else {
13346 own_down
13347 }
13348 .min(self.height)
13349 .min(self.tile_y1);
13350 let above = (y > self.tile_y0 && across > x)
13351 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13352 let left = (x > self.tile_x0 && down > y).then(|| {
13353 (y..down)
13354 .map(|row| self.data[row * self.width + x - 1])
13355 .collect::<Vec<_>>()
13356 });
13357 let corner =
13358 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13359 if matches!((bw, bh), (16, 8) | (8, 16)) {
13360 hit!(RECT_STRIP_PRED_HITS);
13361 if across > own_across || down > own_down {
13362 hit!(RECT_STRIP_REACH_HITS);
13363 }
13364 }
13365 (above, left, corner)
13366 }
13367
13368 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
13369 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
13370 /// already-rect-capable `(bw, bh)` pair.
13371 #[allow(clippy::too_many_arguments)]
13372 #[track_caller]
13373 fn reconstruct_rect(
13374 &mut self,
13375 x: usize,
13376 y: usize,
13377 bw: usize,
13378 bh: usize,
13379 mode: usize,
13380 angle_delta: i32,
13381 reach: Reach,
13382 residual: &[i32],
13383 cfl: Option<(i32, &[i32])>,
13384 filter_intra: Option<usize>,
13385 smooth_neighbor: bool,
13386 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13387 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13388 // than by this replay.
13389 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13390 ) {
13391 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
13392 // (lane-palette2 r4): a palette block's prediction is the
13393 // reconstructed colour-index map, needing no edge pixels at all.
13394 let prediction = if let Some(buf) = pred {
13395 buf
13396 } else {
13397 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
13398 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
13399 eprintln!(
13400 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
13401 above.as_ref().map(|a| (a.len(), a[0])),
13402 left.as_ref().map(|l| l.len()),
13403 left.as_ref().map(|l| l[0]),
13404 self.tile_x0, self.tile_y0, self.true_width, self.true_height
13405 );
13406 }
13407 let mut prediction = vec![0u16; bw * bh];
13408 if let Some(fi_mode) = filter_intra {
13409 crate::intra::predict_filter_intra(
13410 fi_mode,
13411 above.as_deref(),
13412 left.as_deref(),
13413 corner,
13414 bw,
13415 bh,
13416 &mut prediction, fctx,
13417 );
13418 } else {
13419 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13420 predict(
13421 mode as u8,
13422 angle_delta,
13423 above.as_deref(),
13424 left.as_deref(),
13425 corner,
13426 bw,
13427 bh,
13428 enable_edge_filter,
13429 smooth_neighbor,
13430 &mut prediction, fctx,
13431 );
13432 }
13433 prediction
13434 };
13435 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13436 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13437 if crate::envflags::env_flag!("EC_PRED") {
13438 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13439 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
13440 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
13441 eprintln!(
13442 "@{} 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)
13443 );
13444 }
13445 let residual = dense_residual(residual, bw * bh);
13446 for row in 0..bh {
13447 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
13448 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
13449 // whose padded width is not superblock aligned hangs past it.
13450 if y + row >= self.height {
13451 break;
13452 }
13453 for col in 0..bw {
13454 if x + col >= self.width {
13455 break;
13456 }
13457 let idx = row * bw + col;
13458 let mut base = i32::from(prediction[idx]);
13459 if let Some((alpha_q3, ac_q3)) = cfl {
13460 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13461 }
13462 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13463 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13464 }
13465 }
13466 }
13467
13468 /// Predicts under `mode` then adds `residual` (side*side, raster),
13469 /// writing the clamped reconstruction back into the plane at `(x, y)`.
13470 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
13471 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
13472 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
13473 /// order (cfl.c).
13474 #[track_caller]
13475 fn reconstruct(
13476 &mut self,
13477 x: usize,
13478 y: usize,
13479 side: usize,
13480 mode: usize,
13481 angle_delta: i32,
13482 reach: Reach,
13483 residual: &[i32],
13484 cfl: Option<(i32, &[i32])>,
13485 filter_intra: Option<usize>,
13486 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
13487 // libaom `get_filt_type`): true when the block's above OR left
13488 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
13489 // Callers pass their own plane's neighbour-mode check
13490 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
13491 // callers until a smooth/paeth `uv_mode` can reach this call at all
13492 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
13493 // keeps `false` exact for chroma without this fn needing to know why.
13494 smooth_neighbor: bool,
13495 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13496 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13497 // than by this replay.
13498 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13499 ) {
13500 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
13501 // takes priority over `predict()`/`predict_filter_intra` entirely --
13502 // palette prediction needs no edge pixels at all.
13503 let prediction = if let Some(buf) = pred {
13504 buf
13505 } else {
13506 let (above, left, corner) = self.edges(x, y, side, reach);
13507 let mut prediction = vec![0u16; side * side];
13508 if let Some(fi_mode) = filter_intra {
13509 crate::intra::predict_filter_intra(
13510 fi_mode,
13511 above.as_deref(),
13512 left.as_deref(),
13513 corner,
13514 side,
13515 side,
13516 &mut prediction, fctx,
13517 );
13518 } else {
13519 // `enable_intra_edge_filter` is the sequence header's own flag
13520 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
13521 // call, never per-block) -- threading it through every
13522 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
13523 // dozen sites for a value that never changes mid-decode, so it
13524 // rides a thread-local instead (this decoder is single-threaded
13525 // per stream).
13526 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13527 predict(
13528 mode as u8,
13529 angle_delta,
13530 above.as_deref(),
13531 left.as_deref(),
13532 corner,
13533 side,
13534 side,
13535 enable_edge_filter,
13536 smooth_neighbor,
13537 &mut prediction, fctx,
13538 );
13539 }
13540 prediction
13541 };
13542 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13543 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13544 if crate::envflags::env_flag!("EC_PRED") {
13545 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13546 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
13547 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
13548 eprintln!(
13549 "@{} 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)
13550 );
13551 }
13552 let residual = dense_residual(residual, side * side);
13553 for row in 0..side {
13554 // lane-sb128c r8: libaom's frame buffer is superblock
13555 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
13556 // transform unit of a 128x64 block at the BOTTOM frame edge
13557 // can hang past the last padded row (1920x792: a unit at
13558 // y=768 wants 832 rows of an 800-row buffer, which panicked
13559 // the film's key frames). Those samples are outside the
13560 // frame: never output, and no block below ever references
13561 // them.
13562 if y + row >= self.height {
13563 break;
13564 }
13565 for col in 0..side {
13566 if x + col >= self.width {
13567 break;
13568 }
13569 let idx = row * side + col;
13570 let mut base = i32::from(prediction[idx]);
13571 if let Some((alpha_q3, ac_q3)) = cfl {
13572 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13573 }
13574 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13575 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13576 }
13577 }
13578 }
13579}
13580
13581/// Reads one plane's transform block, reconstructs it into `plane` at
13582/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
13583#[allow(clippy::too_many_arguments)]
13584fn read_plane(
13585 dec: &mut SymbolDecoder,
13586 cdfs: &mut Cdfs,
13587 set: TxbSet,
13588 scan: &[u16],
13589 plane_idx: usize,
13590 around: (bool, bool, i32),
13591 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
13592 // it for every plane's `txb` lookup (it is what an intra transform type's
13593 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
13594 tx_mode: usize,
13595 predict_mode: usize,
13596 angle_delta: i32,
13597 reach: Reach,
13598 // lane-wave1 step (i): unread -- this reader records its write
13599 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
13600 // stays in the signature so every call site still proves the plane is
13601 // exclusively held while its coefficients are parsed.
13602 _plane: &mut PlaneBuf<'static>,
13603 x: usize,
13604 y: usize,
13605 side: usize,
13606 tx_side: usize,
13607 base_q_idx: u8,
13608 cfl: Option<(i32, CflSrc)>,
13609 filter_intra: Option<usize>,
13610 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
13611 // smaller than its own block (spec `get_txb_ctx_general`'s
13612 // `plane_bsize != tx_size` branch), carrying the already-looked-up
13613 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
13614 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
13615 // formula below.
13616 luma_skip_ctx: Option<usize>,
13617 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
13618 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
13619) -> Result<Grid> {
13620 let skip_ctx = if plane_idx == 0 {
13621 luma_skip_ctx.unwrap_or(0)
13622 } else {
13623 // libaom `get_txb_ctx`: a chroma unit's context is
13624 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
13625 // plane block is bigger than the transform. Our chroma tables hold the
13626 // offset-7 rows first, so the caller adds 3 for the bigger-block case
13627 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
13628 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
13629 };
13630 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
13631 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
13632 // not by the block's ordinary `mode` (which is always DC_PRED whenever
13633 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
13634 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
13635 // filter-intra in AV1).
13636 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
13637 let mut coding = cdfs.txb(set, tx_mode);
13638 // Luma's `default_tx_type` is only a fallback for the sizes whose
13639 // `TxbSet` carries no symbol at all (32-point and up), which the spec
13640 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
13641 // *never* its own coded symbol (`coding.tx_type` is always `None` for
13642 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
13643 // the plane's own predicted mode (`default_intra_tx_type`) -- except
13644 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
13645 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
13646 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
13647 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
13648 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
13649 // narrows there — only `Chroma32` and up do).
13650 let default_tx_type = if plane_idx == 0 || side >= 32 {
13651 TxType::DctDct
13652 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
13653 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
13654 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
13655 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
13656 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
13657 // [`read_inter_plane`]'s own `side < 32` guard).
13658 inherited
13659 } else {
13660 default_intra_tx_type(predict_mode as u8)
13661 };
13662 let (grid, tx_type) = read_coeffs(
13663 dec,
13664 &mut coding,
13665 scan,
13666 skip_ctx,
13667 dc_sign_ctx(around.2),
13668 default_tx_type,
13669 None,
13670 )?;
13671 note_chroma_class1(plane_idx, tx_type);
13672 if plane_idx == 0 {
13673 fctx.luma_tx_type.with(|c| c.set(tx_type));
13674 }
13675 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
13676 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
13677 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
13678 // guard also assumes.
13679 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
13680 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
13681 // keyed by that true size, not the coded corner's -- so the corner
13682 // goes into the top-left of a `side`-sized grid, not the reverse.
13683 let levels = extend_corner(grid, tx_side, tx_side, side, side);
13684 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
13685 let tx = TxParams {
13686 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13687 ac_delta, tx_type, stride: 0,
13688 };
13689 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13690 let residual = tx.run(&levels);
13691 eprintln!(
13692 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
13693 );
13694 }
13695 push_intra_tx(
13696 plane_idx,
13697 x,
13698 y,
13699 side,
13700 side,
13701 false,
13702 predict_mode,
13703 angle_delta,
13704 reach,
13705 tx,
13706 &levels,
13707 cfl,
13708 filter_intra,
13709 smooth_neighbor, fctx,
13710 );
13711 // `record`'s neighbour state only reads whether *the coded grid* (not the
13712 // residual) has nonzero entries, so the levels this function already
13713 // built are what it wants back -- both arms of the old `tx_side == side`
13714 // branch returned exactly that, one of them through a full `to_vec` copy
13715 // of the grid per intra transform unit (lane-coefbuf).
13716 Ok(levels)
13717}
13718
13719/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
13720/// three planes, reconstructing them into `y`/`u`/`v` and updating
13721/// `neighbours`.
13722#[allow(clippy::too_many_arguments)]
13723fn decode_block(
13724 dec: &mut SymbolDecoder,
13725 cdfs: &mut Cdfs,
13726 neighbours: &mut Neighbours,
13727 at: (usize, usize),
13728 side: usize,
13729 luma_set: TxbSet,
13730 chroma_set: TxbSet,
13731 luma_tx: usize,
13732 chroma_tx: usize,
13733 scans: (&[u16], &[u16]),
13734 cfl: bool,
13735 y: &mut PlaneBuf<'static>,
13736 u: &mut PlaneBuf<'static>,
13737 v: &mut PlaneBuf<'static>,
13738 base_q_idx: u8,
13739 enable_filter_intra: bool,
13740 allow_screen_content_tools: bool,
13741 allow_intrabc: bool,
13742 scan32: &[u16],
13743 scan16: &[u16],
13744 scan8: &[u16],
13745 scan4: &[u16],
13746 tx_select: bool,
13747 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13748) -> Result<()> {
13749 let (r, c) = at;
13750 let (px, py) = (c * SUB, r * SUB);
13751 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13752 let palette_uv_cache = neighbours.palette_uv_cache(at);
13753 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13754 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
13755 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
13756 read_intra_mode(
13757 dec,
13758 cdfs,
13759 nb_above_mode,
13760 nb_left_mode,
13761 cfl,
13762 side,
13763 enable_filter_intra,
13764 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
13765 allow_screen_content_tools,
13766 allow_intrabc,
13767 Some((palette_ctx, &palette_cache)),
13768 &palette_uv_cache,
13769 r * (SUB / MI),
13770 c * (SUB / MI), fctx,
13771 )?;
13772 if at_tile_left && palette_y.is_some() {
13773 hit!(PALETTE_TILE_LEFT_HITS);
13774 }
13775 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
13776 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
13777 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
13778 // actual chroma-from-luma correlation, same as this decoder always did.
13779 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13780 DC_PRED
13781 } else {
13782 uv_mode
13783 };
13784 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13785 if smooth_neighbor {
13786 hit!(SMOOTH_LUMA_HITS);
13787 }
13788 let smooth_neighbor_uv =
13789 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
13790 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13791 eprintln!(
13792 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
13793 angle_delta_uv={angle_delta_uv}"
13794 );
13795 }
13796 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13797 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
13798 // block, skipped or not. `logical_tx` is what the loop filter's edge
13799 // lookup and the next block's own `tx_size_context` want (the *nominal*
13800 // transform size -- 64 even for the 64x64 corner-scanned case, spec
13801 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
13802 // which only differs from it at that one corner case.
13803 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
13804 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
13805 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
13806 // intrabc block reads NO tx-size symbol at all -- it takes
13807 // `maxRectTxSize` -- while every ordinary skipped intra block does read
13808 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
13809 // the tile from that block on (class `equal-range-means-unread`).
13810 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
13811 // tree instead (`read_var_tx_size`), the same syntax the inter block path
13812 // has always read -- libaom's `parse_decode_block` dispatches on
13813 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
13814 // intrabc block as inter.
13815 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
13816 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
13817 let intrabc_leaves = if intrabc_vartx {
13818 let max_tx = side.min(64);
13819 // `max_block_wide`/`max_block_high`: the frame's own mi grid
13820 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
13821 // right/bottom edge reads no split symbol for the units outside it.
13822 let mi_cols = 2 * y.true_width.div_ceil(8);
13823 let mi_rows = 2 * y.true_height.div_ceil(8);
13824 let side_mi = side / MI;
13825 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
13826 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
13827 let mut leaves = Vec::new();
13828 for row in (0..side_mi).step_by(max_tx / MI) {
13829 for col in (0..side_mi).step_by(max_tx / MI) {
13830 read_var_tx_size(
13831 dec, cdfs, neighbours, (mi_r, mi_c), side,
13832 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
13833 );
13834 }
13835 }
13836 hit!(INTRABC_VARTX_HITS);
13837 // The luma reconstruct loop below is a UNIFORM grid of one square
13838 // transform (the intra `tx_depth` shape), so a tree that resolved to
13839 // mixed leaf sizes is refused by name rather than reconstructed at the
13840 // wrong stride.
13841 let uniform = leaves
13842 .first()
13843 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
13844 if !uniform {
13845 return Err(unsupported(
13846 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
13847 ));
13848 }
13849 Some(leaves[0].2)
13850 } else {
13851 None
13852 };
13853 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
13854 (tx, if tx == 64 { 32 } else { tx })
13855 } else if tx_select && !intrabc_skip_tx {
13856 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
13857 (resolved, if resolved == 64 { 32 } else { resolved })
13858 } else {
13859 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
13860 // TX_64X64, so a 128x128 block is always FOUR luma transform units
13861 // even with `tx_select` off -- the TU loop below, never the
13862 // single-unit path.
13863 (side.min(64), luma_tx)
13864 };
13865 if tx_select && logical_tx < side && uv_mode != DC_PRED {
13866 hit!(SQ_CHROMA_TX_HITS);
13867 }
13868 let luma_set = if tx_select {
13869 txbset_for(logical_tx, reduced_tx_set)
13870 } else {
13871 luma_set
13872 };
13873 let luma_set = if intrabc_dv.is_some() {
13874 txbset_for_inter(logical_tx, reduced_tx_set)
13875 } else {
13876 luma_set
13877 };
13878 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
13879 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
13880 let (cpx, cpy) = (px / 2, py / 2);
13881 let chroma_side = side / 2;
13882 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
13883 // frame's own pre-loop-filter reconstruction (all loop filters are off
13884 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
13885 // block vector, with the BILINEAR kernel libaom forces for intrabc --
13886 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
13887 // odd, which is exactly what the bilinear taps then interpolate.
13888 flush_recon(fctx, y, u, v);
13889 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
13890 let mut yb = vec![0u16; side * side];
13891 mc::predict_with_filter(
13892 &y.data, y.width, y.true_width, y.true_height,
13893 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
13894 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
13895 );
13896 let mut ub = vec![0u16; chroma_side * chroma_side];
13897 mc::predict_with_filter(
13898 &u.data, u.width, u.true_width, u.true_height,
13899 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13900 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
13901 );
13902 let mut vb = vec![0u16; chroma_side * chroma_side];
13903 mc::predict_with_filter(
13904 &v.data, v.width, v.true_width, v.true_height,
13905 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13906 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
13907 );
13908 (yb, ub, vb)
13909 });
13910 // A palette-Y block's own prediction is the reconstructed colour-index
13911 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
13912 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
13913 // parameter through this function's dozen `y.reconstruct`/`read_plane`
13914 // sites. A split luma transform (`tx_select && logical_tx != side`)
13915 // would need the map sliced per-TU -- untested against a real
13916 // `--enable-palette=1` stream this round, so refuse by name rather than
13917 // guess at the slicing (charter's own named-acceptable fallback).
13918 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
13919 py.map
13920 .iter()
13921 .map(|&idx| py.colors[idx as usize])
13922 .collect()
13923 });
13924 // lane-t900 r32: the intrabc luma prediction rides the very same
13925 // whole-block override slot, so the multi-TU loop below windows it per
13926 // transform unit exactly like a palette map -- setting it once up front
13927 // handed the whole `side`x`side` buffer to the FIRST unit and left every
13928 // later one predicting off block edges (the var-tx tree above is what
13929 // first makes `logical_tx < side` reachable for an intrabc block).
13930 let palette_y_buf = match &intrabc_bufs {
13931 Some((yb, _, _)) => Some(yb.clone()),
13932 None => palette_y_buf,
13933 };
13934 // With one luma transform unit the whole `side`x`side` map is the
13935 // prediction; with several (`logical_tx != side`) each unit takes its own
13936 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
13937 // below (lane-palette2 r7) -- setting the full-block buffer here would be
13938 // taken by the FIRST unit and indexed at the wrong stride.
13939 if let Some(buf) = &palette_y_buf
13940 && logical_tx == side
13941 {
13942 set_palette_pred(buf.clone(), fctx);
13943 }
13944 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
13945 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
13946 // plane's own `reconstruct`/`read_plane` call below (never both planes at
13947 // once), since Y's own set-then-take already emptied the slot by the time
13948 // either of these run.
13949 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
13950 (
13951 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
13952 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
13953 )
13954 });
13955 // The chroma half of the intrabc prediction rides the same per-plane
13956 // override slot the UV-palette buffers do (set fresh before each plane's
13957 // own `reconstruct`/`read_plane` call below).
13958 let palette_uv_bufs = match &intrabc_bufs {
13959 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
13960 None => palette_uv_bufs,
13961 };
13962 if skip {
13963 // A skipped block codes no residual syntax at all (spec 5.11.34):
13964 // straight prediction, on every plane.
13965 //
13966 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
13967 // is skipped (only an INTER skip forces the largest transform), and
13968 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
13969 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
13970 // already written left/above of it inside this same block. Predicting
13971 // the whole `side`x`side` at once gives a different (uniformly off by
13972 // ~1) answer, which is exactly the residue this lane was chasing.
13973 // The palette/intrabc override path keeps the single-call shape (its
13974 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
13975 // untested for skip and unreachable in these streams).
13976 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
13977 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
13978 // per-unit prediction is keyed on the transform being smaller than
13979 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
13980 // narrower meaning (a READ split tx depth).
13981 let split_tx_skip =
13982 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
13983 if split_tx_skip {
13984 if tx_select {
13985 hit!(SKIP_SPLIT_TX_HITS);
13986 }
13987 let n_axis = side / logical_tx;
13988 for tu_row in 0..n_axis {
13989 for tu_col in 0..n_axis {
13990 let tu_px = px + tu_col * logical_tx;
13991 let tu_py = py + tu_row * logical_tx;
13992 if tu_px >= y.true_width || tu_py >= y.true_height {
13993 continue;
13994 }
13995 let tu_reach = tu_reach(
13996 side,
13997 side,
13998 tu_col * logical_tx,
13999 tu_row * logical_tx,
14000 logical_tx,
14001 reach,
14002 px,
14003 py,
14004 y.width,
14005 y.height, fctx,
14006 );
14007 push_intra(0,
14008 tu_px,
14009 tu_py,
14010 logical_tx,
14011 mode,
14012 angle_delta_y,
14013 tu_reach,
14014 &ZERO_RESIDUAL[..logical_tx * logical_tx],
14015 None,
14016 filter_intra,
14017 smooth_neighbor, fctx,
14018 );
14019 }
14020 }
14021 } else {
14022 push_intra(0,
14023 px,
14024 py,
14025 side,
14026 mode,
14027 angle_delta_y,
14028 reach,
14029 &ZERO_RESIDUAL[..side * side],
14030 None,
14031 filter_intra,
14032 smooth_neighbor, fctx,
14033 );
14034 }
14035 let ac = alpha.map(|_| cfl_src(px, py, side));
14036 let cn = (chroma_side / chroma_tx).max(1);
14037 for cu_row in 0..cn {
14038 for cu_col in 0..cn {
14039 let luma_span = chroma_tx * 2;
14040 let cu_r = if cn == 1 {
14041 reach
14042 } else {
14043 tu_reach(
14044 side, side,
14045 cu_col * luma_span, cu_row * luma_span, luma_span,
14046 reach, px, py, y.width, y.height, fctx,
14047 )
14048 };
14049 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14050 if let Some((ub, _)) = &palette_uv_bufs {
14051 set_palette_pred(ub.clone(), fctx);
14052 }
14053 push_intra(1,
14054 cu_x,
14055 cu_y,
14056 chroma_tx,
14057 uv_predict_mode,
14058 angle_delta_uv,
14059 cu_r,
14060 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14061 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14062 None,
14063 smooth_neighbor_uv, fctx,
14064 );
14065 if let Some((_, vb)) = &palette_uv_bufs {
14066 set_palette_pred(vb.clone(), fctx);
14067 }
14068 push_intra(2,
14069 cu_x,
14070 cu_y,
14071 chroma_tx,
14072 uv_predict_mode,
14073 angle_delta_uv,
14074 cu_r,
14075 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14076 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14077 None,
14078 smooth_neighbor_uv, fctx,
14079 );
14080 }
14081 }
14082 let luma_grid = vec![0i32; side * side];
14083 let u_grid = vec![0i32; chroma_side * chroma_side];
14084 let v_grid = vec![0i32; chroma_side * chroma_side];
14085 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14086 } else if logical_tx == side {
14087 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
14088 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
14089 // that arm was redundant -- and wrong at 128, where
14090 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
14091 // block is four units whether or not `tx_select` is on.
14092 // A single luma transform unit -- the old path, unchanged (including
14093 // the 64x64 corner case, `logical_tx == side == 64` with
14094 // `coeff_tx_side == 32`).
14095 let around = neighbours.around(at, side);
14096 let luma_grid = read_plane(
14097 dec,
14098 cdfs,
14099 luma_set,
14100 luma_scan,
14101 0,
14102 around[0],
14103 mode,
14104 mode,
14105 angle_delta_y,
14106 reach,
14107 y,
14108 px,
14109 py,
14110 side,
14111 coeff_tx_side,
14112 base_q_idx,
14113 None,
14114 filter_intra,
14115 None,
14116 smooth_neighbor, fctx,
14117 )?;
14118 let ac = alpha.map(|_| cfl_src(px, py, side));
14119 // Armed for exactly this block's two chroma reads (see
14120 // [`INTRABC_CHROMA_TX`]); the luma call above just set
14121 // [`LUMA_TX_TYPE`] to the type it coded.
14122 if intrabc_dv.is_some() {
14123 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14124 }
14125 if let Some((ub, _)) = &palette_uv_bufs {
14126 set_palette_pred(ub.clone(), fctx);
14127 }
14128 let u_grid = read_plane(
14129 dec,
14130 cdfs,
14131 chroma_set,
14132 scans.1,
14133 1,
14134 around[1],
14135 mode,
14136 uv_predict_mode,
14137 angle_delta_uv,
14138 reach,
14139 u,
14140 cpx,
14141 cpy,
14142 chroma_side,
14143 chroma_tx,
14144 base_q_idx,
14145 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14146 None,
14147 None,
14148 smooth_neighbor_uv, fctx,
14149 )?;
14150 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14151 eprintln!(
14152 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
14153 &u.data[cpy * u.width + cpx..][..chroma_side]
14154 );
14155 }
14156 if let Some((_, vb)) = &palette_uv_bufs {
14157 set_palette_pred(vb.clone(), fctx);
14158 }
14159 let v_grid = read_plane(
14160 dec,
14161 cdfs,
14162 chroma_set,
14163 scans.1,
14164 2,
14165 around[2],
14166 mode,
14167 uv_predict_mode,
14168 angle_delta_uv,
14169 reach,
14170 v,
14171 cpx,
14172 cpy,
14173 chroma_side,
14174 chroma_tx,
14175 base_q_idx,
14176 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14177 None,
14178 None,
14179 smooth_neighbor_uv, fctx,
14180 )?;
14181 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14182 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14183 } else {
14184 // Several luma transform units, raster order (spec
14185 // `transform_block`'s loop): the block's resolved transform is
14186 // genuinely smaller than its own side, so each tile of it predicts
14187 // and codes independently, its own context read fresh off whatever
14188 // the earlier tiles in this same block already wrote -- the same
14189 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
14190 let n_axis = side / logical_tx;
14191 let cn = (chroma_side / chroma_tx).max(1);
14192 // libaom's transform-block loop is over 64x64 luma "mu" chunks
14193 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
14194 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
14195 // before moving to the next one. Below 128 a block is a single chunk,
14196 // so this is byte-for-byte the all-luma-then-all-chroma order that has
14197 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
14198 // and reading all four luma units first desyncs the tile at the second
14199 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
14200 let nchunk = (side / 64).max(1);
14201 // `cn > 1` means the uv plane block is larger than the uv transform,
14202 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
14203 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
14204 let tpc = (n_axis / nchunk).max(1);
14205 let cpc = (cn / nchunk).max(1);
14206 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14207 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
14208 for ch_row in 0..nchunk {
14209 for ch_col in 0..nchunk {
14210 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14211 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14212 let tu_mi = (
14213 mi_r + tu_row * (logical_tx / MI),
14214 mi_c + tu_col * (logical_tx / MI),
14215 );
14216 let tu_px = px + tu_col * logical_tx;
14217 let tu_py = py + tu_row * logical_tx;
14218 // Same libaom clip as `decode_rect_split`'s loop above; a
14219 // square block only hangs off the frame when the frame's mi
14220 // dimensions are odd at the block's own level.
14221 if tu_px >= y.true_width || tu_py >= y.true_height {
14222 continue;
14223 }
14224 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14225 // A transform unit inside a block is NOT a block at that
14226 // position (lane-palette2 r12): `Reach::of` granted the
14227 // top-right 8x8 unit of a 16x16 D203 block bottom-left
14228 // pixels libaom refuses outright (`col_off > 0`), which is
14229 // the diagonal wedge seed 46 reconstructed wrong.
14230 let tu_reach = tu_reach(
14231 side,
14232 side,
14233 tu_col * logical_tx,
14234 tu_row * logical_tx,
14235 logical_tx,
14236 reach,
14237 px,
14238 py,
14239 y.width,
14240 y.height, fctx,
14241 );
14242 // This transform unit's own bsize (`logical_tx`) is smaller
14243 // than the block it sits in (`side`), so `txb_skip_ctx` is
14244 // the neighbour-magnitude table, not the lone-TU 0 (spec
14245 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
14246 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14247 if let Some(buf) = &palette_y_buf {
14248 hit!(PALETTE_SPLIT_TX_HITS);
14249 let mut window = vec![0u16; logical_tx * logical_tx];
14250 for row in 0..logical_tx {
14251 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
14252 window[row * logical_tx..][..logical_tx]
14253 .copy_from_slice(&buf[src..][..logical_tx]);
14254 }
14255 set_palette_pred(window, fctx);
14256 }
14257 let tu_grid = read_plane(
14258 dec,
14259 cdfs,
14260 luma_set,
14261 luma_scan,
14262 0,
14263 tu_around,
14264 mode,
14265 mode,
14266 angle_delta_y,
14267 tu_reach,
14268 y,
14269 tu_px,
14270 tu_py,
14271 logical_tx,
14272 // The unit's own COEFFICIENT grid, half its side at
14273 // TX_64X64 (a 64-point transform codes nothing past 32);
14274 // identical to `logical_tx` at every smaller size
14275 // (lane-sb128b r1).
14276 coeff_tx_side,
14277 base_q_idx,
14278 None,
14279 filter_intra,
14280 Some(tu_skip_ctx),
14281 smooth_neighbor, fctx,
14282 )?;
14283 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14284 eprintln!(
14285 "TRACE tu_bitpos mi=({},{}) tell={}",
14286 tu_mi.0,
14287 tu_mi.1,
14288 dec.debug_bitpos()
14289 );
14290 }
14291 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14292 }
14293 }
14294 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
14295 // this still runs after every luma unit of the block.
14296 let ac = alpha.map(|_| cfl_src(px, py, side));
14297 // The block's uv plane block is `chroma_side` across but its uv
14298 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
14299 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
14300 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
14301 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
14302 // FOUR units (lane-sb128b r2) -- one per mu chunk.
14303 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
14304 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
14305 // The chroma context arrays are indexed in LUMA mi, so this
14306 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
14307 // pixels span `2 * chroma_tx` luma ones.
14308 let luma_span = chroma_tx * 2;
14309 let cu_mi = (
14310 mi_r + cu_row * (luma_span / MI),
14311 mi_c + cu_col * (luma_span / MI),
14312 );
14313 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14314 let cu_reach = if cn == 1 {
14315 reach
14316 } else {
14317 tu_reach(
14318 side, side,
14319 cu_col * luma_span, cu_row * luma_span, luma_span,
14320 reach, px, py, y.width, y.height, fctx,
14321 )
14322 };
14323 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14324 if let Some((ub, _)) = &palette_uv_bufs {
14325 set_palette_pred(ub.clone(), fctx);
14326 }
14327 let u_grid = read_plane(
14328 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
14329 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
14330 chroma_tx, chroma_tx, base_q_idx,
14331 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14332 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14333 )?;
14334 if let Some((_, vb)) = &palette_uv_bufs {
14335 set_palette_pred(vb.clone(), fctx);
14336 }
14337 let v_grid = read_plane(
14338 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
14339 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
14340 chroma_tx, chroma_tx, base_q_idx,
14341 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14342 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14343 )?;
14344 if cn > 1 {
14345 hit!(CHROMA_SPLIT_TX_HITS);
14346 // Immediately, so the NEXT unit of this same block reads
14347 // this one's coefficient context (libaom's chroma
14348 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
14349 // 1 from this left neighbour -- measured against aomdec).
14350 // The same writes are replayed after `record_split_luma`
14351 // below, which would otherwise clobber them whole-block.
14352 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14353 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14354 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
14355 }
14356 last_grids = [u_grid, v_grid];
14357 }
14358 }
14359 }
14360 }
14361 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
14362 // context write; at `cn > 1` the per-unit writes above are what the
14363 // next block reads, so they run after this (last writer wins).
14364 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
14365 for (cu_mi, luma_span, u_grid, v_grid) in &units {
14366 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
14367 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
14368 }
14369 }
14370 // Unconditional, `size == 0` for a non-palette block: clears any stale
14371 // neighbour palette state the same way [`Neighbours::record`] always
14372 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
14373 // (the split-luma-TU branch above always refuses before reaching here
14374 // when `palette_y` is `Some`, so it is never live for that branch).
14375 let (py_size, py_colors) = palette_y
14376 .as_ref()
14377 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14378 neighbours.record_palette_y(at, side, py_size, py_colors);
14379 let (puv_size, puv_colors) = palette_uv
14380 .as_ref()
14381 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14382 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
14383 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
14384 neighbours.fill_lf_grid(
14385 (r * (SUB / MI), c * (SUB / MI)),
14386 side / MI,
14387 logical_tx as u8,
14388 0, fctx,
14389 );
14390 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
14391 // `decode_block`, key frames included, and the intrabc var-tx read above
14392 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
14393 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
14394 // row. Armed by the frame's own `allow_intrabc` so every other key frame
14395 // (whose readers use the deblock-grid approximation) is untouched.
14396 if allow_intrabc {
14397 set_txfm_ctxs(
14398 neighbours,
14399 (mi_r, mi_c),
14400 logical_tx,
14401 side / MI,
14402 side / MI,
14403 skip && intrabc_dv.is_some(),
14404 );
14405 }
14406 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
14407 Ok(())
14408}
14409
14410thread_local! {
14411 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
14412 /// root's HORZ arm, and 64x128 ones at its VERT arm.
14413 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14414 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14415 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
14416 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
14417 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
14418 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
14419 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
14420 /// inter frame) -- (128x64, 64x128).
14421 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
14422 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
14423 /// handed back var-tx leaves, so the per-transform-unit luma publication
14424 /// loop never ran and the block has to clear its own luma coefficient
14425 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
14426 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
14427 /// non-vacuous.
14428 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14429}
14430
14431/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
14432pub fn skip_vartx_luma_reset_hits() -> usize {
14433 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
14434}
14435
14436/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
14437pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
14438 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
14439}
14440
14441/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
14442/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
14443pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
14444 (
14445 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
14446 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
14447 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
14448 )
14449}
14450
14451/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
14452/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
14453/// `decode_inter_block`'s own rect path).
14454///
14455/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
14456/// transform unit, with the 128-specific geometry:
14457/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
14458/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
14459/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
14460/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
14461/// same CDF a 64x64 square block reads).
14462/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
14463/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
14464/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
14465/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
14466/// a chunk before moving to the next (the interleave lane-sb128b r3
14467/// measured at the 128x128 NONE root).
14468/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
14469/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
14470/// No CfL, no filter intra (both cap at 32x32) and no palette
14471/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
14472/// reader's own size gates already say so, and the guard below is defensive.
14473#[allow(clippy::too_many_arguments)]
14474fn decode_block_128rect(
14475 dec: &mut SymbolDecoder,
14476 cdfs: &mut Cdfs,
14477 neighbours: &mut Neighbours,
14478 at: (usize, usize),
14479 bw: usize,
14480 bh: usize,
14481 y: &mut PlaneBuf<'static>,
14482 u: &mut PlaneBuf<'static>,
14483 v: &mut PlaneBuf<'static>,
14484 base_q_idx: u8,
14485 enable_filter_intra: bool,
14486 allow_screen_content_tools: bool,
14487 tx_select: bool,
14488 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14489) -> Result<()> {
14490 let (r, c) = at;
14491 let (px, py) = (c * SUB, r * SUB);
14492 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14493 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14494 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14495 let palette_uv_cache = neighbours.palette_uv_cache(at);
14496 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14497 read_intra_mode_rect(
14498 dec,
14499 cdfs,
14500 nb_above_mode,
14501 nb_left_mode,
14502 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
14503 // 13-symbol no-CFL CDF here, never the 14-symbol one.
14504 false,
14505 true,
14506 bw,
14507 bh,
14508 enable_filter_intra,
14509 neighbours.skip_txfm_ctx(mi_r, mi_c),
14510 allow_screen_content_tools,
14511 Some((palette_ctx, &palette_cache)),
14512 &palette_uv_cache,
14513 mi_r,
14514 mi_c, fctx,
14515 )?;
14516 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
14517 return Err(unsupported(
14518 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
14519 their size gates caps at 64x64 or below, so none of these symbols exists there)",
14520 ));
14521 }
14522 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14523 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14524 if smooth_neighbor {
14525 hit!(SMOOTH_LUMA_HITS);
14526 }
14527 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
14528 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
14529 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
14530 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
14531 let depth = if tx_select {
14532 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
14533 // the real `TXFM_CONTEXT` bands, and compares them against
14534 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
14535 // every 128-axis block, hence the `min(64)`.
14536 let ctx = if in_inter {
14537 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
14538 } else {
14539 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
14540 };
14541 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14542 } else {
14543 0
14544 };
14545 if depth != 0 {
14546 hit!(TX_DEPTH_HITS);
14547 }
14548 hit_do! {
14549 INTRA_SB128_DEPTH_HITS.with(|c| {
14550 let mut h = c.get();
14551 h[depth.min(2)] += 1;
14552 c.set(h);
14553 });
14554 }
14555 let logical_tx = 64 >> depth;
14556 // A 64-point transform codes nothing past its low 32 coefficients.
14557 let coeff_tx_side = logical_tx.min(32);
14558 let luma_set = txbset_for(logical_tx, reduced_tx_set);
14559 let luma_scan = default_scan(coeff_tx_side);
14560 let chroma_tx = 32;
14561 let chroma_scan = default_scan(chroma_tx);
14562 let (cpx, cpy) = (px / 2, py / 2);
14563 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
14564 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14565 let (nch_x, nch_y) = (bw / 64, bh / 64);
14566 // One 32x32 chroma unit per mu chunk, per plane.
14567 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
14568 let tpc = 64 / logical_tx;
14569 let zero_tu = vec![0i32; logical_tx * logical_tx];
14570 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
14571 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14572 let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new();
14573 for ch_row in 0..nch_y {
14574 for ch_col in 0..nch_x {
14575 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14576 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14577 let tu_mi = (
14578 mi_r + tu_row * (logical_tx / MI),
14579 mi_c + tu_col * (logical_tx / MI),
14580 );
14581 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
14582 // libaom clips the transform loop to
14583 // `max_blocks_wide/high`: a unit whose top-left sample is
14584 // outside the frame is never coded.
14585 if tu_px >= y.true_width || tu_py >= y.true_height {
14586 continue;
14587 }
14588 // Edge availability of a unit INSIDE a block, with the
14589 // 128 geometry -- `has_top_right` is false for a block
14590 // whose largest side is > 64, which [`Reach::of_rect`]
14591 // already answered for the block and [`tu_reach`] carries
14592 // down to the units on its own top row.
14593 let tu_r = tu_reach(
14594 bw,
14595 bh,
14596 tu_col * logical_tx,
14597 tu_row * logical_tx,
14598 logical_tx,
14599 reach,
14600 px,
14601 py,
14602 y.width,
14603 y.height, fctx,
14604 );
14605 if skip {
14606 push_intra(0,
14607 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
14608 None, smooth_neighbor, fctx,
14609 );
14610 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
14611 continue;
14612 }
14613 // The unit is smaller than its block, so `txb_skip_ctx`
14614 // is the neighbour-magnitude table, never the lone-TU 0.
14615 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14616 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14617 let tu_grid = read_plane(
14618 dec,
14619 cdfs,
14620 luma_set,
14621 &luma_scan,
14622 0,
14623 tu_around,
14624 mode,
14625 mode,
14626 angle_delta_y,
14627 tu_r,
14628 y,
14629 tu_px,
14630 tu_py,
14631 logical_tx,
14632 coeff_tx_side,
14633 base_q_idx,
14634 None,
14635 None,
14636 Some(tu_skip_ctx),
14637 smooth_neighbor, fctx,
14638 )?;
14639 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14640 }
14641 }
14642 // The chroma context arrays are indexed in LUMA mi, so this
14643 // unit's anchor is its own 64x64 mu chunk.
14644 let luma_span = chroma_tx * 2;
14645 let cu_mi = (
14646 mi_r + ch_row * (luma_span / MI),
14647 mi_c + ch_col * (luma_span / MI),
14648 );
14649 let cu_r = tu_reach(
14650 bw,
14651 bh,
14652 ch_col * luma_span,
14653 ch_row * luma_span,
14654 luma_span,
14655 reach,
14656 px,
14657 py,
14658 y.width,
14659 y.height, fctx,
14660 );
14661 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
14662 if skip {
14663 push_intra(1,
14664 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14665 None, smooth_neighbor_uv, fctx,
14666 );
14667 push_intra(2,
14668 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14669 None, smooth_neighbor_uv, fctx,
14670 );
14671 continue;
14672 }
14673 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14674 let u_grid = read_plane(
14675 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
14676 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14677 Some(3), smooth_neighbor_uv, fctx,
14678 )?;
14679 let v_grid = read_plane(
14680 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
14681 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14682 Some(3), smooth_neighbor_uv, fctx,
14683 )?;
14684 hit!(CHROMA_SPLIT_TX_HITS);
14685 // Immediately, so the NEXT unit of this same block reads this
14686 // one's coefficient context; replayed after `record_split_luma_rect`
14687 // below, which would otherwise clobber them whole-block.
14688 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14689 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14690 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
14691 last_grids = [u_grid, v_grid];
14692 }
14693 }
14694 if skip {
14695 neighbours.record_rect(
14696 at,
14697 bw,
14698 bh,
14699 mode,
14700 uv_predict_mode,
14701 &[
14702 &ZERO_RESIDUAL[..bw * bh],
14703 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14704 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14705 ],
14706 );
14707 } else {
14708 neighbours.record_split_luma_rect(
14709 at,
14710 bw,
14711 bh,
14712 mode,
14713 uv_predict_mode,
14714 [&last_grids[0], &last_grids[1]],
14715 );
14716 for (cu_mi, u_grid, v_grid) in &units {
14717 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
14718 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
14719 }
14720 }
14721 // No palette exists at this size; the unconditional stamp clears any
14722 // stale neighbour palette state, as every other block path does.
14723 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
14724 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
14725 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14726 neighbours.fill_lf_grid_rect(
14727 (mi_r, mi_c),
14728 bw / MI,
14729 bh / MI,
14730 logical_tx as u8,
14731 logical_tx as u8,
14732 0, fctx,
14733 );
14734 if in_inter {
14735 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
14736 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
14737 // inter frame, intra ones included: an intra block stamps its
14738 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
14739 // A key frame has no var-tx tree and its readers use the deblock grid,
14740 // so this is the inter path's alone.
14741 txfm_partition_update_rect(
14742 neighbours,
14743 (mi_r, mi_c),
14744 (logical_tx, logical_tx),
14745 (bw, bh),
14746 );
14747 hit_do! {
14748 INTRA128_IN_INTER_HITS.with(|c| {
14749 let mut h = c.get();
14750 h[usize::from(bw < bh)] += 1;
14751 c.set(h);
14752 });
14753 }
14754 } else if bw > bh {
14755 hit!(INTRA_SB128_HORZ_HITS);
14756 } else {
14757 hit!(INTRA_SB128_VERT_HITS);
14758 }
14759 Ok(())
14760}
14761
14762
14763/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
14764/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
14765/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
14766/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
14767/// just-decoded mode, not the enclosing slot's stale one, is the true
14768/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
14769/// units, which is what its coefficient context (finer than [`SUB`]) is read
14770/// at. Returns the mode this leaf decoded, for the caller's own
14771/// `prev_leaf`/final mode-writeback bookkeeping.
14772#[allow(clippy::too_many_arguments)]
14773/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
14774/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
14775/// `above_mode[col]`, and its true above neighbour is the mi directly above
14776/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
14777/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
14778/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
14779/// (bottom-right) into both, as this path did, is right only when all four
14780/// leaves happen to share a mode. `done` may be short at the true frame edge
14781/// (the straddle caller filters positions off the frame), so each side falls
14782/// back to the last leaf actually decoded.
14783fn write_back_split_modes(
14784 neighbours: &mut Neighbours,
14785 done: &[((usize, usize), usize)],
14786 parent_mi: (usize, usize),
14787 slot: (usize, usize),
14788) {
14789 let (sr, sc) = slot;
14790 let Some(&(_, last)) = done.last() else {
14791 return;
14792 };
14793 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
14794 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
14795 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
14796}
14797
14798fn decode_leaf8(
14799 dec: &mut SymbolDecoder,
14800 cdfs: &mut Cdfs,
14801 neighbours: &mut Neighbours,
14802 outer_at: (usize, usize),
14803 leaf_mi: (usize, usize),
14804 scans: (&[u16], &[u16]),
14805 prev_leaf: Option<((usize, usize), usize)>,
14806 y: &mut PlaneBuf<'static>,
14807 u: &mut PlaneBuf<'static>,
14808 v: &mut PlaneBuf<'static>,
14809 base_q_idx: u8,
14810 enable_filter_intra: bool,
14811 allow_screen_content_tools: bool,
14812 allow_intrabc: bool,
14813 tx_select: bool,
14814 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14815) -> Result<usize> {
14816 let (r, c) = outer_at;
14817 // lane-modectx r1: the group's own availability-correct fallback pair, not
14818 // the raw coarse bands (which leak across a tile edge -- see
14819 // `modes_above_left`).
14820 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
14821 if let Some(((pr, pc), pmode)) = prev_leaf {
14822 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
14823 above_mode = pmode;
14824 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
14825 left_mode = pmode;
14826 }
14827 }
14828 // The mi-exact neighbour wins over both the coarse 16x16 slot and
14829 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
14830 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
14831 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
14832 // lane-rectsplitx r2 swept this arm into
14833 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
14834 // "no neighbour" at a tile edge, where the coarse cell holds the block
14835 // above/left of it inside the same 16x16.
14836 let (above_mode, left_mode) =
14837 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
14838 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
14839 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
14840 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
14841 // this leaf's `smooth_neighbor` is built from -- passing `false` here
14842 // filtered a directional chroma block's edge at the wrong strength
14843 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
14844 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
14845 // with the coarse [`SUB`] slot as the fallback when no block recorded
14846 // that exact mi cell.
14847 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
14848 if smooth_neighbor {
14849 hit!(SMOOTH_LUMA_HITS);
14850 }
14851 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
14852 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
14853 // `decode_block` caller at 16x16 and up.
14854 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
14855 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
14856 // `read_palette_mode_info`), at its REAL mi position -- passing
14857 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
14858 // moment a real 8x8 palette block fired, which is where every 8-bit
14859 // `--tune-content=screen --min-partition-size=8` stream stopped.
14860 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
14861 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
14862 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14863 read_intra_mode(
14864 dec,
14865 cdfs,
14866 above_mode,
14867 left_mode,
14868 true,
14869 8,
14870 enable_filter_intra,
14871 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
14872 allow_screen_content_tools,
14873 allow_intrabc,
14874 Some((palette_ctx, &palette_cache)),
14875 &palette_uv_cache,
14876 leaf_mi.0,
14877 leaf_mi.1, fctx,
14878 )?;
14879 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
14880 // `read_intra_mode` and then decoded the block as if it were ordinary
14881 // intra. libaom's `is_inter_block` counts an intrabc block
14882 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
14883 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
14884 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
14885 // same value with a different interval, so the tile desynced at the very
14886 // next symbol (class `wrong-alphabet-same-value`). Everything below
14887 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
14888 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
14889 if intrabc_dv.is_some() {
14890 hit!(LEAF8_INTRABC_HITS);
14891 }
14892 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
14893 // index map, mapped through the base colours, IS the block's prediction --
14894 // carried to the next `reconstruct`/`read_plane` through the same
14895 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
14896 let palette_y_buf: Option<Vec<u16>> = palette_y
14897 .as_ref()
14898 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
14899 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
14900 (
14901 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14902 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14903 )
14904 });
14905 let (pal_y_size, pal_y_colors) =
14906 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14907 let (pal_uv_size, pal_uv_colors) =
14908 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14909 if palette_y.is_some() || palette_uv.is_some() {
14910 hit!(PALETTE_LEAF8_HITS);
14911 }
14912 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14913 DC_PRED
14914 } else {
14915 uv_mode
14916 };
14917 neighbours.above_uv_mode[c] = uv_predict_mode;
14918 neighbours.left_uv_mode[r] = uv_predict_mode;
14919 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
14920 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
14921 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
14922 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
14923 // transform units, same raster-order per-TU pattern `decode_block`'s
14924 // multi-TU branch runs).
14925 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
14926 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
14927 // intrabc block, so a SKIPPED one takes the largest transform and an
14928 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
14929 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
14930 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
14931 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
14932 let mut leaves = Vec::new();
14933 let mi_cols = 2 * y.true_width.div_ceil(8);
14934 let mi_rows = 2 * y.true_height.div_ceil(8);
14935 read_var_tx_size(
14936 dec,
14937 cdfs,
14938 neighbours,
14939 leaf_mi,
14940 8,
14941 (
14942 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
14943 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
14944 ),
14945 (8, 8),
14946 0,
14947 0,
14948 0,
14949 &mut leaves,
14950 );
14951 hit!(INTRABC_VARTX_HITS);
14952 leaves.first().map_or(8, |l| l.2)
14953 } else if tx_select && intrabc_dv.is_none() {
14954 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
14955 } else {
14956 8
14957 };
14958 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
14959 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
14960 let (cpx, cpy) = (px / 2, py / 2);
14961 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
14962 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
14963 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
14964 // the full-pel block vector, with the BILINEAR kernel libaom forces.
14965 flush_recon(fctx, y, u, v);
14966 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14967 let mut yb = vec![0u16; 8 * 8];
14968 mc::predict_with_filter(
14969 &y.data, y.width, y.true_width, y.true_height,
14970 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14971 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14972 );
14973 let mut ub = vec![0u16; 4 * 4];
14974 mc::predict_with_filter(
14975 &u.data, u.width, u.true_width, u.true_height,
14976 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14977 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14978 );
14979 let mut vb = vec![0u16; 4 * 4];
14980 mc::predict_with_filter(
14981 &v.data, v.width, v.true_width, v.true_height,
14982 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14983 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14984 );
14985 (yb, ub, vb)
14986 });
14987 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
14988 // `decode_block` uses: set fresh right before each plane's own
14989 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
14990 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
14991 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
14992 // first shape that reaches that loop with an override set).
14993 let palette_y_buf = match &intrabc_bufs {
14994 Some((yb, _, _)) => Some(yb.clone()),
14995 None => palette_y_buf,
14996 };
14997 let (luma_grid, u_grid, v_grid);
14998 if skip {
14999 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
15000 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
15001 // transform units, each off the units already written left/above of
15002 // it inside this same leaf -- an intra block's transform size is read
15003 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
15004 // A palette block's prediction is the whole-block index map, never
15005 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
15006 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
15007 // even when `tx_depth` resolved to TX_4X4.
15008 if resolved == 4 && palette_y_buf.is_none() {
15009 hit!(SKIP_SPLIT_TX_HITS);
15010 for tu_row in 0..2 {
15011 for tu_col in 0..2 {
15012 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
15013 if tu_px >= y.true_width || tu_py >= y.true_height {
15014 continue;
15015 }
15016 let tu_reach = tu_reach(
15017 8,
15018 8,
15019 tu_col * 4,
15020 tu_row * 4,
15021 4,
15022 reach,
15023 px,
15024 py,
15025 y.width,
15026 y.height, fctx,
15027 );
15028 push_intra(0,
15029 tu_px,
15030 tu_py,
15031 4,
15032 mode,
15033 angle_delta_y,
15034 tu_reach,
15035 &ZERO_RESIDUAL[..16],
15036 None,
15037 filter_intra,
15038 smooth_neighbor, fctx,
15039 );
15040 }
15041 }
15042 } else {
15043 if let Some(buf) = &palette_y_buf {
15044 set_palette_pred(buf.clone(), fctx);
15045 }
15046 push_intra(0,
15047 px,
15048 py,
15049 8,
15050 mode,
15051 angle_delta_y,
15052 reach,
15053 &ZERO_RESIDUAL[..64],
15054 None,
15055 filter_intra,
15056 smooth_neighbor, fctx,
15057 );
15058 }
15059 let ac = alpha.map(|_| cfl_src(px, py, 8));
15060 if let Some((_, ub, _)) = &intrabc_bufs {
15061 set_palette_pred(ub.clone(), fctx);
15062 } else if let Some((ub, _)) = &palette_uv_bufs {
15063 set_palette_pred(ub.clone(), fctx);
15064 }
15065 push_intra(1,
15066 cpx,
15067 cpy,
15068 4,
15069 uv_predict_mode,
15070 angle_delta_uv,
15071 reach,
15072 &ZERO_RESIDUAL[..16],
15073 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15074 None,
15075 smooth_neighbor_uv, fctx,
15076 );
15077 if let Some((_, _, vb)) = &intrabc_bufs {
15078 set_palette_pred(vb.clone(), fctx);
15079 } else if let Some((_, vb)) = &palette_uv_bufs {
15080 set_palette_pred(vb.clone(), fctx);
15081 }
15082 push_intra(2,
15083 cpx,
15084 cpy,
15085 4,
15086 uv_predict_mode,
15087 angle_delta_uv,
15088 reach,
15089 &ZERO_RESIDUAL[..16],
15090 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15091 None,
15092 smooth_neighbor_uv, fctx,
15093 );
15094 luma_grid = Grid::Zero(64);
15095 u_grid = Grid::Zero(16);
15096 v_grid = Grid::Zero(16);
15097 } else if resolved != 4 {
15098 let around = neighbours.around_mi(leaf_mi, 8);
15099 if let Some(buf) = &palette_y_buf {
15100 set_palette_pred(buf.clone(), fctx);
15101 }
15102 luma_grid = read_plane(
15103 dec,
15104 cdfs,
15105 if intrabc_dv.is_some() {
15106 txbset_for_inter(8, reduced_tx_set)
15107 } else if reduced_tx_set {
15108 TxbSet::Luma8
15109 } else {
15110 TxbSet::Luma8Set1
15111 },
15112 scans.0,
15113 0,
15114 around[0],
15115 mode,
15116 mode,
15117 angle_delta_y,
15118 reach,
15119 y,
15120 px,
15121 py,
15122 8,
15123 TX8,
15124 base_q_idx,
15125 None,
15126 filter_intra,
15127 None,
15128 smooth_neighbor, fctx,
15129 )?;
15130 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
15131 // an intrabc block's chroma tx_type is the colocated LUMA transform's
15132 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
15133 if intrabc_dv.is_some() {
15134 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15135 }
15136 let ac = alpha.map(|_| cfl_src(px, py, 8));
15137 if let Some((_, ub, _)) = &intrabc_bufs {
15138 set_palette_pred(ub.clone(), fctx);
15139 } else if let Some((ub, _)) = &palette_uv_bufs {
15140 set_palette_pred(ub.clone(), fctx);
15141 }
15142 u_grid = read_plane(
15143 dec,
15144 cdfs,
15145 TxbSet::Chroma4,
15146 scans.1,
15147 1,
15148 around[1],
15149 mode,
15150 uv_predict_mode,
15151 angle_delta_uv,
15152 reach,
15153 u,
15154 cpx,
15155 cpy,
15156 4,
15157 TX4,
15158 base_q_idx,
15159 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15160 None,
15161 None,
15162 smooth_neighbor_uv, fctx,
15163 )?;
15164 if let Some((_, _, vb)) = &intrabc_bufs {
15165 set_palette_pred(vb.clone(), fctx);
15166 } else if let Some((_, vb)) = &palette_uv_bufs {
15167 set_palette_pred(vb.clone(), fctx);
15168 }
15169 v_grid = read_plane(
15170 dec,
15171 cdfs,
15172 TxbSet::Chroma4,
15173 scans.1,
15174 2,
15175 around[2],
15176 mode,
15177 uv_predict_mode,
15178 angle_delta_uv,
15179 reach,
15180 v,
15181 cpx,
15182 cpy,
15183 4,
15184 TX4,
15185 base_q_idx,
15186 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15187 None,
15188 None,
15189 smooth_neighbor_uv, fctx,
15190 )?;
15191 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
15192 // two chroma reads (`decode_block`'s own tail does the same) -- left
15193 // set, every later chroma block would inherit this luma tx_type,
15194 // which picks the scan and the inverse transform.
15195 fctx.intrabc_chroma_tx.with(|c| c.set(None));
15196 } else {
15197 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
15198 // grid of 4x4 transform units, each predicted from the leaf's own
15199 // 8x8 `mode` and reading its own fresh context off the earlier
15200 // units in this same leaf (the same per-TU pattern `decode_block`'s
15201 // multi-TU branch runs at bigger blocks).
15202 for tu_row in 0..2 {
15203 for tu_col in 0..2 {
15204 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15205 let tu_px = px + tu_col * 4;
15206 let tu_py = py + tu_row * 4;
15207 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15208 if crate::encode::Reach::in_vert_ab() {
15209 hit!(VERT_AB_TX4_HITS);
15210 }
15211 let tu_reach = tu_reach(
15212 8,
15213 8,
15214 tu_col * 4,
15215 tu_row * 4,
15216 4,
15217 reach,
15218 px,
15219 py,
15220 y.width,
15221 y.height, fctx,
15222 );
15223 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15224 // Each 4x4 unit predicts from its own window of the block's
15225 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
15226 // 16x16 and up) -- the whole-block buffer would be taken by
15227 // the FIRST unit and indexed at the wrong stride.
15228 if let Some(buf) = &palette_y_buf {
15229 hit!(PALETTE_SPLIT_TX_HITS);
15230 let mut window = vec![0u16; 16];
15231 for row in 0..4 {
15232 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
15233 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
15234 }
15235 set_palette_pred(window, fctx);
15236 }
15237 let tu_grid = read_plane(
15238 dec,
15239 cdfs,
15240 if intrabc_dv.is_some() {
15241 txbset_for_inter(4, reduced_tx_set)
15242 } else if reduced_tx_set {
15243 TxbSet::Luma4
15244 } else {
15245 TxbSet::Luma4Set1
15246 },
15247 scans.1,
15248 0,
15249 tu_around,
15250 mode,
15251 mode,
15252 angle_delta_y,
15253 tu_reach,
15254 y,
15255 tu_px,
15256 tu_py,
15257 4,
15258 4,
15259 base_q_idx,
15260 None,
15261 filter_intra,
15262 Some(tu_skip_ctx),
15263 smooth_neighbor, fctx,
15264 )?;
15265 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15266 eprintln!(
15267 "TRACE tu_bitpos mi=({},{}) tell={}",
15268 tu_mi.0,
15269 tu_mi.1,
15270 dec.debug_bitpos()
15271 );
15272 }
15273 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15274 }
15275 }
15276 let ac = alpha.map(|_| cfl_src(px, py, 8));
15277 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15278 if let Some((ub, _)) = &palette_uv_bufs {
15279 set_palette_pred(ub.clone(), fctx);
15280 }
15281 u_grid = read_plane(
15282 dec,
15283 cdfs,
15284 TxbSet::Chroma4,
15285 scans.1,
15286 1,
15287 chroma_around[1],
15288 mode,
15289 uv_predict_mode,
15290 angle_delta_uv,
15291 reach,
15292 u,
15293 cpx,
15294 cpy,
15295 4,
15296 TX4,
15297 base_q_idx,
15298 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15299 None,
15300 None,
15301 smooth_neighbor_uv, fctx,
15302 )?;
15303 if let Some((_, vb)) = &palette_uv_bufs {
15304 set_palette_pred(vb.clone(), fctx);
15305 }
15306 v_grid = read_plane(
15307 dec,
15308 cdfs,
15309 TxbSet::Chroma4,
15310 scans.1,
15311 2,
15312 chroma_around[2],
15313 mode,
15314 uv_predict_mode,
15315 angle_delta_uv,
15316 reach,
15317 v,
15318 cpx,
15319 cpy,
15320 4,
15321 TX4,
15322 base_q_idx,
15323 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15324 None,
15325 None,
15326 smooth_neighbor_uv, fctx,
15327 )?;
15328 // `record_split_luma` expects a `record`-style `(r, c)` position in
15329 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
15330 // already in mi units, so calling it here double-scaled the
15331 // position. Plane 0 is already correct per-TU from the
15332 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
15333 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
15334 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
15335 // leaf's own 8x8 side over `MI`).
15336 let side_mi = 2;
15337 for cell in 0..side_mi {
15338 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
15339 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
15340 }
15341 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15342 let bound_h = round_up_even(neighbours.mi_rows);
15343 let bound_w = round_up_even(neighbours.mi_cols);
15344 let u_state = neighbour_state(&u_grid);
15345 let v_state = neighbour_state(&v_grid);
15346 for cell in 0..side_mi {
15347 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15348 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15349 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15350 }
15351 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15352 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15353 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15354 }
15355 }
15356 // This leaf's own palette state into the mi-granular above/left bands
15357 // (sizes 0 when it used none, which is what clears a previous block's
15358 // palette out of the next block's ctx and colour cache).
15359 {
15360 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15361 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15362 }
15363 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15364 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
15365 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15366 // own copy; only an intrabc var-tx read consumes these bands on the intra
15367 // path, so the write is armed by `allow_intrabc`.
15368 if allow_intrabc {
15369 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
15370 }
15371 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15372 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15373 return Ok(mode);
15374 }
15375 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15376 // This leaf's own palette state into the mi-granular above/left bands
15377 // (sizes 0 when it used none, which is what clears a previous block's
15378 // palette out of the next block's ctx and colour cache).
15379 {
15380 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15381 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15382 }
15383 hit!(INTER8_SKIP_BAND_HITS);
15384 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15385 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
15386 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
15387 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
15388 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
15389 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
15390 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
15391 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
15392 // wrong CDF row, so the msac range diverged mid-frame with no refusal
15393 // (class `wrong-alphabet-same-value`; the ReelB key frame at
15394 // -ss 900, first bad luma sample row 186 col 1803).
15395 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
15396 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15397 // own copy; only an intrabc var-tx read consumes these bands on the intra
15398 // path, so the write is armed by `allow_intrabc`.
15399 if allow_intrabc {
15400 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
15401 }
15402 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15403 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
15404 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
15405 // publish its own cells exactly like `decode_block` does.
15406 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15407 Ok(mode)
15408}
15409
15410/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
15411/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
15412/// bottom, where no partition symbol is read at all -- `decode_block` runs
15413/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
15414/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
15415/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
15416/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
15417/// of the 2x2 4x4 group carries chroma syntax at all.
15418#[allow(clippy::too_many_arguments)]
15419fn read_intra_mode_sub8(
15420 dec: &mut SymbolDecoder,
15421 cdfs: &mut Cdfs,
15422 above_mode: usize,
15423 left_mode: usize,
15424 has_chroma: bool,
15425 enable_filter_intra: bool,
15426 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
15427 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
15428 // from the wrong row is the same VALUE with a different interval, so it
15429 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
15430 fi_class: usize,
15431 skip_ctx: usize,
15432 allow_intrabc: bool,
15433 mi_r: usize,
15434 mi_c: usize, fctx: &crate::decode::FrameCtx,
15435) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
15436 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15437 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15438 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
15439 }
15440 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15441 if trace {
15442 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
15443 }
15444 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
15445 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15446 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15447 if allow_intrabc {
15448 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15449 if use_intrabc {
15450 return Err(unsupported(
15451 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
15452 ));
15453 }
15454 }
15455 let above_ctx = INTRA_MODE_CTX[above_mode];
15456 let left_ctx = INTRA_MODE_CTX[left_mode];
15457 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15458 if trace {
15459 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15460 }
15461 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
15462 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
15463 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
15464 // symbol. Reading one consumed a symbol the encoder never wrote and
15465 // desynced the tile at the very next element.
15466 let angle_delta_y = 0;
15467 let chroma = if has_chroma {
15468 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15469 if trace {
15470 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
15471 }
15472 if (9..=12).contains(&uv_mode) {
15473 hit!(SMOOTH_UV_HITS);
15474 }
15475 let alpha = if uv_mode == UV_CFL_PRED {
15476 Some(read_cfl_alphas(dec, cdfs))
15477 } else {
15478 None
15479 };
15480 if (V_PRED..=D67_PRED).contains(&uv_mode) {
15481 hit!(DIRECTIONAL_UV_HITS);
15482 }
15483 // See the luma comment above: no angle delta below 8x8.
15484 let angle_delta_uv = 0;
15485 Some((uv_mode, angle_delta_uv, alpha))
15486 } else {
15487 None
15488 };
15489 let mut filter_intra = None;
15490 if mode == DC_PRED && enable_filter_intra {
15491 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
15492 if trace {
15493 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
15494 }
15495 if use_filter_intra {
15496 hit!(FILTER_INTRA_HITS);
15497 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
15498 filter_intra = Some(fi_mode);
15499 }
15500 }
15501 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
15502}
15503
15504/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
15505/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
15506/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
15507/// bookkeeping needs no change. Each leaf reads its own luma mode info,
15508/// neighboured off the *previously decoded leaf in this same group* on
15509/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
15510/// pattern, one level deeper); chroma is read and reconstructed exactly
15511/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
15512/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
15513/// derivation.
15514#[allow(clippy::too_many_arguments)]
15515fn decode_leaf_split4(
15516 dec: &mut SymbolDecoder,
15517 cdfs: &mut Cdfs,
15518 neighbours: &mut Neighbours,
15519 outer_at: (usize, usize),
15520 leaf_mi: (usize, usize),
15521 scan4: &[u16],
15522 prev_leaf: Option<((usize, usize), usize)>,
15523 y: &mut PlaneBuf<'static>,
15524 u: &mut PlaneBuf<'static>,
15525 v: &mut PlaneBuf<'static>,
15526 base_q_idx: u8,
15527 enable_filter_intra: bool,
15528 allow_intrabc: bool,
15529 reduced_tx_set: bool,
15530 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
15531 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
15532 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
15533 fctx: &crate::decode::FrameCtx,
15534) -> Result<(usize, usize)> {
15535 hit!(SUB8_SPLIT_HITS);
15536 let (r, c) = outer_at;
15537 let mut above_mode = neighbours.above_mode[c];
15538 let mut left_mode = neighbours.left_mode[r];
15539 if let Some(((pr, pc), pmode)) = prev_leaf {
15540 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15541 above_mode = pmode;
15542 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15543 left_mode = pmode;
15544 }
15545 }
15546 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
15547 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
15548 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15549 let mut leaf_modes = [0usize; 4];
15550 let mut leaf_skips = [false; 4];
15551 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15552 for i in 0..4usize {
15553 let (dr, dc) = (i / 2, i % 2);
15554 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
15555 // Neighbour modes at real mi granularity: inside the group the
15556 // sibling leaf, outside it the split-leaf map when the adjacent mi
15557 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
15558 // `sub8_mode_col`'s doc).
15559 let leaf_above = if dr == 0 {
15560 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15561 } else {
15562 leaf_modes[i - 2]
15563 };
15564 let leaf_left = if dc == 0 {
15565 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15566 } else {
15567 leaf_modes[i - 1]
15568 };
15569 let has_chroma = i == 3;
15570 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15571 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15572 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15573 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
15574 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15575 )?;
15576 leaf_modes[i] = mode;
15577 leaf_skips[i] = skip;
15578 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
15579 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15580 if smooth_neighbor {
15581 hit!(SMOOTH_LUMA_HITS);
15582 }
15583 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15584 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
15585 if skip {
15586 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
15587 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
15588 } else {
15589 let tu_around = neighbours.around_mi(lmi, 4)[0];
15590 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
15591 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
15592 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
15593 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
15594 // off the wrong CDF on the very first leaf and desynced the tile.
15595 let tu_grid = read_plane(
15596 dec,
15597 cdfs,
15598 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
15599 scan4,
15600 0,
15601 tu_around,
15602 mode,
15603 mode,
15604 angle_delta_y,
15605 reach,
15606 y,
15607 px,
15608 py,
15609 4,
15610 4,
15611 base_q_idx,
15612 None,
15613 filter_intra,
15614 None,
15615 smooth_neighbor, fctx,
15616 )?;
15617 neighbours.record_mi_luma(lmi, 4, &tu_grid);
15618 }
15619 neighbours.fill_skip_grid(lmi, 1, skip);
15620 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
15621 if has_chroma {
15622 last_uv = chroma;
15623 }
15624 }
15625 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15626 let (cpx, cpy) = (gpx / 2, gpy / 2);
15627 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15628 let (uv_mode, angle_delta_uv, alpha) =
15629 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
15630 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15631 neighbours.above_uv_mode[c] = uv_predict_mode;
15632 neighbours.left_uv_mode[r] = uv_predict_mode;
15633 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15634 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
15635 // A skipped chroma block still gets its CfL contribution: libaom's
15636 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15637 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15638 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15639 // added -- `skip_txfm` only drops the residual, never the alpha.
15640 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15641 // merge keeps one fix and feeds both lanes' counters so neither of
15642 // their gates goes vacuous.
15643 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15644 if alpha.is_some() {
15645 hit!(CHROMA_SKIP_CFL_HITS);
15646 hit!(SKIP_CFL_HITS);
15647 }
15648 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);
15649 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);
15650 (Grid::Zero(16), Grid::Zero(16))
15651 } else {
15652 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15653 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15654 let ug = read_plane(
15655 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15656 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15657 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15658 )?;
15659 let vg = read_plane(
15660 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15661 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
15662 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
15663 )?;
15664 (ug, vg)
15665 };
15666 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
15667 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
15668 // rescaling is wrong for an already-mi-unit position, so this inlines
15669 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
15670 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
15671 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
15672 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
15673 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
15674 // bottom). libaom's `update_ext_partition_context` writes
15675 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
15676 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
15677 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
15678 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
15679 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
15680 // round's bug) makes the very next sibling 8x8's `partition_w8` read
15681 // with the wrong context and desync immediately.
15682 let side_mi = 2;
15683 for cell in 0..side_mi {
15684 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
15685 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
15686 }
15687 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15688 let bound_h = round_up_even(neighbours.mi_rows);
15689 let bound_w = round_up_even(neighbours.mi_cols);
15690 let u_state = neighbour_state(&u_grid);
15691 let v_state = neighbour_state(&v_grid);
15692 for cell in 0..side_mi {
15693 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15694 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15695 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15696 }
15697 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15698 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15699 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15700 }
15701 }
15702 Ok((leaf_modes[2], leaf_modes[1]))
15703}
15704
15705/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
15706/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
15707/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
15708/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
15709/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
15710/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
15711/// every sub-block one mi wide or high but the last) -- differing only where
15712/// the shape does:
15713///
15714/// * the transform is a true `TX_4X8`/`TX_8X4`
15715/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
15716/// `av1_inv_txfm_shift_ls` row already cover this size pair);
15717/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
15718/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
15719/// row -- see that variant's doc comment;
15720/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
15721/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
15722/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
15723/// ([`Reach::of_rect`]);
15724/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
15725/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
15726/// `BLOCK_4X4` split writes.
15727///
15728/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
15729/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
15730/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
15731/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
15732/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
15733/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
15734#[allow(clippy::too_many_arguments)]
15735fn decode_leaf_rect8(
15736 dec: &mut SymbolDecoder,
15737 cdfs: &mut Cdfs,
15738 neighbours: &mut Neighbours,
15739 outer_at: (usize, usize),
15740 leaf_mi: (usize, usize),
15741 vert: bool,
15742 scan4: &[u16],
15743 y: &mut PlaneBuf<'static>,
15744 u: &mut PlaneBuf<'static>,
15745 v: &mut PlaneBuf<'static>,
15746 base_q_idx: u8,
15747 enable_filter_intra: bool,
15748 allow_intrabc: bool,
15749 tx_select: bool,
15750 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15751) -> Result<(usize, usize)> {
15752 let (r, c) = outer_at;
15753 // lane-modectx r1: availability-correct fallback pair (see
15754 // `modes_above_left`), not the raw coarse bands.
15755 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
15756 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15757 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
15758 let (w_mi, h_mi) = (bw / MI, bh / MI);
15759 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
15760 let mut leaf_modes = [0usize; 2];
15761 let mut leaf_skips = [false; 2];
15762 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15763 for i in 0..2usize {
15764 let lmi = if vert {
15765 (leaf_mi.0, leaf_mi.1 + i)
15766 } else {
15767 (leaf_mi.0 + i, leaf_mi.1)
15768 };
15769 // Inside the pair the sibling is the neighbour on the split axis;
15770 // outside it the mi-granular map, else the coarse 16x16 slot.
15771 let leaf_above = if !vert && i == 1 {
15772 leaf_modes[0]
15773 } else {
15774 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15775 };
15776 let leaf_left = if vert && i == 1 {
15777 leaf_modes[0]
15778 } else {
15779 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15780 };
15781 let has_chroma = i == 1;
15782 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15783 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15784 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15785 filter_intra_size_class_rect(bw, bh)
15786 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
15787 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15788 )?;
15789 if filter_intra.is_some() {
15790 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
15791 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
15792 // same `reconstruct_rect`/`reconstruct` calls below -- and under
15793 // a split transform, per 4x4 unit with that unit's own edge,
15794 // which is exactly what the depth-1 loop already does.
15795 hit!(FILTER_INTRA_RECT_HITS);
15796 hit!(FILTER_INTRA_RECT_SUB8_HITS);
15797 }
15798 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
15799 // leaf too, and is read for every intra block, skipped or not. Its
15800 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
15801 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
15802 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
15803 // `tx_size_cat2` the 32x16 strips read -- with the rect context
15804 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
15805 // Missing this read consumed one symbol fewer than the encoder wrote
15806 // and desynced the tile at the very first rect leaf (class
15807 // `symbol-consumption-gap`).
15808 let depth = if tx_select {
15809 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
15810 // read every other rect reader now does -- a no-op on a key frame.
15811 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
15812 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
15813 } else {
15814 tx_size_context_rect(neighbours, lmi, bw, bh)
15815 };
15816 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
15817 } else {
15818 0
15819 };
15820 if depth != 0 {
15821 hit!(TX_DEPTH_HITS);
15822 hit!(RECT8_SPLIT_TX_HITS);
15823 }
15824 leaf_modes[i] = mode;
15825 leaf_skips[i] = skip;
15826 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
15827 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15828 if smooth_neighbor {
15829 hit!(SMOOTH_LUMA_HITS);
15830 }
15831 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15832 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15833 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
15834 // two 4x4 transform units along its long axis, each predicted from
15835 // the previous unit's reconstruction and reading its own `txb_skip`
15836 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
15837 // four. The per-TU path writes its own neighbour state, so the
15838 // block-level write below is skipped for it.
15839 let split = depth != 0;
15840 if split {
15841 let mut done = 0usize;
15842 for tu in 0..2usize {
15843 let tu_mi = if vert {
15844 (lmi.0 + tu, lmi.1)
15845 } else {
15846 (lmi.0, lmi.1 + tu)
15847 };
15848 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
15849 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15850 // Same per-TU rule as every other split-transform site
15851 // (lane-palette2 r12): a transform unit inside a block is not
15852 // a block at that position, so its reach comes from the
15853 // block's own row, offset by the unit's position.
15854 let tu_reach = tu_reach(
15855 bw,
15856 bh,
15857 tu_px - px,
15858 tu_py - py,
15859 4,
15860 reach,
15861 px,
15862 py,
15863 y.width,
15864 y.height, fctx,
15865 );
15866 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15867 if skip {
15868 // A skipped leaf still predicts per transform unit: the
15869 // second 4x4 takes its above/left edge from the first
15870 // one's reconstruction, which is NOT what a single 4x8
15871 // prediction of the same mode produces.
15872 let zeros = vec![0i32; 16];
15873 push_intra(0,
15874 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
15875 filter_intra, smooth_neighbor, fctx,
15876 );
15877 neighbours.record_mi_luma(tu_mi, 4, &zeros);
15878 continue;
15879 }
15880 let tu_grid = read_plane(
15881 dec,
15882 cdfs,
15883 if reduced_tx_set {
15884 TxbSet::Luma4
15885 } else {
15886 TxbSet::Luma4Set1
15887 },
15888 scan4,
15889 0,
15890 tu_around,
15891 mode,
15892 mode,
15893 angle_delta_y,
15894 tu_reach,
15895 y,
15896 tu_px,
15897 tu_py,
15898 4,
15899 TX4,
15900 base_q_idx,
15901 None,
15902 filter_intra,
15903 Some(tu_skip_ctx),
15904 smooth_neighbor, fctx,
15905 )?;
15906 if tu_grid.iter().any(|&l| l != 0) {
15907 done += 1;
15908 }
15909 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15910 }
15911 if done > 0 {
15912 if vert {
15913 hit!(TX4X8_CODED_HITS);
15914 } else {
15915 hit!(TX8X4_CODED_HITS);
15916 }
15917 }
15918 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15919 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
15920 if has_chroma {
15921 last_uv = chroma;
15922 }
15923 continue;
15924 }
15925 let grid = if skip {
15926 let zeros = Grid::Zero(bw * bh);
15927 push_intra_rect(0,
15928 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
15929 smooth_neighbor, fctx,
15930 );
15931 zeros
15932 } else {
15933 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
15934 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
15935 // at 0 -- see `decode_leaf_split4`'s own note.
15936 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
15937 let set = if reduced_tx_set {
15938 TxbSet::LumaRect4x8
15939 } else {
15940 TxbSet::LumaRect4x8Set1
15941 };
15942 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
15943 let (levels, tx_type) = read_coeffs_rect(
15944 dec,
15945 &mut coding,
15946 scan,
15947 bw,
15948 bh,
15949 0,
15950 dc_sign_ctx(around.2),
15951 TxType::DctDct,
15952 )?;
15953 if levels.iter().any(|&l| l != 0) {
15954 if vert {
15955 hit!(TX4X8_CODED_HITS);
15956 } else {
15957 hit!(TX8X4_CODED_HITS);
15958 }
15959 }
15960 let residual = dequant_and_inverse_typed_wh(
15961 &levels,
15962 bw,
15963 bh,
15964 crate::decode::bit_depth(fctx),
15965 fctx.current_q_idx.with(|q| q.get()),
15966 plane_q_delta(0, fctx).0,
15967 plane_q_delta(0, fctx).1,
15968 tx_type,
15969 );
15970 push_intra_rect(0,
15971 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
15972 smooth_neighbor, fctx,
15973 );
15974 levels
15975 };
15976 // Plane 0's per-TU coefficient context over this leaf's own mi span
15977 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
15978 // for the whole 8x8 group below).
15979 let state = neighbour_state(&grid);
15980 for cell in 0..h_mi {
15981 if lmi.0 + cell < neighbours.mi_rows {
15982 neighbours.left[lmi.0 + cell][0] = state;
15983 }
15984 }
15985 for cell in 0..w_mi {
15986 if lmi.1 + cell < neighbours.mi_cols {
15987 neighbours.above[lmi.1 + cell][0] = state;
15988 }
15989 }
15990 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15991 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
15992 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
15993 if has_chroma {
15994 last_uv = chroma;
15995 }
15996 }
15997 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15998 let (cpx, cpy) = (gpx / 2, gpy / 2);
15999 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
16000 let (uv_mode, angle_delta_uv, alpha) =
16001 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
16002 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16003 neighbours.above_uv_mode[c] = uv_predict_mode;
16004 neighbours.left_uv_mode[r] = uv_predict_mode;
16005 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16006 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] {
16007 // A skipped chroma block still gets its CfL contribution: libaom's
16008 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16009 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16010 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16011 // added -- `skip_txfm` only drops the residual, never the alpha.
16012 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16013 // merge keeps one fix and feeds both lanes' counters so neither of
16014 // their gates goes vacuous.
16015 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16016 if alpha.is_some() {
16017 hit!(CHROMA_SKIP_CFL_HITS);
16018 hit!(SKIP_CFL_HITS);
16019 }
16020 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);
16021 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);
16022 (Grid::Zero(16), Grid::Zero(16))
16023 } else {
16024 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16025 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16026 let ug = read_plane(
16027 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16028 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16029 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16030 )?;
16031 let vg = read_plane(
16032 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16033 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16034 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16035 )?;
16036 (ug, vg)
16037 };
16038 // `update_partition_context` at the 8x8 level writes
16039 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
16040 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
16041 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
16042 // `partition_ctx_mi` reads back off these side values.
16043 for cell in 0..2 {
16044 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
16045 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
16046 }
16047 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16048 let bound_h = round_up_even(neighbours.mi_rows);
16049 let bound_w = round_up_even(neighbours.mi_cols);
16050 let u_state = neighbour_state(&u_grid);
16051 let v_state = neighbour_state(&v_grid);
16052 for cell in 0..2usize {
16053 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
16054 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16055 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16056 }
16057 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
16058 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16059 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16060 }
16061 }
16062 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
16063 // bottom one (the second under HORZ, the left one under VERT), the one a
16064 // neighbour to the right sees is the top-right (the second under VERT).
16065 Ok(if vert {
16066 (leaf_modes[0], leaf_modes[1])
16067 } else {
16068 (leaf_modes[1], leaf_modes[0])
16069 })
16070}
16071
16072/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
16073/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
16074/// (mod 8) reuse the same table.
16075const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
16076 [(-1, 1), (-2, 2)],
16077 [(0, 1), (-1, 2)],
16078 [(0, 1), (0, 2)],
16079 [(0, 1), (1, 2)],
16080 [(1, 1), (2, 2)],
16081 [(1, 0), (2, 1)],
16082 [(1, 0), (2, 0)],
16083 [(1, 0), (2, -1)],
16084];
16085/// A neighbour tap outside the frame's true extent -- `constrain` reads this
16086/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
16087const CDEF_VERY_LARGE: i32 = 0x4000;
16088const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
16089const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
16090
16091fn cdef_msb(x: i32) -> i32 {
16092 31 - x.leading_zeros() as i32
16093}
16094
16095/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
16096/// centre sample a filter tap is allowed to contribute.
16097#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16098fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
16099 if threshold == 0 {
16100 return 0;
16101 }
16102 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
16103}
16104
16105/// `constrain`'s damping shift: a function of the block's threshold and
16106/// damping alone, so the filter loop computes it once per block instead of
16107/// the `leading_zeros` + branch it used to do twice per tap read.
16108fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
16109 (damping - cdef_msb(threshold)).max(0)
16110}
16111
16112/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
16113/// non-zero on every call (the caller only filters when its strength is).
16114fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
16115 let a = diff.abs();
16116 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
16117}
16118
16119/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
16120/// lies inside its own samples grown by this much.
16121const CDEF_BORDER: usize = 2;
16122
16123/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
16124/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
16125/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
16126/// index a small contiguous window instead of re-deriving the frame-bounds
16127/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
16128/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
16129fn cdef_gather(
16130 src: &[u16],
16131 stride: usize,
16132 true_w: usize,
16133 true_h: usize,
16134 ox: usize,
16135 oy: usize,
16136 bw: usize,
16137 bh: usize,
16138 buf: &mut [i16],
16139) {
16140 let bstride = bw + 2 * CDEF_BORDER;
16141 let rows = bh + 2 * CDEF_BORDER;
16142 if oy >= CDEF_BORDER
16143 && ox >= CDEF_BORDER
16144 && oy + bh + CDEF_BORDER <= true_h
16145 && ox + bw + CDEF_BORDER <= true_w
16146 {
16147 // Interior block: every tap is inside the frame, so the whole window
16148 // is `rows` contiguous runs.
16149 for r in 0..rows {
16150 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
16151 let src_row = &src[s0..s0 + bstride];
16152 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
16153 for (d, &v) in dst_row.iter_mut().zip(src_row) {
16154 *d = v as i16;
16155 }
16156 }
16157 return;
16158 }
16159 for r in 0..rows {
16160 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
16161 for c in 0..bstride {
16162 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
16163 buf[r * bstride + c] =
16164 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
16165 CDEF_VERY_LARGE as i16
16166 } else {
16167 src[ny as usize * stride + nx as usize] as i16
16168 };
16169 }
16170 }
16171}
16172
16173/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
16174/// array takes the row, its reverse, its pairwise sums or its total added
16175/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
16176/// per-sample form did become a handful of lane-wide adds per row. i32 is
16177/// exact here: every partial is a sum of at most eight values in -128..127,
16178/// and slot 15 exists only so an eight-lane store at offset 7 fits.
16179fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
16180 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
16181 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
16182 *d += x;
16183 }
16184 }
16185 let mut partial = [[0i32; 16]; 8];
16186 for i in 0..8usize {
16187 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16188 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
16189 // accumulating, same as `constrain`'s threshold shift.
16190 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
16191 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
16192 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
16193 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
16194 let (p, rest) = partial.split_at_mut(1);
16195 add_at(&mut p[0], i, &row); // partial[0][i + j]
16196 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
16197 rest[1][i] = row.iter().sum(); // partial[2][i]
16198 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
16199 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
16200 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
16201 add_at(&mut rest[5], 0, &row); // partial[6][j]
16202 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
16203 }
16204 partial
16205}
16206
16207/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
16208/// direction of an 8x8 luma window and the variance gap between it and its
16209/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
16210/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
16211fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
16212 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
16213 #[cfg(target_arch = "x86_64")]
16214 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16215 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16216 // the same eight rows of eight samples the scalar form does.
16217 #[allow(unsafe_code)]
16218 unsafe {
16219 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
16220 }
16221 } else {
16222 cdef_find_dir_partials(win, bstride, coeff_shift)
16223 };
16224 #[cfg(not(target_arch = "x86_64"))]
16225 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
16226 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
16227 let mut cost = [0i64; 8];
16228 for i in 0..8usize {
16229 cost[2] += sq(partial[2][i]);
16230 cost[6] += sq(partial[6][i]);
16231 }
16232 cost[2] *= DIV_TABLE[8];
16233 cost[6] *= DIV_TABLE[8];
16234 for i in 0..7usize {
16235 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
16236 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
16237 }
16238 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
16239 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
16240 for i in (1..8).step_by(2) {
16241 for j in 0..5usize {
16242 cost[i] += sq(partial[i][3 + j]);
16243 }
16244 cost[i] *= DIV_TABLE[8];
16245 for j in 0..3usize {
16246 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
16247 }
16248 }
16249 let mut best_cost = 0i64;
16250 let mut best_dir = 0usize;
16251 for (i, &c) in cost.iter().enumerate() {
16252 if c > best_cost {
16253 best_cost = c;
16254 best_dir = i;
16255 }
16256 }
16257 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
16258 (best_dir, var as i32)
16259}
16260
16261/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
16262/// (high variance gap) gets more deringing than a flat or non-directional
16263/// one, only ever applied to the luma primary strength.
16264fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
16265 if var == 0 {
16266 return 0;
16267 }
16268 let i = if var >> 6 != 0 {
16269 cdef_msb(var >> 6).min(12)
16270 } else {
16271 0
16272 };
16273 (strength * (4 + i) + 8) >> 4
16274}
16275
16276/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
16277/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
16278/// previously-filtered neighbour must never feed this block's own sum).
16279#[allow(clippy::too_many_arguments)]
16280#[allow(unsafe_code)]
16281fn cdef_filter_block(
16282 src: &[i16],
16283 dst: &mut PlaneBuf<'static>,
16284 ox: usize,
16285 oy: usize,
16286 bw: usize,
16287 bh: usize,
16288 pri_strength: i32,
16289 sec_strength: i32,
16290 dir: usize,
16291 pri_damping: i32,
16292 sec_damping: i32,
16293 enable_primary: bool,
16294 enable_secondary: bool,
16295 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
16296) {
16297 let (stride, smax) = (dst.width, sample_max(fctx));
16298 #[cfg(target_arch = "x86_64")]
16299 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
16300 {
16301 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16302 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
16303 // `bh` runs of `bw` samples the scalar form writes.
16304 unsafe {
16305 cdef_simd::filter_block_avx2(
16306 src,
16307 dst.data.to_mut(),
16308 stride,
16309 ox,
16310 oy,
16311 bw,
16312 bh,
16313 pri_strength,
16314 sec_strength,
16315 dir,
16316 pri_damping,
16317 sec_damping,
16318 enable_primary,
16319 enable_secondary,
16320 coeff_shift,
16321 smax,
16322 )
16323 };
16324 return;
16325 }
16326 cdef_filter_block_scalar(
16327 src,
16328 dst.data.to_mut(),
16329 stride,
16330 ox,
16331 oy,
16332 bw,
16333 bh,
16334 pri_strength,
16335 sec_strength,
16336 dir,
16337 pri_damping,
16338 sec_damping,
16339 enable_primary,
16340 enable_secondary,
16341 coeff_shift,
16342 smax,
16343 );
16344}
16345
16346/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
16347/// the form every non-AVX2 build decodes through and the one
16348/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
16349#[allow(clippy::too_many_arguments)]
16350fn cdef_filter_block_scalar(
16351 src: &[i16],
16352 dst: &mut [u16],
16353 stride: usize,
16354 ox: usize,
16355 oy: usize,
16356 bw: usize,
16357 bh: usize,
16358 pri_strength: i32,
16359 sec_strength: i32,
16360 dir: usize,
16361 pri_damping: i32,
16362 sec_damping: i32,
16363 enable_primary: bool,
16364 enable_secondary: bool,
16365 coeff_shift: i32,
16366 smax: i32,
16367) {
16368 let clipping_required = enable_primary && enable_secondary;
16369 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
16370 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
16371 // derivative) carries the bit-depth shift, so the tap-set parity bit
16372 // must be read back above that shift, not off the raw low bit.
16373 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16374 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
16375 // `constrain`), so they are resolved here rather than per tap read.
16376 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
16377 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
16378 let bstride = bw + 2 * CDEF_BORDER;
16379 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
16380 // reaching +-CDEF_BORDER, so every index below is in range by construction.
16381 let at = |i: i32, j: i32| -> i32 {
16382 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
16383 };
16384 let (pri_dir, sec_dir0, sec_dir1) =
16385 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16386 for i in 0..bh {
16387 for j in 0..bw {
16388 let (i32i, i32j) = (i as i32, j as i32);
16389 let x = at(i32i, i32j);
16390 let mut sum = 0i32;
16391 let mut max = x;
16392 let mut min = x;
16393 for k in 0..2usize {
16394 if enable_primary {
16395 let (tr, tc) = pri_dir[k];
16396 let p0 = at(i32i + tr, i32j + tc);
16397 let p1 = at(i32i - tr, i32j - tc);
16398 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
16399 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
16400 if clipping_required {
16401 if p0 != CDEF_VERY_LARGE {
16402 max = max.max(p0);
16403 }
16404 if p1 != CDEF_VERY_LARGE {
16405 max = max.max(p1);
16406 }
16407 min = min.min(p0).min(p1);
16408 }
16409 }
16410 if enable_secondary {
16411 let (tr0, tc0) = sec_dir0[k];
16412 let (tr1, tc1) = sec_dir1[k];
16413 let s0 = at(i32i + tr0, i32j + tc0);
16414 let s1 = at(i32i - tr0, i32j - tc0);
16415 let s2 = at(i32i + tr1, i32j + tc1);
16416 let s3 = at(i32i - tr1, i32j - tc1);
16417 if clipping_required {
16418 for s in [s0, s1, s2, s3] {
16419 if s != CDEF_VERY_LARGE {
16420 max = max.max(s);
16421 }
16422 }
16423 min = min.min(s0).min(s1).min(s2).min(s3);
16424 }
16425 sum += CDEF_SEC_TAPS[k]
16426 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
16427 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
16428 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
16429 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
16430 }
16431 }
16432 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
16433 if clipping_required {
16434 y = y.clamp(min, max);
16435 }
16436 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
16437 }
16438 }
16439}
16440
16441/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
16442/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
16443/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
16444/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
16445/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
16446/// a time in 16-bit lanes.
16447///
16448/// 16-bit lanes are exact for every value this filter sees: window samples
16449/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
16450/// `i16`, a `constrain` result is bounded by the threshold (at most
16451/// `15 << 4`), and the tap-weighted sum by `24 *` that.
16452#[cfg(target_arch = "x86_64")]
16453#[allow(unsafe_code)]
16454#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16455mod cdef_simd {
16456 use super::{
16457 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
16458 CDEF_VERY_LARGE,
16459 };
16460 use std::arch::x86_64::*;
16461
16462 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
16463 /// register (low half = row `i`).
16464 ///
16465 /// # Safety
16466 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
16467 #[target_feature(enable = "avx2")]
16468 #[inline]
16469 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
16470 let lo = _mm_loadu_si128(w.offset(off).cast());
16471 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
16472 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
16473 }
16474
16475 /// Spec 7.15.3's `constrain`, lane-parallel:
16476 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
16477 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
16478 /// clamped magnitude is already 0 where `diff` is).
16479 ///
16480 /// # Safety
16481 /// Requires AVX2.
16482 #[target_feature(enable = "avx2")]
16483 #[inline]
16484 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
16485 let diff = _mm256_sub_epi16(p, x);
16486 let a = _mm256_abs_epi16(diff);
16487 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
16488 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
16489 _mm256_sign_epi16(t, diff)
16490 }
16491
16492 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
16493 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
16494 /// four the auto-vectorised scalar form gets without the feature.
16495 ///
16496 /// # Safety
16497 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
16498 /// grown by `CDEF_BORDER` at row stride `bstride`.
16499 #[target_feature(enable = "avx2")]
16500 pub unsafe fn find_dir_partials_avx2(
16501 win: &[i16],
16502 bstride: usize,
16503 coeff_shift: i32,
16504 ) -> [[i32; 16]; 8] {
16505 #[target_feature(enable = "avx2")]
16506 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
16507 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
16508 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
16509 }
16510 #[target_feature(enable = "avx2")]
16511 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
16512 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
16513 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
16514 }
16515 let mut partial = [[0i32; 16]; 8];
16516 let shift = _mm_cvtsi32_si128(coeff_shift);
16517 let c128 = _mm256_set1_epi32(128);
16518 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
16519 let mut p6 = _mm256_setzero_si256();
16520 for i in 0..8usize {
16521 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16522 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
16523 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
16524 let rev = _mm256_permutevar8x32_epi32(row, revidx);
16525 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
16526 // four pairwise sums are the two lanes' low halves joined.
16527 let h = _mm256_hadd_epi32(row, row);
16528 let pair =
16529 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
16530 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
16531 let hs = _mm_hadd_epi32(pair, pair);
16532 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
16533 add8(&mut partial[0], i, row);
16534 add4(&mut partial[1], i, pair);
16535 partial[2][i] = total;
16536 add4(&mut partial[3], i, rpair);
16537 add8(&mut partial[4], i, rev);
16538 add8(&mut partial[5], 3 - i / 2, row);
16539 p6 = _mm256_add_epi32(p6, row);
16540 add8(&mut partial[7], i / 2, row);
16541 }
16542 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
16543 partial
16544 }
16545
16546 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
16547 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
16548 /// `bw == 4` the upper four lanes of each half are window samples read
16549 /// past the row (never past the buffer -- `w` is padded to 256 entries),
16550 /// computed and then dropped by the 64-bit store.
16551 ///
16552 /// # Safety
16553 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
16554 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
16555 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
16556 /// of `bw` samples at `(ox, oy)`.
16557 #[target_feature(enable = "avx2")]
16558 #[allow(clippy::too_many_arguments)]
16559 pub unsafe fn filter_block_avx2(
16560 src: &[i16],
16561 dst: &mut [u16],
16562 stride: usize,
16563 ox: usize,
16564 oy: usize,
16565 bw: usize,
16566 bh: usize,
16567 pri_strength: i32,
16568 sec_strength: i32,
16569 dir: usize,
16570 pri_damping: i32,
16571 sec_damping: i32,
16572 enable_primary: bool,
16573 enable_secondary: bool,
16574 coeff_shift: i32,
16575 smax: i32,
16576 ) {
16577 let bstride = bw + 2 * CDEF_BORDER;
16578 // The caller's window is already `i16` and 256 entries long, so the
16579 // kernel taps it in place: the largest two-row load is
16580 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
16581 // 4x4 chroma one, both inside the buffer's zeroed tail.
16582 let w = src;
16583 let clipping_required = enable_primary && enable_secondary;
16584 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16585 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
16586 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
16587 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
16588 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
16589 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
16590 let zero = _mm256_setzero_si256();
16591 let eight = _mm256_set1_epi16(8);
16592 let smaxv = _mm256_set1_epi16(smax as i16);
16593 let (pri_dir, sec_dir0, sec_dir1) =
16594 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16595 let wp = w.as_ptr();
16596 let bs = bstride as isize;
16597 let dp = dst.as_mut_ptr();
16598 let mut i = 0usize;
16599 while i < bh {
16600 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
16601 let x = ld2(wp, base, bs);
16602 let mut sum = zero;
16603 let mut max = x;
16604 let mut min = x;
16605 for k in 0..2usize {
16606 if enable_primary {
16607 let (tr, tc) = pri_dir[k];
16608 let off = tr as isize * bs + tc as isize;
16609 let p0 = ld2(wp, base + off, bs);
16610 let p1 = ld2(wp, base - off, bs);
16611 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
16612 sum = _mm256_add_epi16(
16613 sum,
16614 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
16615 );
16616 sum = _mm256_add_epi16(
16617 sum,
16618 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
16619 );
16620 if clipping_required {
16621 // The sentinel is excluded from the max exactly as the
16622 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
16623 // 0 cannot win a max whose seed `x` is non-negative.
16624 max = _mm256_max_epi16(
16625 max,
16626 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
16627 );
16628 max = _mm256_max_epi16(
16629 max,
16630 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
16631 );
16632 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
16633 }
16634 }
16635 if enable_secondary {
16636 let (tr0, tc0) = sec_dir0[k];
16637 let (tr1, tc1) = sec_dir1[k];
16638 let off0 = tr0 as isize * bs + tc0 as isize;
16639 let off1 = tr1 as isize * bs + tc1 as isize;
16640 let s0 = ld2(wp, base + off0, bs);
16641 let s1 = ld2(wp, base - off0, bs);
16642 let s2 = ld2(wp, base + off1, bs);
16643 let s3 = ld2(wp, base - off1, bs);
16644 if clipping_required {
16645 for s in [s0, s1, s2, s3] {
16646 max = _mm256_max_epi16(
16647 max,
16648 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
16649 );
16650 }
16651 min = _mm256_min_epi16(
16652 min,
16653 _mm256_min_epi16(
16654 _mm256_min_epi16(s0, s1),
16655 _mm256_min_epi16(s2, s3),
16656 ),
16657 );
16658 }
16659 let c = _mm256_add_epi16(
16660 _mm256_add_epi16(
16661 constrain(s0, x, sec_thr, sec_shift),
16662 constrain(s1, x, sec_thr, sec_shift),
16663 ),
16664 _mm256_add_epi16(
16665 constrain(s2, x, sec_thr, sec_shift),
16666 constrain(s3, x, sec_thr, sec_shift),
16667 ),
16668 );
16669 sum = _mm256_add_epi16(
16670 sum,
16671 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
16672 );
16673 }
16674 }
16675 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
16676 let neg = _mm256_cmpgt_epi16(zero, sum);
16677 let mut y = _mm256_add_epi16(
16678 x,
16679 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
16680 );
16681 if clipping_required {
16682 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
16683 }
16684 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
16685 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
16686 let o0 = ((oy + i) * stride + ox) as isize;
16687 let o1 = o0 + stride as isize;
16688 if bw == 8 {
16689 _mm_storeu_si128(dp.offset(o0).cast(), lo);
16690 _mm_storeu_si128(dp.offset(o1).cast(), hi);
16691 } else {
16692 _mm_storel_epi64(dp.offset(o0).cast(), lo);
16693 _mm_storel_epi64(dp.offset(o1).cast(), hi);
16694 }
16695 i += 2;
16696 }
16697 }
16698}
16699
16700/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
16701/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
16702/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
16703/// every block's level comes from [`LoopFilterParams::level`] plus the
16704/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
16705/// `get_filter_level`, precomputed per-block here rather than cached in a
16706/// table the way libaom's `av1_loop_filter_frame_init` does).
16707///
16708/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
16709/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
16710fn apply_deblock(
16711 y: &mut PlaneBuf<'static>,
16712 u: &mut PlaneBuf<'static>,
16713 v: &mut PlaneBuf<'static>,
16714 lf: &LoopFilterParams,
16715 n: &Neighbours,
16716 frame_width: usize,
16717 frame_height: usize, fctx: &crate::decode::FrameCtx,
16718) {
16719 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
16720 // mismatch between the raw reconstruction and post-filter output.
16721 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
16722 return;
16723 }
16724 if lf.level[0] != 0 || lf.level[1] != 0 {
16725 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
16726 }
16727 if lf.level[2] != 0 {
16728 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
16729 }
16730 if lf.level[3] != 0 {
16731 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
16732 }
16733}
16734
16735/// [`apply_deblock`] for ONE pass over ONE band of luma rows
16736/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
16737/// planes' vertical passes and then their three horizontal ones is the same
16738/// output as `apply_deblock`'s plane-at-a-time order: the planes are
16739/// separate buffers and neither pass reads another plane.
16740#[allow(clippy::too_many_arguments)]
16741fn deblock_span(
16742 y: &mut PlaneBuf<'static>,
16743 u: &mut PlaneBuf<'static>,
16744 v: &mut PlaneBuf<'static>,
16745 lf: &LoopFilterParams,
16746 n: &Neighbours,
16747 frame_width: usize,
16748 frame_height: usize,
16749 y_lo: usize,
16750 y_hi: usize,
16751 horz: bool,
16752 fctx: &crate::decode::FrameCtx,
16753) {
16754 if lf.level[0] != 0 || lf.level[1] != 0 {
16755 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
16756 }
16757 if lf.level[2] != 0 {
16758 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16759 }
16760 if lf.level[3] != 0 {
16761 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16762 }
16763}
16764
16765/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
16766/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
16767/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
16768/// mi unit under this decoder's assumed 4:2:0 subsampling).
16769///
16770/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
16771/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
16772/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
16773/// prediction mode is obtained from the bottom/right mi structure of the
16774/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
16775/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
16776/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
16777/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
16778/// the group is split into 4x4 luma blocks (class
16779/// `context-read-from-one-cell`).
16780fn plane_to_mi(chroma: bool, coord: usize) -> usize {
16781 if chroma { (coord / 2) | 1 } else { coord / 4 }
16782}
16783
16784/// This plane's own transform width in pixels at the covering block, spec
16785/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
16786/// width directly; chroma halves it (this decoder's UV transform is always
16787/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
16788/// under 4:2:0 and a block that never splits its own transform).
16789fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16790 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
16791 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16792}
16793
16794/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
16795/// edges step and gate by transform height, which differs from width only
16796/// on rect partition strips.
16797fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16798 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
16799 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16800}
16801
16802/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
16803/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
16804/// present only when its neighbour exists inside the true frame -- whether
16805/// the block immediately above (at this block's own leftmost mi column) or
16806/// to the left (at its own topmost mi row) coded a transform at least as wide
16807/// as `own_side`.
16808fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
16809 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
16810 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
16811 usize::from(above) + usize::from(left)
16812}
16813
16814/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
16815/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
16816/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
16817/// inter path maintains), except that an *inter* neighbour contributes its
16818/// own BLOCK size rather than its transform size -- the two differ the moment
16819/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
16820/// approximation coincides with this only while every neighbour codes one
16821/// whole-block transform, which is exactly what `TxMode::Select` ends.
16822/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
16823/// r1): `get_tx_size_context` compares the neighbour ABOVE against
16824/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
16825/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
16826/// strip are two different numbers. The intra strip inside an inter frame read
16827/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
16828/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
16829/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
16830fn tx_size_context_txfm_rect(
16831 n: &Neighbours,
16832 (mi_r, mi_c): (usize, usize),
16833 own_w: usize,
16834 own_h: usize, fctx: &crate::decode::FrameCtx,
16835) -> usize {
16836 hit!(INTRA_IN_INTER_TXCTX_HITS);
16837 let has_above = mi_r > n.tile_row0_mi;
16838 let has_left = mi_c > n.tile_col0_mi;
16839 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
16840 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
16841 if has_above && n.above_inter[mi_c] {
16842 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
16843 }
16844 if has_left && n.left_inter[mi_r] {
16845 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
16846 }
16847 if crate::envflags::env_flag!("EC_TXCTX") {
16848 eprintln!(
16849 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
16850 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16851 above={above} left={left}",
16852 n.above_txfm[mi_c],
16853 n.left_txfm[mi_r],
16854 n.above_inter[mi_c],
16855 n.left_inter[mi_r],
16856 n.above_side_mi[mi_c],
16857 n.left_side_mi[mi_r],
16858 );
16859 }
16860 let ctx = match (has_above, has_left) {
16861 (true, true) => usize::from(above) + usize::from(left),
16862 (true, false) => usize::from(above),
16863 (false, true) => usize::from(left),
16864 (false, false) => 0,
16865 };
16866 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
16867 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
16868 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
16869 // intra in an inter frame" tally is green on the buggy code too (class
16870 // gate-blind-to-feature).
16871 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16872 let (cw, ch) = (own_w.min(64), own_h.min(64));
16873 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
16874 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
16875 if ctx != stale {
16876 hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS);
16877 }
16878 }
16879 ctx
16880}
16881
16882/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
16883/// are written and read everywhere else with a raw mi index); the SUB-cell
16884/// division this pair used read a cell four blocks away, so the inter-neighbour
16885/// override above fired on the wrong neighbour -- the first divergence of the
16886/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
16887/// at the intra block right of an inter one).
16888fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
16889 let has_above = mi_r > n.tile_row0_mi;
16890 let has_left = mi_c > n.tile_col0_mi;
16891 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
16892 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
16893 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
16894 // `above_inter`/`left_inter` bands are written per MI unit
16895 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
16896 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
16897 // block whenever the neighbour column/row is not the cell's first. A
16898 // 16x16 intra block whose left neighbour is an inter block at mi row 4
16899 // then missed libaom's "an inter neighbour contributes its BLOCK size"
16900 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
16901 if has_above && n.above_inter[mi_c] {
16902 above = usize::from(n.above_side_mi[mi_c]) >= side;
16903 }
16904 if has_left && n.left_inter[mi_r] {
16905 left = usize::from(n.left_side_mi[mi_r]) >= side;
16906 }
16907 if crate::envflags::env_flag!("EC_TXCTX") {
16908 eprintln!(
16909 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
16910 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16911 above={above} left={left}",
16912 n.above_txfm[mi_c],
16913 n.left_txfm[mi_r],
16914 n.above_inter[mi_c],
16915 n.left_inter[mi_r],
16916 n.above_side_mi[mi_c],
16917 n.left_side_mi[mi_r],
16918 );
16919 }
16920 match (has_above, has_left) {
16921 (true, true) => usize::from(above) + usize::from(left),
16922 (true, false) => usize::from(above),
16923 (false, true) => usize::from(left),
16924 (false, false) => 0,
16925 }
16926}
16927
16928/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
16929/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
16930/// the transform's own side in pixels (`side >> depth`) -- this decoder's
16931/// four square categories (8/16/32/64) each halve at most twice, matching
16932/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
16933fn read_tx_size(
16934 dec: &mut SymbolDecoder,
16935 cdfs: &mut Cdfs,
16936 n: &Neighbours,
16937 at_mi: (usize, usize),
16938 side: usize,
16939 // lane-txselect: `get_tx_size_context`'s real context, for the callers
16940 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
16941 // key-frame path's own deblock-grid approximation.
16942 ctx_override: Option<usize>,
16943) -> usize {
16944 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
16945 // `get_tx_size_context`): a block wider than 64 still tops out at
16946 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
16947 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
16948 // never against its own 128 side (lane-sb128b r1).
16949 let max_tx = side.min(64);
16950 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
16951 let depth = match max_tx {
16952 8 => {
16953 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16954 }
16955 16 => {
16956 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
16957 }
16958 32 => {
16959 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
16960 }
16961 64 => {
16962 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
16963 }
16964 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
16965 };
16966 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16967 let (rng, _) = dec.debug_state();
16968 let (mi_r, mi_c) = at_mi;
16969 eprintln!(
16970 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
16971 );
16972 }
16973 if depth != 0 {
16974 hit!(TX_DEPTH_HITS);
16975 }
16976 max_tx >> depth
16977}
16978
16979/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
16980/// `txfm_split` context -- a category from the block's own largest square
16981/// transform and whether this unit already sits below it, times three, plus
16982/// the two neighbour terms (whether the transform last written above/left of
16983/// this unit is narrower/shorter than the unit itself).
16984#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16985fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
16986 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
16987}
16988
16989/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
16990/// libaom's `txfm_partition_context` compares the above context against
16991/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
16992/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
16993/// side for a square transform, which is why the square form above is a
16994/// special case of this one.
16995pub(crate) fn txfm_partition_ctx_rect(
16996 above_px: u8,
16997 left_px: u8,
16998 blk_max_px: usize,
16999 tx_w: usize,
17000 tx_h: usize,
17001) -> usize {
17002 let above = usize::from(usize::from(above_px) < tx_w);
17003 let left = usize::from(usize::from(left_px) < tx_h);
17004 let tx_px = tx_w.max(tx_h);
17005 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
17006 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
17007 // `log2(px) - 2`.
17008 let max_tx = blk_max_px.min(64);
17009 let max_idx = max_tx.trailing_zeros() as usize - 2;
17010 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
17011 category * 3 + above + left
17012}
17013
17014/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
17015/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
17016/// resolved transform's own size.
17017#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17018fn txfm_partition_update(
17019 n: &mut Neighbours,
17020 at_mi: (usize, usize),
17021 tx_px: usize,
17022 txb_px: usize,
17023) {
17024 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
17025}
17026
17027/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
17028/// the left column records `tx_size_high` over the parent's own height and
17029/// the above row records `tx_size_wide` over its width.
17030/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
17031/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
17032/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
17033/// key frame writes neither (its readers use the deblock grid), so the
17034/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
17035/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
17036/// at the call site (the transform size comes back to them); the 1:4 arms
17037/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
17038/// so they call this where their own depth resolves. A no-op on a key frame
17039/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
17040///
17041/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
17042/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
17043/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
17044/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
17045/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
17046/// / early-return-skips-tail).
17047fn publish_txfm_bands_if_in_inter(
17048 n: &mut Neighbours,
17049 at_mi: (usize, usize),
17050 (tx_w, tx_h): (usize, usize),
17051 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
17052) {
17053 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
17054 return;
17055 }
17056 let (mi_r, mi_c) = at_mi;
17057 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17058 for i in 0..bw / MI {
17059 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17060 *cell = tx_w as u8;
17061 }
17062 }
17063 for i in 0..bh / MI {
17064 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17065 *cell = tx_h as u8;
17066 }
17067 }
17068}
17069
17070fn txfm_partition_update_rect(
17071 n: &mut Neighbours,
17072 (mi_r, mi_c): (usize, usize),
17073 (tx_w, tx_h): (usize, usize),
17074 (txb_w, txb_h): (usize, usize),
17075) {
17076 if crate::envflags::env_flag!("EC_TXUPD") {
17077 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
17078 }
17079 for i in 0..txb_h / MI {
17080 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17081 *cell = tx_h as u8;
17082 }
17083 }
17084 for i in 0..txb_w / MI {
17085 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17086 *cell = tx_w as u8;
17087 }
17088 }
17089}
17090
17091/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
17092/// same contexts -- a skipped *inter* block records its own block size rather
17093/// than its transform size.
17094fn set_txfm_ctxs(
17095 n: &mut Neighbours,
17096 (mi_r, mi_c): (usize, usize),
17097 tx_px: usize,
17098 w_mi: usize,
17099 h_mi: usize,
17100 skip_inter: bool,
17101) {
17102 if crate::envflags::env_flag!("EC_TXUPD") {
17103 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
17104 }
17105 let bw = if skip_inter { w_mi * MI } else { tx_px };
17106 let bh = if skip_inter { h_mi * MI } else { tx_px };
17107 for i in 0..w_mi {
17108 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17109 *cell = bw as u8;
17110 }
17111 }
17112 for i in 0..h_mi {
17113 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17114 *cell = bh as u8;
17115 }
17116 }
17117}
17118
17119/// The value libaom initialises both transform contexts to -- NOT zero:
17120/// `av1_zero_above_context` memsets the txfm row to
17121/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
17122/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17123/// pixels, so an unwritten neighbour reads as the *widest* possible
17124/// transform, not the narrowest.
17125pub(crate) const TXFM_CTX_INIT: u8 = 64;
17126
17127/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17128/// twice below its own largest transform.
17129const MAX_VARTX_DEPTH: usize = 2;
17130
17131/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
17132/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
17133/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
17134/// small ones, square everywhere else.
17135fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
17136 match (tx_w, tx_h) {
17137 (4, 4) => (4, 4),
17138 (8, 8) => (4, 4),
17139 (16, 16) => (8, 8),
17140 (32, 32) => (16, 16),
17141 (64, 64) => (32, 32),
17142 (4, 8) | (8, 4) => (4, 4),
17143 (8, 16) | (16, 8) => (8, 8),
17144 (16, 32) | (32, 16) => (16, 16),
17145 (32, 64) | (64, 32) => (32, 32),
17146 (4, 16) => (4, 8),
17147 (16, 4) => (8, 4),
17148 (8, 32) => (8, 16),
17149 (32, 8) => (16, 8),
17150 (16, 64) => (16, 32),
17151 (64, 16) => (32, 16),
17152 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
17153 }
17154}
17155
17156#[test]
17157fn sub_tx_size_map_matches_libaom() {
17158 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
17159 const TABLE: [((usize, usize), (usize, usize)); 19] = [
17160 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
17161 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
17162 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
17163 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
17164 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
17165 ];
17166 for (tx, want) in TABLE {
17167 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
17168 }
17169}
17170
17171/// The domain of var-tx leaf sizes, enumerated against the two refusals that
17172/// name a leaf "larger than 32x32" / "larger than 64x64".
17173///
17174/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
17175/// either the unit it was entered with or a `sub_tx_size_map` step below it:
17176/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
17177/// return. So the leaf set reachable from an entry unit is that unit plus the
17178/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
17179/// which this test enumerates, and over which no leaf is ever larger than the
17180/// entry.
17181///
17182/// That closes both refusals:
17183///
17184/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
17185/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
17186/// 64x64" names a leaf the tree cannot produce;
17187/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
17188/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
17189/// reached only when `side == 64`, and then the block is ONE unit whose only
17190/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
17191/// case the refusal is guarded by.
17192#[test]
17193fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
17194 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
17195 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
17196 out.push((depth, entry.0, entry.1));
17197 if depth == MAX_VARTX_DEPTH {
17198 return;
17199 }
17200 let sub = sub_tx_size_map(entry.0, entry.1);
17201 if sub == (4, 4) {
17202 out.push((depth + 1, 4, 4));
17203 return;
17204 }
17205 reachable(sub, depth + 1, out);
17206 }
17207
17208 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
17209 let mut leaves = Vec::new();
17210 reachable(entry, 0, &mut leaves);
17211 for (depth, w, h) in &leaves {
17212 assert!(
17213 w.max(h) <= &entry.0.max(entry.1),
17214 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
17215 entry.0,
17216 entry.1
17217 );
17218 }
17219 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
17220 if entry == (64, 64) {
17221 let above: Vec<&(usize, usize, usize)> =
17222 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
17223 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
17224 }
17225 }
17226
17227 // The entry size and ceiling each caller uses, over the block sides that
17228 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
17229 // enters at a fixed 64).
17230 for side in [8usize, 16, 32, 64, 128] {
17231 let max_tx = side.min(64);
17232 let ceiling = if side > 64 { 64 } else { 32 };
17233 let units = (side / max_tx) * (side / max_tx);
17234 if max_tx <= ceiling {
17235 continue;
17236 }
17237 assert_eq!(
17238 (side, units),
17239 (64, 1),
17240 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
17241 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
17242 );
17243 }
17244}
17245
17246/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
17247/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
17248/// max-transform-sized unit of an inter block, collecting the resolved leaf
17249/// transform units into `out` as `(row offset, col offset, side)` in mi units
17250/// -- exactly the order `decode_reconstruct_tx` later reads their
17251/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
17252/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
17253/// `max_block_high`).
17254#[allow(clippy::too_many_arguments)]
17255fn read_var_tx_size(
17256 dec: &mut SymbolDecoder,
17257 cdfs: &mut Cdfs,
17258 n: &mut Neighbours,
17259 at_mi: (usize, usize),
17260 blk_max_px: usize,
17261 (max_w_mi, max_h_mi): (usize, usize),
17262 (tx_w, tx_h): (usize, usize),
17263 depth: usize,
17264 blk_row: usize,
17265 blk_col: usize,
17266 out: &mut Vec<(usize, usize, usize, usize)>,
17267) {
17268 if blk_row >= max_h_mi || blk_col >= max_w_mi {
17269 return;
17270 }
17271 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
17272 if depth == MAX_VARTX_DEPTH {
17273 out.push((blk_row, blk_col, tx_w, tx_h));
17274 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17275 return;
17276 }
17277 let ctx = txfm_partition_ctx_rect(
17278 n.above_txfm[unit.1],
17279 n.left_txfm[unit.0],
17280 blk_max_px,
17281 tx_w,
17282 tx_h,
17283 );
17284 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17285 hit!(TXFM_SPLIT_READS);
17286 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17287 let (rng, _) = dec.debug_state();
17288 eprintln!(
17289 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
17290 unit.0,
17291 unit.1,
17292 u8::from(split)
17293 );
17294 }
17295 if !split {
17296 out.push((blk_row, blk_col, tx_w, tx_h));
17297 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17298 return;
17299 }
17300 hit!(TXFM_SPLIT_HITS);
17301 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17302 if (sub_w, sub_h) == (4, 4) {
17303 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
17304 // unit is marked 4x4 (raster order) without recursing.
17305 for row in 0..tx_h / MI {
17306 for col in 0..tx_w / MI {
17307 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
17308 out.push((blk_row + row, blk_col + col, 4, 4));
17309 }
17310 }
17311 }
17312 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
17313 return;
17314 }
17315 for row in (0..tx_h / MI).step_by(sub_h / MI) {
17316 for col in (0..tx_w / MI).step_by(sub_w / MI) {
17317 read_var_tx_size(
17318 dec,
17319 cdfs,
17320 n,
17321 at_mi,
17322 blk_max_px,
17323 (max_w_mi, max_h_mi),
17324 (sub_w, sub_h),
17325 depth + 1,
17326 blk_row + row,
17327 blk_col + col,
17328 out,
17329 );
17330 }
17331 }
17332}
17333
17334/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
17335/// branch): every block of a `TxMode::Select` inter frame codes its transform
17336/// size right after its own mode info -- an inter non-skip block through the
17337/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
17338/// every other block through the intra `tx_depth` symbol (a skipped inter
17339/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
17340/// block's own resolved transform side and the leaf list, the latter only
17341/// when the tree resolved to more than one transform unit.
17342#[allow(clippy::too_many_arguments)]
17343fn read_block_tx_size(
17344 dec: &mut SymbolDecoder,
17345 cdfs: &mut Cdfs,
17346 n: &mut Neighbours,
17347 at_mi: (usize, usize),
17348 side: usize,
17349 (mi_cols, mi_rows): (usize, usize),
17350 is_inter: bool,
17351 skip: bool, fctx: &crate::decode::FrameCtx,
17352) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17353 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17354 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
17355 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
17356 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
17357 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
17358 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
17359 if side > 64 {
17360 let step = 64 / MI;
17361 let mut leaves = Vec::new();
17362 for row in (0..side / MI).step_by(step) {
17363 for col in (0..side / MI).step_by(step) {
17364 leaves.push((row, col, 64, 64));
17365 }
17366 }
17367 return Ok((64, Some(leaves)));
17368 }
17369 return Ok((side, None));
17370 }
17371 let side_mi = side / MI;
17372 if is_inter && !skip {
17373 let max_tx = side.min(64);
17374 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
17375 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
17376 let mut leaves = Vec::new();
17377 let step = max_tx / MI;
17378 for row in (0..side_mi).step_by(step) {
17379 for col in (0..side_mi).step_by(step) {
17380 read_var_tx_size(
17381 dec,
17382 cdfs,
17383 n,
17384 at_mi,
17385 side,
17386 (max_w_mi, max_h_mi),
17387 (max_tx, max_tx),
17388 0,
17389 row,
17390 col,
17391 &mut leaves,
17392 );
17393 }
17394 }
17395 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
17396 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
17397 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
17398 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
17399 // which the mu-chunk reader above codes as their 32x32 coded corner.
17400 let leaf_ceiling = if side > 64 { 64 } else { 32 };
17401 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
17402 // Only a block wider than a superblock's own 64x64 max transform
17403 // reaches here; this crate has no 64-point *inter* coefficient
17404 // table set ([`inter_txbset_for`] stops at 32).
17405 return Err(unsupported(
17406 "an inter var-tx tree with a leaf transform larger than 32x32",
17407 ));
17408 }
17409 let resolved = leaves.last().map_or(side, |l| l.2);
17410 return Ok((resolved, (!single).then_some(leaves)));
17411 }
17412 let tx = if is_inter {
17413 side.min(64)
17414 } else {
17415 read_tx_size(
17416 dec,
17417 cdfs,
17418 n,
17419 at_mi,
17420 side,
17421 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
17422 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
17423 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
17424 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
17425 )
17426 };
17427 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
17428 if !is_inter && tx != side {
17429 // lane-intrainter r1: an intra block inside an inter frame whose
17430 // `tx_depth` split its luma transform codes exactly the key-frame
17431 // split path's transform units (`decode_block`'s multi-TU loop),
17432 // raster order over the block. Handed back in the same leaf shape the
17433 // inter var-tx tree uses, so the caller's per-TU luma loop, the
17434 // `record_split_luma` neighbour write-back and the per-TU deblock
17435 // edges are the ones it already runs for a var-tx inter block. A
17436 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
17437 // seeing `Some` here.
17438 let step = tx / MI;
17439 let mut leaves = Vec::new();
17440 for row in (0..side_mi).step_by(step) {
17441 for col in (0..side_mi).step_by(step) {
17442 leaves.push((row, col, tx, tx));
17443 }
17444 }
17445 hit_do! {
17446 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
17447 let mut h = c.get();
17448 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
17449 c.set(h);
17450 });
17451 }
17452 return Ok((tx, Some(leaves)));
17453 }
17454 Ok((tx, None))
17455}
17456
17457/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
17458/// decoder codes -- a 2:1 strip whose own max rect transform
17459/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
17460/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
17461/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
17462/// 64-point rect transform, and 16x8/8x16 needs
17463/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
17464/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
17465/// rect transform), neither of which exists yet -- both stay refused by name.
17466pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
17467 matches!(
17468 (w, h),
17469 // 2:1 strips whose transform is coded in full (lane-inter4).
17470 (32, 16) | (16, 32) | (16, 8) | (8, 16)
17471 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
17472 // codes all 64 of its positions, and its chroma pair is an 8x4 /
17473 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
17474 | (16, 4) | (4, 16)
17475 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
17476 // only the low 32 coefficients of a 64-length axis, so these read
17477 // exactly the truncated corner the INTRA superblock-strip path
17478 // already reads (`read_intra_mode_rect`), through
17479 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
17480 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
17481 // `tx_type` symbol is coded at all.
17482 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
17483 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
17484 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
17485 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
17486 // refused earlier ("an inter partition below 8x8").
17487 | (8, 4) | (4, 8)
17488 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
17489 // one rectangular transform -- `max_txsize_rect_lookup
17490 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
17491 // TX_64X64 units read through the mu-chunk loop, same as the
17492 // 128x128 NONE block's four.
17493 | (128, 64) | (64, 128)
17494 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
17495 // 10-bit film cuts and every measured 1080p offset stop on
17496 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
17497 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
17498 // positions, and its chroma pair is a 16x4 / 4x16 unit
17499 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
17500 | (32, 8) | (8, 32)
17501 )
17502}
17503
17504// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
17505// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
17506// the "rectangular ... has no ... here" refusals. `side` is the square context
17507// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
17508// `inter_piece!` derives `reject_residual` from exactly that inequality, so
17509// these triples are what decides whether those refusals can fire at all. Bit
17510// 31 is "a triple this table does not list", which is what makes the gate a
17511// census rather than a restatement of its own table.
17512pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
17513 (16, 16, 16),
17514 (32, 32, 32),
17515 (32, 16, 32),
17516 (32, 32, 16),
17517 (16, 8, 16),
17518 (16, 16, 8),
17519 (32, 8, 32),
17520 (64, 64, 64),
17521 (32, 32, 8),
17522 (64, 16, 64),
17523 (128, 128, 128),
17524 (64, 32, 64),
17525 (64, 64, 32),
17526 (16, 4, 16),
17527 (64, 64, 16),
17528 (16, 16, 4),
17529 (128, 128, 64),
17530 (128, 64, 128),
17531];
17532
17533/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
17534/// outside [`INTER_BLOCK_SHAPES`].
17535pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
17536
17537thread_local! {
17538 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
17539}
17540
17541/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
17542/// gate reading it sees only the streams it decoded itself).
17543pub fn inter_block_shape_mask() -> u32 {
17544 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
17545}
17546
17547/// Records one block's shape. The table is ordered by measured frequency over
17548/// the three witnesses the census gate decodes, so the common square shapes
17549/// leave the scan on their first comparison.
17550fn census_inter_block_shape(side: usize, w: usize, h: usize) {
17551 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
17552 Some(i) => 1u32 << i,
17553 None => INTER_BLOCK_SHAPE_UNLISTED,
17554 };
17555 let seen = inter_block_shape_mask();
17556 if seen & bit == 0 {
17557 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
17558 }
17559}
17560
17561/// The luma coefficient/`tx_type` table set of a whole-block rectangular
17562/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
17563/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
17564/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
17565/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
17566/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
17567/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
17568/// row (`txsize_sqr_map`), never the 16x16 one.
17569fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
17570 Ok(match (w, h) {
17571 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
17572 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
17573 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
17574 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
17575 // ALL16 otherwise -- both at the TX_4X4 row.
17576 (8, 4) | (4, 8) => {
17577 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17578 TxbSet::LumaRect8x4Inter
17579 } else {
17580 TxbSet::LumaRect8x4InterSet1
17581 }
17582 }
17583 (16, 4) | (4, 16) => {
17584 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17585 TxbSet::LumaRect16x4Inter
17586 } else {
17587 TxbSet::LumaRect16x4Inter1
17588 }
17589 }
17590 (16, 8) | (8, 16) => {
17591 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17592 TxbSet::LumaRect16x8Inter
17593 } else {
17594 TxbSet::LumaRect16x8InterSet1
17595 }
17596 }
17597 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
17598 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
17599 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
17600 // adjusted size, so the existing sets are bit-exact. Neither carries a
17601 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
17602 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
17603 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
17604 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
17605 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
17606 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
17607 (64, 32) | (32, 64) => TxbSet::Luma64,
17608 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
17609 _ => {
17610 return Err(unsupported(
17611 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
17612 ));
17613 }
17614 })
17615}
17616
17617/// The chroma table set of the same block's single rectangular chroma unit
17618/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
17619/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
17620/// the luma unit's.
17621fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
17622 Ok(match (w, h) {
17623 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
17624 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
17625 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
17626 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
17627 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
17628 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
17629 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
17630 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
17631 (32, 8) | (8, 32) => TxbSet::Chroma16,
17632 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
17633 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
17634 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
17635 (16, 4) | (4, 16) => TxbSet::Chroma8,
17636 _ => {
17637 return Err(unsupported(
17638 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
17639 ));
17640 }
17641 })
17642}
17643
17644/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
17645/// inter path reaches, from the block's TRUE footprint rather than the
17646/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
17647/// everything 32 and above -> 3.
17648fn size_group_wh(w: usize, h: usize) -> usize {
17649 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
17650 // `common_data.h:60`) is 0 for every block with a 4-px side
17651 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
17652 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
17653 match w.min(h) {
17654 0..=4 => 0,
17655 8 => 1,
17656 16 => 2,
17657 _ => 3,
17658 }
17659}
17660
17661#[test]
17662fn size_group_wh_matches_libaom_size_group_lookup() {
17663 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
17664 // transcribed values (common_data.h:60-62).
17665 const TABLE: [((usize, usize), usize); 22] = [
17666 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
17667 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
17668 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
17669 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
17670 ];
17671 for ((w, h), want) in TABLE {
17672 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
17673 }
17674}
17675
17676/// The default (2D) coefficient scan of a rectangular transform.
17677fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
17678 Ok(match (w, h) {
17679 (32, 16) => &SCAN_32X16,
17680 (16, 32) => &SCAN_16X32,
17681 (16, 8) => &SCAN_16X8,
17682 (8, 16) => &SCAN_8X16,
17683 (16, 4) => &SCAN_16X4,
17684 (4, 16) => &SCAN_4X16,
17685 (8, 4) => &SCAN_8X4,
17686 (4, 8) => &SCAN_4X8,
17687 (32, 8) => &SCAN_32X8,
17688 (8, 32) => &SCAN_8X32,
17689 _ => {
17690 return Err(unsupported(
17691 "a rectangular transform unit whose shape has no coefficient scan table here",
17692 ));
17693 }
17694 })
17695}
17696
17697/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
17698/// transform unit whose shape has no coefficient table set here" / "a
17699/// rectangular transform unit whose shape has no coefficient scan table here"
17700/// arms, enumerated against the MEASURED domain of the inter block path
17701/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
17702/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
17703///
17704/// What each helper is actually handed:
17705///
17706/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
17707/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
17708/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
17709/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
17710/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
17711/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
17712/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
17713/// unit, and only when that corner is not 32x32 (a square corner goes
17714/// through the square reader with `rect_shape = Some((w, h))`).
17715///
17716/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
17717/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
17718/// loop, which is why they are skipped below.
17719#[test]
17720fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
17721 let fctx = &crate::decode::FrameCtx::new();
17722 let corner_scan = |w: usize, h: usize| {
17723 let (cw, ch) = (w.min(32), h.min(32));
17724 if (cw, ch) == (32, 32) {
17725 return; // the square coefficient reader, not `rect_scan`
17726 }
17727 assert!(
17728 rect_scan(cw, ch).is_ok(),
17729 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
17730 );
17731 };
17732 let mut checked = 0;
17733 for &(side, w, h) in &INTER_BLOCK_SHAPES {
17734 if (w, h) == (side, side) || w.max(h) > 64 {
17735 continue;
17736 }
17737 assert!(
17738 rect_inter_luma_set(w, h, fctx).is_ok(),
17739 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
17740 );
17741 corner_scan(w, h);
17742 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
17743 // footprint for every other shape.
17744 let (cw, ch) = match (w, h) {
17745 (16, 4) => (8, 4),
17746 (4, 16) => (4, 8),
17747 _ => (w / 2, h / 2),
17748 };
17749 assert!(
17750 rect_inter_chroma_set(cw, ch).is_ok(),
17751 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
17752 );
17753 corner_scan(cw, ch);
17754 checked += 1;
17755 }
17756 assert_eq!(
17757 checked, 12,
17758 "the block-shape census changed: {checked} rect shapes reach the rect transform \
17759 tables, not the 12 this claim was measured over"
17760 );
17761 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
17762 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
17763 for (w, h) in [(8usize, 4usize), (4, 8)] {
17764 assert!(
17765 rect_inter_luma_set(w, h, fctx).is_ok(),
17766 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
17767 );
17768 corner_scan(w, h);
17769 }
17770}
17771
17772/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
17773/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
17774/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
17775/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
17776/// own width/height; a `0` leaves one whole-block rect transform unit
17777/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
17778/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
17779/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
17780/// every leaf of a split rect block is square and the existing square leaf
17781/// loop reconstructs it unchanged.
17782#[allow(clippy::too_many_arguments)]
17783fn read_block_tx_size_rect(
17784 dec: &mut SymbolDecoder,
17785 cdfs: &mut Cdfs,
17786 n: &mut Neighbours,
17787 at_mi: (usize, usize),
17788 (bw, bh): (usize, usize),
17789 (mi_cols, mi_rows): (usize, usize),
17790 skip: bool, fctx: &crate::decode::FrameCtx,
17791) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
17792 if skip {
17793 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
17794 // its own BLOCK size -- width above, height left -- not a transform.
17795 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
17796 return Ok(None);
17797 }
17798 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
17799 // `rect_inter_residual_supported` has already excluded everything above 32.
17800 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
17801 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
17802 // is TWO square top-level transform units side by side and a 64x128 one is
17803 // two stacked -- exactly what libaom `read_block_tx_size`
17804 // (decodeframe.c:1140) codes with its `idy/idx` loop over
17805 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
17806 // own `txfm_partition` symbol at depth 0.
17807 if bw.max(bh) > 64 {
17808 let tx = 64usize;
17809 let (max_w_mi, max_h_mi) = (
17810 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
17811 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
17812 );
17813 let mut leaves = Vec::new();
17814 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17815 for row in (0..bh / MI).step_by(tx / MI) {
17816 for col in (0..bw / MI).step_by(tx / MI) {
17817 leaves.push((row, col, tx, tx));
17818 }
17819 }
17820 for &(row, col, tw, th) in &leaves {
17821 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
17822 }
17823 return Ok(Some(leaves));
17824 }
17825 for row in (0..bh / MI).step_by(tx / MI) {
17826 for col in (0..bw / MI).step_by(tx / MI) {
17827 read_var_tx_size(
17828 dec,
17829 cdfs,
17830 n,
17831 at_mi,
17832 bw.max(bh),
17833 (max_w_mi, max_h_mi),
17834 (tx, tx),
17835 0,
17836 row,
17837 col,
17838 &mut leaves,
17839 );
17840 }
17841 }
17842 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
17843 return Err(unsupported(
17844 "an inter var-tx tree with a leaf transform larger than 64x64",
17845 ));
17846 }
17847 return Ok(Some(leaves));
17848 }
17849 let (tx_w, tx_h) = (bw, bh);
17850 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17851 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
17852 // transform, and `set_txfm_ctxs` records exactly what
17853 // `txfm_partition_update` would for that same unit.
17854 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17855 hit!(RECT_INTER_TU_HITS);
17856 return Ok(None);
17857 }
17858 let ctx = txfm_partition_ctx_rect(
17859 n.above_txfm[at_mi.1],
17860 n.left_txfm[at_mi.0],
17861 bw.max(bh),
17862 tx_w,
17863 tx_h,
17864 );
17865 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17866 hit!(TXFM_SPLIT_READS);
17867 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17868 let (rng, _) = dec.debug_state();
17869 eprintln!(
17870 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17871 at_mi.0,
17872 at_mi.1,
17873 u8::from(split)
17874 );
17875 }
17876 if !split {
17877 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17878 hit!(RECT_INTER_TU_HITS);
17879 return Ok(None);
17880 }
17881 hit!(TXFM_SPLIT_HITS);
17882 hit!(RECT_INTER_TXSPLIT_HITS);
17883 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
17884 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
17885 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
17886 // rect one and its leaves carry their own width and height.
17887 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17888 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
17889 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
17890 let mut leaves = Vec::new();
17891 for row in (0..bh / MI).step_by(sub_h / MI) {
17892 for col in (0..bw / MI).step_by(sub_w / MI) {
17893 read_var_tx_size(
17894 dec,
17895 cdfs,
17896 n,
17897 at_mi,
17898 bw.max(bh),
17899 (max_w_mi, max_h_mi),
17900 (sub_w, sub_h),
17901 1,
17902 row,
17903 col,
17904 &mut leaves,
17905 );
17906 }
17907 }
17908 Ok(Some(leaves))
17909}
17910
17911/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
17912/// the coefficients are read with the rect coefficient machinery
17913/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
17914/// types), inverted with the rect inverse transform
17915/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
17916/// and added onto the top-left `w x h` of the block's own square-strided
17917/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
17918/// and the coded `tx_type`.
17919///
17920/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
17921/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
17922#[allow(clippy::too_many_arguments)]
17923fn read_inter_plane_rect(
17924 dec: &mut SymbolDecoder,
17925 cdfs: &mut Cdfs,
17926 set: TxbSet,
17927 (w, h): (usize, usize),
17928 stride: usize,
17929 plane_idx: usize,
17930 around: (bool, bool, i32),
17931 tx_mode: usize,
17932 // lane-wave1 step (i): unread -- this reader records its write
17933 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
17934 // stays in the signature so every call site still proves the plane is
17935 // exclusively held while its coefficients are parsed.
17936 _plane: &mut PlaneBuf<'static>,
17937 x: usize,
17938 y: usize,
17939 prediction: Pred<'_>,
17940 inherited_luma_tx_type: Option<TxType>,
17941 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
17942) -> Result<(Grid, TxType)> {
17943 let skip_ctx = if plane_idx == 0 {
17944 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
17945 // block; a var-tx leaf passes its own neighbour-table context.
17946 luma_skip_ctx.unwrap_or(0)
17947 } else {
17948 usize::from(around.0) + usize::from(around.1)
17949 };
17950 let mut coding = cdfs.txb(set, tx_mode);
17951 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
17952 // the *longer* side of this rect transform.
17953 let default_tx_type = match inherited_luma_tx_type {
17954 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
17955 None => TxType::DctDct,
17956 };
17957 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
17958 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
17959 // corner, zero-extended into the true `w x h` grid before the inverse
17960 // transform -- exactly what the intra superblock-strip path does. A
17961 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
17962 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
17963 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
17964 // rectangular shape (lane-sbpart r8).
17965 let (cw, ch) = (w.min(32), h.min(32));
17966 if plane_idx == 0 && w.max(h) == 64 {
17967 hit!(RECT64_INTER_TU_HITS);
17968 }
17969 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
17970 hit_do! {
17971 RECT32X8_INTER_TU_HITS.with(|c| {
17972 let mut v = c.get();
17973 v[usize::from(w == 8)] += 1;
17974 c.set(v);
17975 });
17976 }
17977 }
17978 let (corner, tx_type) = if (cw, ch) == (32, 32) {
17979 let scan32 = default_scan(TX32);
17980 read_coeffs(
17981 dec,
17982 &mut coding,
17983 &scan32,
17984 skip_ctx,
17985 dc_sign_ctx(around.2),
17986 default_tx_type,
17987 Some((w, h)),
17988 )?
17989 } else {
17990 read_coeffs_rect(
17991 dec,
17992 &mut coding,
17993 rect_scan(cw, ch)?,
17994 cw,
17995 ch,
17996 skip_ctx,
17997 dc_sign_ctx(around.2),
17998 default_tx_type,
17999 )?
18000 };
18001 let grid = extend_corner(corner, cw, ch, w, h);
18002 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
18003 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
18004 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
18005 }
18006 // `reconstruct_mc_rect` reads both buffers at the square prediction
18007 // stride, so the dense `w x h` residual is re-laid at that stride
18008 // (`TxParams::stride`) after the inverse transform.
18009 let tx = TxParams {
18010 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18011 stride,
18012 };
18013 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
18014 Ok((grid, tx_type))
18015}
18016
18017/// The coded `cw x ch` corner of a transform zero-extended into its true
18018/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
18019/// corner that coded nothing stays the shared zero grid -- no allocation
18020/// (lane-coefgrid).
18021fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
18022 if (cw, ch) == (w, h) {
18023 return corner;
18024 }
18025 if let Grid::Zero(_) = corner {
18026 return Grid::Zero(w * h);
18027 }
18028 let mut full = vec![0i32; w * h];
18029 for row in 0..ch {
18030 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
18031 }
18032 Grid::Own(full)
18033}
18034
18035/// A rect coefficient grid re-laid into the square `stride x stride` grid the
18036/// neighbour/deblock stamps downstream of the residual expect.
18037fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
18038 let mut full = vec![0i32; stride * stride];
18039 for row in 0..h {
18040 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
18041 }
18042 full
18043}
18044
18045/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
18046/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
18047/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
18048/// raster order, each reading its own coefficient context off the units
18049/// already decoded before it. Returns the block's luma grid (all-zero in the
18050/// split case, whose reconstruction has already happened unit by unit) and
18051/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
18052/// which for a split block lands on the top-left unit.
18053#[allow(clippy::too_many_arguments)]
18054fn read_inter_luma8(
18055 dec: &mut SymbolDecoder,
18056 cdfs: &mut Cdfs,
18057 neighbours: &mut Neighbours,
18058 leaf_mi: (usize, usize),
18059 y: &mut PlaneBuf<'static>,
18060 px: usize,
18061 py: usize,
18062 pred_y: Pred<'_>,
18063 mode_for_tx: usize,
18064 base_q_idx: u8,
18065 scan8: &[u16],
18066 scan4: &[u16],
18067 reduced_tx_set: bool,
18068 split: bool, fctx: &crate::decode::FrameCtx,
18069) -> Result<(Grid, TxType)> {
18070 if !split {
18071 return read_inter_plane(
18072 dec,
18073 cdfs,
18074 if reduced_tx_set {
18075 TxbSet::Luma8Inter
18076 } else {
18077 TxbSet::Luma8InterSet1
18078 },
18079 scan8,
18080 0,
18081 neighbours.around_mi(leaf_mi, 8)[0],
18082 mode_for_tx,
18083 y,
18084 px,
18085 py,
18086 8,
18087 base_q_idx,
18088 pred_y,
18089 None,
18090 None, fctx,
18091 );
18092 }
18093 let mut first = TxType::DctDct;
18094 for tu_row in 0..2 {
18095 for tu_col in 0..2 {
18096 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18097 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
18098 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18099 let (tu_grid, tu_tx_type) = read_inter_plane(
18100 dec,
18101 cdfs,
18102 if reduced_tx_set {
18103 TxbSet::Luma4Inter
18104 } else {
18105 TxbSet::Luma4InterSet1
18106 },
18107 scan4,
18108 0,
18109 neighbours.around_mi(tu_mi, 4)[0],
18110 mode_for_tx,
18111 y,
18112 px + tu_col * 4,
18113 py + tu_row * 4,
18114 4,
18115 base_q_idx,
18116 tu_pred,
18117 None,
18118 Some(tu_skip_ctx), fctx,
18119 )?;
18120 if tu_row == 0 && tu_col == 0 {
18121 first = tu_tx_type;
18122 }
18123 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18124 }
18125 }
18126 Ok((Grid::Zero(64), first))
18127}
18128
18129/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
18130/// coefficient tables from -- the inter counterpart of [`txbset_for`].
18131/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
18132/// an inter block's chroma transform inherits the *colocated luma* unit's
18133/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
18134/// of the extended set the CHROMA transform size selects
18135/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
18136/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
18137/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
18138/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
18139/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
18140/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
18141/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
18142/// sync and only corrupted the inverse transform (one 64x64 superblock of
18143/// high-frequency chroma noise, luma bit-exact).
18144fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
18145 use TxType::*;
18146 let sqr_up = w.max(h);
18147 let sqr = w.min(h);
18148 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
18149 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
18150 let allowed: &[TxType] = if sqr_up > 32 {
18151 // EXT_TX_SET_DCTONLY
18152 &[DctDct]
18153 } else if sqr_up == 32 || reduced {
18154 // EXT_TX_SET_DCT_IDTX
18155 &[DctDct, Idtx]
18156 } else if sqr == 16 {
18157 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
18158 // the four 1D ADST/FLIPADST types.
18159 &[
18160 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
18161 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
18162 ]
18163 } else {
18164 // EXT_TX_SET_ALL16
18165 return t;
18166 };
18167 if allowed.contains(&t) { t } else { DctDct }
18168}
18169
18170fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18171 match tx_px {
18172 // lane-sb128c r1: a 128x128 inter block's own luma unit
18173 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
18174 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
18175 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
18176 // coincide -- exactly the set the whole-64x64 inter block already uses.
18177 64 => TxbSet::Luma64,
18178 32 => TxbSet::Luma32Inter,
18179 16 if reduced_tx_set => TxbSet::Luma16Inter,
18180 16 => TxbSet::Luma16InterSet1,
18181 8 if reduced_tx_set => TxbSet::Luma8Inter,
18182 8 => TxbSet::Luma8InterSet1,
18183 4 if reduced_tx_set => TxbSet::Luma4Inter,
18184 4 => TxbSet::Luma4InterSet1,
18185 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
18186 }
18187}
18188
18189/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
18190/// the only four sizes a `TxMode::Select` block's coded coefficient grid
18191/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
18192fn scan_for<'a>(
18193 tx_px: usize,
18194 scan32: &'a [u16],
18195 scan16: &'a [u16],
18196 scan8: &'a [u16],
18197 scan4: &'a [u16],
18198) -> &'a [u16] {
18199 match tx_px {
18200 32 => scan32,
18201 16 => scan16,
18202 8 => scan8,
18203 4 => scan4,
18204 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
18205 }
18206}
18207
18208/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
18209/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
18210/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
18211/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
18212/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
18213/// regardless of the flag (`av1_get_ext_tx_set_type`'s
18214/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
18215/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
18216/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
18217/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
18218/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
18219/// inter `ext_tx` sets, never the mode-indexed intra ones.
18220fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18221 match tx_px {
18222 64 => TxbSet::Luma64,
18223 32 => TxbSet::Luma32Inter,
18224 16 if reduced_tx_set => TxbSet::Luma16Inter,
18225 16 => TxbSet::Luma16InterSet1,
18226 8 if reduced_tx_set => TxbSet::Luma8Inter,
18227 8 => TxbSet::Luma8InterSet1,
18228 _ => TxbSet::Luma64,
18229 }
18230}
18231
18232fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18233 match tx_px {
18234 64 => TxbSet::Luma64,
18235 32 => TxbSet::Luma32,
18236 16 => TxbSet::Luma16,
18237 8 if reduced_tx_set => TxbSet::Luma8,
18238 8 => TxbSet::Luma8Set1,
18239 4 if reduced_tx_set => TxbSet::Luma4,
18240 4 => TxbSet::Luma4Set1,
18241 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
18242 }
18243}
18244
18245/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
18246/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
18247fn unit_log2(px: u32) -> i32 {
18248 if px == 0 {
18249 0
18250 } else {
18251 px.trailing_zeros() as i32 - 2
18252 }
18253}
18254
18255/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
18256/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
18257/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
18258/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
18259/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
18260/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
18261/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
18262/// block anywhere aborted the whole stream's decode before comparison).
18263fn lf_level(
18264 lf: &LoopFilterParams,
18265 plane_idx: usize,
18266 dir: usize,
18267 ref_frame: i8,
18268 delta_lf: i32,
18269 segment_id: u8, fctx: &crate::decode::FrameCtx,
18270) -> i32 {
18271 let base = i32::from(if plane_idx == 0 {
18272 lf.level[dir]
18273 } else if plane_idx == 1 {
18274 lf.level[2]
18275 } else {
18276 lf.level[3]
18277 });
18278 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
18279 // ref/mode delta scaling below, and regardless of `delta_enabled`
18280 // (that flag only gates `ref_deltas`/`mode_deltas`).
18281 let base = (base + delta_lf).clamp(0, 63);
18282 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
18283 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
18284 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
18285 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
18286 // for chroma.
18287 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18288 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
18289 // when the frame codes no segmentation (`seg_lf_active`), which is what
18290 // spares the deblock loop two thread-local reads per 4x4 edge.
18291 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
18292 Some(data) => (base + data).clamp(0, 63),
18293 None => base,
18294 };
18295 if !lf.delta_enabled {
18296 return base;
18297 }
18298 let scale = 1i32 << (base >> 5);
18299 let is_inter = ref_frame != 0;
18300 let is_globalmv = ref_frame < 0;
18301 let ref_idx = ref_frame.unsigned_abs() as usize;
18302 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
18303 if is_inter {
18304 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
18305 }
18306 lvl.clamp(0, 63)
18307}
18308
18309thread_local! {
18310 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
18311 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
18312 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
18313 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
18314 /// build per plane and pass serves the whole frame. The pipeline builds
18315 /// an `EdgeCtx` per superblock-row band rather than per frame, which
18316 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
18317 static LVL_CACHE: std::cell::RefCell<
18318 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
18319 > = const { std::cell::RefCell::new(Vec::new()) };
18320}
18321
18322/// `lf_level` over the whole `(base level, ref frame)` domain -- see
18323/// [`LVL_CACHE`]. `lf_level`'s own first step is
18324/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
18325/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
18326fn lvl_table(
18327 lf: &LoopFilterParams,
18328 plane_idx: usize,
18329 dir: usize,
18330 base0: i32,
18331 fctx: &crate::decode::FrameCtx,
18332) -> [[u8; 15]; 64] {
18333 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18334 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
18335 if let Some(t) = LVL_CACHE.with(|c| {
18336 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
18337 }) {
18338 return t;
18339 }
18340 let mut lvl = [[0u8; 15]; 64];
18341 for (b, row) in lvl.iter_mut().enumerate() {
18342 for (r, cell) in row.iter_mut().enumerate() {
18343 *cell =
18344 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
18345 }
18346 }
18347 LVL_CACHE.with(|c| {
18348 let mut c = c.borrow_mut();
18349 if c.len() >= 8 {
18350 c.remove(0);
18351 }
18352 c.push((key, lvl));
18353 });
18354 lvl
18355}
18356
18357/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18358/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18359/// that a coded block's transform is always its own full size -- so a TU
18360/// edge is always also a PU edge, and the "both sides skipped, not a PU
18361/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18362/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18363/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18364/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
18365/// seven values that used to be re-passed per 4-pixel edge group -- half of
18366/// them on the stack, into an `inline(never)` body -- plus libaom's
18367/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
18368/// filter level for every `(base level, ref frame)` pair once per frame
18369/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
18370struct EdgeCtx<'a> {
18371 lf: &'a LoopFilterParams,
18372 n: &'a Neighbours,
18373 fctx: &'a crate::decode::FrameCtx,
18374 plane_idx: usize,
18375 dir: usize,
18376 chroma: bool,
18377 seg_lf_active: bool,
18378 /// `delta_lf_grid`'s column for this plane and direction.
18379 delta_idx: usize,
18380 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
18381 /// chroma.
18382 step: usize,
18383 /// This pass's own `lf.level[..]`, the LUT's base.
18384 base0: i32,
18385 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
18386 /// override -- the whole domain, since a level is `0..=63` and a ref
18387 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
18388 /// entries and is indexed by the ref frame's magnitude).
18389 lvl: [[u8; 15]; 64],
18390}
18391
18392impl<'a> EdgeCtx<'a> {
18393 fn new(
18394 lf: &'a LoopFilterParams,
18395 n: &'a Neighbours,
18396 plane_idx: usize,
18397 dir: usize,
18398 chroma: bool,
18399 seg_lf_active: bool,
18400 fctx: &'a crate::decode::FrameCtx,
18401 ) -> Self {
18402 let base0 = i32::from(if plane_idx == 0 {
18403 lf.level[dir]
18404 } else if plane_idx == 1 {
18405 lf.level[2]
18406 } else {
18407 lf.level[3]
18408 });
18409 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
18410 Self {
18411 lf,
18412 n,
18413 fctx,
18414 plane_idx,
18415 dir,
18416 chroma,
18417 seg_lf_active,
18418 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
18419 step: if chroma { 2 } else { 1 },
18420 base0,
18421 lvl,
18422 }
18423 }
18424
18425 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
18426 /// override it (which is every frame that codes no segmentation).
18427 #[inline(always)]
18428 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
18429 if self.seg_lf_active {
18430 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
18431 }
18432 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
18433 debug_assert!((-7..=7).contains(&ref_frame));
18434 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
18435 i32::from(self.lvl[b][r])
18436 }
18437}
18438
18439/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18440/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18441/// that a coded block's transform is always its own full size -- so a TU
18442/// edge is always also a PU edge, and the "both sides skipped, not a PU
18443/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18444/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18445/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18446#[inline(always)]
18447fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
18448 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
18449 let cur_tx = if c.dir == 0 {
18450 tx_px_at(c.n, c.chroma, mi_r, mi_c)
18451 } else {
18452 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
18453 };
18454 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
18455 // test is a mask, not the hardware `divl` this used to emit (10.7% of
18456 // `edge_params`' own samples sat on that divide's result test).
18457 //
18458 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
18459 // the covering transform does not start at), so this head is inlined
18460 // into the deblock loops and only survivors pay the call and the
18461 // register-spilling prologue of the body below.
18462 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
18463 return None;
18464 }
18465 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
18466}
18467
18468/// [`edge_params`] past its transform-alignment gate.
18469#[inline(never)]
18470fn edge_params_body(
18471 c: &EdgeCtx,
18472 x0: usize,
18473 y0: usize,
18474 mi_r: usize,
18475 mi_c: usize,
18476 cur_tx: u32,
18477) -> Option<(u8, i32)> {
18478 let n = c.n;
18479 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18480 // The previous cell must keep the odd parity `plane_to_mi` just
18481 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
18482 // not the other half of this one.
18483 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
18484 (mi_r, mi_c - c.step)
18485 } else {
18486 (mi_r - c.step, mi_c)
18487 };
18488 let pv_tx = if c.dir == 0 {
18489 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18490 } else {
18491 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18492 };
18493 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
18494 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
18495 let pv_delta_lf =
18496 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
18497
18498 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
18499 // SKIPPED INTER blocks is filtered only when it is also a prediction
18500 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
18501 // omission of this term (on the stale invariant "a coded block's transform
18502 // is always its own full size", which var-tx broke) had us filtering an
18503 // interior 8-px lattice the reference never touches: on the pinned 192x68
18504 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
18505 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
18506 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
18507 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
18508 // edge of a sub-8x8 group is a prediction edge, even though the group's
18509 // bottom/right mi does not start there. Comparing mi origins instead is
18510 // the same test only while the block's own origin is aligned to its
18511 // size, which a 4x4 luma block read at the `| 1` mi is not.
18512 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18513 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
18514 let (org_px, dim_mi) = if c.dir == 0 {
18515 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
18516 } else {
18517 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
18518 };
18519 let pu_edge = if c.chroma {
18520 let plane_dim = (dim_mi * MI / 2).max(4);
18521 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
18522 } else {
18523 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
18524 };
18525 if !pu_edge
18526 && cur_ref != 0
18527 && pv_ref != 0
18528 && n.skip_at(mi_r, mi_c)
18529 && n.skip_at(pv_mi_r, pv_mi_c)
18530 {
18531 return None;
18532 }
18533 let (cur_seg, pv_seg) = if c.seg_lf_active {
18534 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
18535 } else {
18536 (0, 0)
18537 };
18538 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
18539 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
18540 if cur_level == 0 && pv_level == 0 {
18541 return None;
18542 }
18543 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
18544 let len: u8 = if c.chroma {
18545 if dim == 0 { 4 } else { 6 }
18546 } else {
18547 [4, 8, 14, 14, 14][dim]
18548 };
18549 let level = if cur_level != 0 { cur_level } else { pv_level };
18550 hit!(DEBLOCK_HITS);
18551 Some((len, level))
18552}
18553
18554/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
18555fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
18556 let sharpness = i32::from(sharpness);
18557 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
18558 let mut lim = level >> shift;
18559 if sharpness > 0 {
18560 lim = lim.min(9 - sharpness);
18561 }
18562 lim = lim.max(1);
18563 (2 * (level + 2) + lim, lim, level >> 4)
18564}
18565
18566#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
18567fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
18568 // libaom's `signed_char_clamp_high`: the clamp range scales with
18569 // `128 << (bit_depth - 8)` alongside the centering constant below.
18570 let scale = 1i32 << (bit_depth(fctx) - 8);
18571 v.clamp(-128 * scale, 128 * scale - 1)
18572}
18573
18574fn round_pow2(v: i32, n: u32) -> i32 {
18575 (v + (1 << (n - 1))) >> n
18576}
18577
18578/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
18579/// fallback.
18580fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
18581 if !mask {
18582 return [p1, p0, q0, q1];
18583 }
18584 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
18585 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
18586 // this kernel's eight clamps, and this kernel runs per deblocked sample.
18587 // Same bound, resolved once.
18588 let scale = 1i32 << (bit_depth(fctx) - 8);
18589 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
18590 let centre = 128i32 * scale;
18591 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
18592 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
18593 let filter = sclamp(outer + 3 * (qs0 - ps0));
18594 let filter1 = sclamp(filter + 4) >> 3;
18595 let filter2 = sclamp(filter + 3) >> 3;
18596 let oq0 = sclamp(qs0 - filter1) + centre;
18597 let op0 = sclamp(ps0 + filter2) + centre;
18598 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
18599 let oq1 = sclamp(qs1 - tap) + centre;
18600 let op1 = sclamp(ps1 + tap) + centre;
18601 [op1, op0, oq0, oq1]
18602}
18603
18604/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
18605/// `filter4`'s narrow taps.
18606#[allow(clippy::too_many_arguments)]
18607fn filter6(
18608 mask: bool,
18609 thresh: i32,
18610 flat: bool,
18611 p2: i32,
18612 p1: i32,
18613 p0: i32,
18614 q0: i32,
18615 q1: i32,
18616 q2: i32, fctx: &crate::decode::FrameCtx,
18617) -> [i32; 4] {
18618 if flat && mask {
18619 [
18620 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
18621 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
18622 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
18623 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
18624 ]
18625 } else {
18626 filter4(mask, thresh, p1, p0, q0, q1, fctx)
18627 }
18628}
18629
18630/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
18631#[allow(clippy::too_many_arguments)]
18632fn filter8(
18633 mask: bool,
18634 thresh: i32,
18635 flat: bool,
18636 p3: i32,
18637 p2: i32,
18638 p1: i32,
18639 p0: i32,
18640 q0: i32,
18641 q1: i32,
18642 q2: i32,
18643 q3: i32, fctx: &crate::decode::FrameCtx,
18644) -> [i32; 6] {
18645 if flat && mask {
18646 [
18647 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
18648 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
18649 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
18650 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
18651 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
18652 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
18653 ]
18654 } else {
18655 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
18656 [p2, op1, op0, oq0, oq1, q2]
18657 }
18658}
18659
18660/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
18661/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
18662/// way -- they are only ever taps here, never written).
18663#[allow(clippy::too_many_arguments)]
18664fn filter14(
18665 mask: bool,
18666 thresh: i32,
18667 flat: bool,
18668 flat2: bool,
18669 p6: i32,
18670 p5: i32,
18671 p4: i32,
18672 p3: i32,
18673 p2: i32,
18674 p1: i32,
18675 p0: i32,
18676 q0: i32,
18677 q1: i32,
18678 q2: i32,
18679 q3: i32,
18680 q4: i32,
18681 q5: i32,
18682 q6: i32, fctx: &crate::decode::FrameCtx,
18683) -> [i32; 12] {
18684 if flat2 && flat && mask {
18685 [
18686 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
18687 round_pow2(
18688 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
18689 4,
18690 ),
18691 round_pow2(
18692 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
18693 4,
18694 ),
18695 round_pow2(
18696 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
18697 4,
18698 ),
18699 round_pow2(
18700 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
18701 4,
18702 ),
18703 round_pow2(
18704 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
18705 4,
18706 ),
18707 round_pow2(
18708 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
18709 4,
18710 ),
18711 round_pow2(
18712 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
18713 4,
18714 ),
18715 round_pow2(
18716 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
18717 4,
18718 ),
18719 round_pow2(
18720 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
18721 4,
18722 ),
18723 round_pow2(
18724 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
18725 4,
18726 ),
18727 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
18728 ]
18729 } else {
18730 let [op2, op1, op0, oq0, oq1, oq2] =
18731 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
18732 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
18733 }
18734}
18735
18736/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
18737/// the first (`q0`) sample past the edge, `outer_stride` advances to the
18738/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
18739/// the next along the edge's own filtering direction.
18740#[allow(clippy::too_many_arguments)]
18741fn filter_edge(
18742 data: &mut [u16],
18743 base: usize,
18744 outer_stride: isize,
18745 tap_stride: isize,
18746 len: u8,
18747 level: i32,
18748 sharpness: u8, fctx: &crate::decode::FrameCtx,
18749) {
18750 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
18751 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
18752 // every 8-bit threshold (including the flat masks' fixed `1`) is
18753 // compared against a raw pixel difference on the stream's own bit-depth
18754 // scale, so each is shifted left by `bit_depth - 8` before use.
18755 let shift = bit_depth(fctx) - 8;
18756 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
18757 let flat_thresh = 1i32 << shift;
18758 let smax = sample_max(fctx);
18759 for i in 0..4isize {
18760 let center = (base as isize + i * outer_stride) as usize;
18761 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
18762 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
18763 match len {
18764 4 => {
18765 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
18766 let mask = (p1 - p0).abs() <= limit
18767 && (q1 - q0).abs() <= limit
18768 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18769 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
18770 data[idx(-2)] = op1.clamp(0, smax) as u16;
18771 data[idx(-1)] = op0.clamp(0, smax) as u16;
18772 data[idx(0)] = oq0.clamp(0, smax) as u16;
18773 data[idx(1)] = oq1.clamp(0, smax) as u16;
18774 }
18775 6 => {
18776 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
18777 let mask = (p2 - p1).abs() <= limit
18778 && (p1 - p0).abs() <= limit
18779 && (q1 - q0).abs() <= limit
18780 && (q2 - q1).abs() <= limit
18781 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18782 let flat = (p1 - p0).abs() <= flat_thresh
18783 && (q1 - q0).abs() <= flat_thresh
18784 && (p2 - p0).abs() <= flat_thresh
18785 && (q2 - q0).abs() <= flat_thresh;
18786 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
18787 data[idx(-2)] = op1.clamp(0, smax) as u16;
18788 data[idx(-1)] = op0.clamp(0, smax) as u16;
18789 data[idx(0)] = oq0.clamp(0, smax) as u16;
18790 data[idx(1)] = oq1.clamp(0, smax) as u16;
18791 }
18792 8 => {
18793 let (p3, p2, p1, p0, q0, q1, q2, q3) =
18794 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
18795 let mask = (p3 - p2).abs() <= limit
18796 && (p2 - p1).abs() <= limit
18797 && (p1 - p0).abs() <= limit
18798 && (q1 - q0).abs() <= limit
18799 && (q2 - q1).abs() <= limit
18800 && (q3 - q2).abs() <= limit
18801 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18802 let flat = (p1 - p0).abs() <= flat_thresh
18803 && (q1 - q0).abs() <= flat_thresh
18804 && (p2 - p0).abs() <= flat_thresh
18805 && (q2 - q0).abs() <= flat_thresh
18806 && (p3 - p0).abs() <= flat_thresh
18807 && (q3 - q0).abs() <= flat_thresh;
18808 let [op2, op1, op0, oq0, oq1, oq2] =
18809 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
18810 data[idx(-3)] = op2.clamp(0, smax) as u16;
18811 data[idx(-2)] = op1.clamp(0, smax) as u16;
18812 data[idx(-1)] = op0.clamp(0, smax) as u16;
18813 data[idx(0)] = oq0.clamp(0, smax) as u16;
18814 data[idx(1)] = oq1.clamp(0, smax) as u16;
18815 data[idx(2)] = oq2.clamp(0, smax) as u16;
18816 }
18817 _ => {
18818 let (p6, p5, p4, p3, p2, p1, p0) =
18819 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
18820 let (q0, q1, q2, q3, q4, q5, q6) =
18821 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
18822 let mask = (p3 - p2).abs() <= limit
18823 && (p2 - p1).abs() <= limit
18824 && (p1 - p0).abs() <= limit
18825 && (q1 - q0).abs() <= limit
18826 && (q2 - q1).abs() <= limit
18827 && (q3 - q2).abs() <= limit
18828 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
18829 let flat = (p1 - p0).abs() <= flat_thresh
18830 && (q1 - q0).abs() <= flat_thresh
18831 && (p2 - p0).abs() <= flat_thresh
18832 && (q2 - q0).abs() <= flat_thresh
18833 && (p3 - p0).abs() <= flat_thresh
18834 && (q3 - q0).abs() <= flat_thresh;
18835 let flat2 = (p4 - p0).abs() <= flat_thresh
18836 && (q4 - q0).abs() <= flat_thresh
18837 && (p5 - p0).abs() <= flat_thresh
18838 && (q5 - q0).abs() <= flat_thresh
18839 && (p6 - p0).abs() <= flat_thresh
18840 && (q6 - q0).abs() <= flat_thresh;
18841 let out = filter14(
18842 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
18843 q6, fctx,
18844 );
18845 for (k, v) in (-6..=5isize).zip(out) {
18846 data[idx(k)] = v.clamp(0, smax) as u16;
18847 }
18848 }
18849 }
18850 }
18851}
18852
18853/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
18854/// 4K decode's self time, spent almost entirely on the per-tap strided
18855/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
18856/// arithmetic). Nothing here is spec logic: the same masks, the same
18857/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
18858/// rounding, done for 16 edge lines at once.
18859///
18860/// 16-bit lanes are exact for every value these filters see. Samples are in
18861/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
18862/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
18863/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
18864/// wide kernels' weights each total 8 or 16, so their sums (at most
18865/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
18866/// rounding shift, which is the unsigned shift the scalar's non-negative sum
18867/// takes.
18868#[cfg(target_arch = "x86_64")]
18869#[allow(unsafe_code)]
18870#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
18871mod deblock_simd {
18872 use std::arch::x86_64::*;
18873
18874 /// `a <= b` lane-wise, as a full-width mask.
18875 ///
18876 /// # Safety
18877 /// Requires AVX2.
18878 #[target_feature(enable = "avx2")]
18879 #[inline]
18880 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
18881 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
18882 }
18883
18884 /// `|a - b|` lane-wise.
18885 ///
18886 /// # Safety
18887 /// Requires AVX2.
18888 #[target_feature(enable = "avx2")]
18889 #[inline]
18890 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
18891 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
18892 }
18893
18894 /// `signed_char_clamp_high`, lane-wise.
18895 ///
18896 /// # Safety
18897 /// Requires AVX2.
18898 #[target_feature(enable = "avx2")]
18899 #[inline]
18900 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
18901 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
18902 }
18903
18904 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
18905 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
18906 ///
18907 /// # Safety
18908 /// Requires AVX2.
18909 #[target_feature(enable = "avx2")]
18910 unsafe fn transpose16(t: &mut [__m256i; 16]) {
18911 let mut a = [_mm256_setzero_si256(); 16];
18912 for k in 0..8 {
18913 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
18914 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
18915 }
18916 let mut b = [_mm256_setzero_si256(); 16];
18917 for g in 0..4 {
18918 let s = 4 * g;
18919 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
18920 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
18921 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
18922 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
18923 }
18924 let mut c = [_mm256_setzero_si256(); 16];
18925 for g in 0..2 {
18926 let s = 8 * g;
18927 for j in 0..4 {
18928 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
18929 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
18930 }
18931 }
18932 for i in 0..8 {
18933 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
18934 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
18935 }
18936 }
18937
18938 /// The wide kernels' tap weights, in tap order and with the spec's
18939 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
18940 /// over `p3..q3`, `filter14` over `p6..q6`.
18941 const W6: [[i16; 6]; 4] = [
18942 [3, 2, 2, 1, 0, 0],
18943 [1, 2, 2, 2, 1, 0],
18944 [0, 1, 2, 2, 2, 1],
18945 [0, 0, 1, 2, 2, 3],
18946 ];
18947 const W8: [[i16; 8]; 6] = [
18948 [3, 2, 1, 1, 1, 0, 0, 0],
18949 [2, 1, 2, 1, 1, 1, 0, 0],
18950 [1, 1, 1, 2, 1, 1, 1, 0],
18951 [0, 1, 1, 1, 2, 1, 1, 1],
18952 [0, 0, 1, 1, 1, 2, 1, 2],
18953 [0, 0, 0, 1, 1, 1, 2, 3],
18954 ];
18955 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
18956 const W14: [[i16; 14]; 12] = [
18957 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
18958 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
18959 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
18960 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
18961 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
18962 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
18963 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
18964 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
18965 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
18966 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
18967 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
18968 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
18969 ];
18970
18971 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
18972 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
18973 /// below `1 << 16`, so the logical shift is the arithmetic one.
18974 ///
18975 /// # Safety
18976 /// Requires AVX2.
18977 ///
18978 /// lane-deblock: the tap count, the weights and the shift are all const
18979 /// here (they were slice parameters, which left the weight `match` as a
18980 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
18981 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
18982 #[target_feature(enable = "avx2")]
18983 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
18984 unsafe fn wsum<const N: usize, const SHIFT: i32>(
18985 taps: &[__m256i; N],
18986 w: &[i16; N],
18987 ) -> __m256i {
18988 let mut s = _mm256_setzero_si256();
18989 for i in 0..N {
18990 match w[i] {
18991 0 => {}
18992 1 => s = _mm256_add_epi16(s, taps[i]),
18993 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
18994 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
18995 }
18996 }
18997 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
18998 if SHIFT == 3 {
18999 _mm256_srli_epi16(s, 3)
19000 } else {
19001 _mm256_srli_epi16(s, 4)
19002 }
19003 }
19004
19005 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
19006 /// `t[8]`; the filtered taps are written back in place. Returns `false`
19007 /// when the filter mask is empty on every one of the 16 lines -- nothing
19008 /// was written and the caller can skip the whole write-back.
19009 ///
19010 /// # Safety
19011 /// Requires AVX2.
19012 ///
19013 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
19014 /// its own kernel holding only its own taps, and every wide row is
19015 /// clamped straight into `t` instead of into a shared twelve-entry
19016 /// result array (which the register allocator spilled -- 35% of this
19017 /// kernel's samples were `vmovdqa` to the stack).
19018 #[target_feature(enable = "avx2")]
19019 #[allow(clippy::too_many_arguments)]
19020 unsafe fn filter16<const LEN: u8>(
19021 t: &mut [__m256i; 16],
19022 blimit: i32,
19023 limit: i32,
19024 hev_thr: i32,
19025 flat_thresh: i32,
19026 scale: i32,
19027 smax: i32,
19028 ) -> bool {
19029 let lim = _mm256_set1_epi16(limit as i16);
19030 let blim = _mm256_set1_epi16(blimit as i16);
19031 let hthr = _mm256_set1_epi16(hev_thr as i16);
19032 let fthr = _mm256_set1_epi16(flat_thresh as i16);
19033 let zero = _mm256_setzero_si256();
19034 let smaxv = _mm256_set1_epi16(smax as i16);
19035 macro_rules! put {
19036 ($i:expr, $v:expr) => {
19037 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
19038 };
19039 }
19040 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
19041 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
19042
19043 // `highbd_filter_mask`: the neighbour steps this kernel's length
19044 // reaches, plus the shared `blimit` term.
19045 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
19046 let mut md = d1;
19047 if LEN >= 6 {
19048 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
19049 }
19050 if LEN >= 8 {
19051 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
19052 }
19053 let bl = _mm256_add_epi16(
19054 _mm256_slli_epi16(ad(p0, q0), 1),
19055 _mm256_srli_epi16(ad(p1, q1), 1),
19056 );
19057 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
19058 // lane-deblock2: an empty mask leaves every tap at its loaded value
19059 // (the flat masks are `& mask`, so they are empty too, and the final
19060 // clamp is the identity on samples that came out of the plane), so
19061 // the whole write-back -- including the vertical edge's second
19062 // transpose -- is dead.
19063 if _mm256_testz_si256(mask, mask) != 0 {
19064 return false;
19065 }
19066 let hev = _mm256_cmpgt_epi16(d1, hthr);
19067
19068 // `filter4`, in the centred domain.
19069 let centre = _mm256_set1_epi16((128 * scale) as i16);
19070 let lo = _mm256_set1_epi16((-128 * scale) as i16);
19071 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
19072 let ps1 = _mm256_sub_epi16(p1, centre);
19073 let ps0 = _mm256_sub_epi16(p0, centre);
19074 let qs0 = _mm256_sub_epi16(q0, centre);
19075 let qs1 = _mm256_sub_epi16(q1, centre);
19076 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
19077 let f = sclamp(
19078 _mm256_add_epi16(
19079 outer,
19080 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
19081 ),
19082 lo,
19083 hi,
19084 );
19085 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
19086 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
19087 let tap = _mm256_andnot_si256(
19088 hev,
19089 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
19090 );
19091 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
19092 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
19093 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
19094 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
19095 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
19096 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
19097 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
19098 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
19099 if LEN == 4 {
19100 put!(6, b_p1);
19101 put!(7, b_p0);
19102 put!(8, b_q0);
19103 put!(9, b_q1);
19104 return true;
19105 }
19106
19107 // `highbd_flat_mask4`, over the same reach as this length's mask.
19108 let mut fl = _mm256_max_epi16(
19109 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
19110 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
19111 );
19112 if LEN >= 8 {
19113 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
19114 }
19115 let flat = _mm256_and_si256(le(fl, fthr), mask);
19116 let any_flat = _mm256_testz_si256(flat, flat) == 0;
19117 if LEN == 6 {
19118 if any_flat {
19119 let taps = [p2, p1, p0, q0, q1, q2];
19120 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
19121 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
19122 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
19123 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
19124 } else {
19125 put!(6, b_p1);
19126 put!(7, b_p0);
19127 put!(8, b_q0);
19128 put!(9, b_q1);
19129 }
19130 return true;
19131 }
19132
19133 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
19134 let (o0, o1, o2, o3, o4, o5) = if any_flat {
19135 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
19136 (
19137 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
19138 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
19139 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
19140 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
19141 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
19142 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
19143 )
19144 } else {
19145 (p2, b_p1, b_p0, b_q0, b_q1, q2)
19146 };
19147 macro_rules! put8 {
19148 () => {
19149 put!(5, o0);
19150 put!(6, o1);
19151 put!(7, o2);
19152 put!(8, o3);
19153 put!(9, o4);
19154 put!(10, o5);
19155 };
19156 }
19157 if LEN == 8 {
19158 put8!();
19159 return true;
19160 }
19161
19162 let fl2 = _mm256_max_epi16(
19163 _mm256_max_epi16(
19164 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
19165 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
19166 ),
19167 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
19168 );
19169 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
19170 if _mm256_testz_si256(flat2, flat2) != 0 {
19171 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
19172 // taps they were loaded with, exactly as the blend would.
19173 put8!();
19174 return true;
19175 }
19176 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
19177 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
19178 // j is a constant vector with two negative and two positive
19179 // entries), so each output costs one add, one sub and the rounding
19180 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
19181 // become 44. Exact: every partial sum is taken mod 2^16 by
19182 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
19183 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
19184 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
19185 // it against `filter_edge` at 8/10/12-bit.
19186 let mut s = _mm256_add_epi16(
19187 _mm256_add_epi16(
19188 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
19189 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
19190 ),
19191 _mm256_add_epi16(
19192 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
19193 q0,
19194 ),
19195 );
19196 let add2 = |a, b| _mm256_add_epi16(a, b);
19197 macro_rules! row14 {
19198 ($idx:literal, $base:expr) => {
19199 put!(
19200 $idx,
19201 _mm256_blendv_epi8(
19202 $base,
19203 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
19204 flat2,
19205 )
19206 );
19207 };
19208 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
19209 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
19210 row14!($idx, $base);
19211 };
19212 }
19213 row14!(2, p5);
19214 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
19215 row14!(4, p3, add2(p2, q2), add2(p6, p5));
19216 row14!(5, o0, add2(p1, q3), add2(p6, p4));
19217 row14!(6, o1, add2(p0, q4), add2(p6, p3));
19218 row14!(7, o2, add2(q0, q5), add2(p6, p2));
19219 row14!(8, o3, add2(q1, q6), add2(p6, p1));
19220 row14!(9, o4, add2(q2, q6), add2(p5, p0));
19221 row14!(10, o5, add2(q3, q6), add2(p4, q0));
19222 row14!(11, q3, add2(q4, q6), add2(p3, q1));
19223 row14!(12, q4, add2(q5, q6), add2(p2, q2));
19224 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
19225 true
19226 }
19227
19228 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
19229 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
19230 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
19231 /// consecutive columns with each tap a whole row segment.
19232 ///
19233 /// # Safety
19234 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
19235 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
19236 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
19237 /// must be inside it.
19238 #[target_feature(enable = "avx2")]
19239 #[allow(clippy::too_many_arguments)]
19240 pub unsafe fn edge16(
19241 data: &mut [u16],
19242 base: usize,
19243 stride: usize,
19244 vertical: bool,
19245 len: u8,
19246 blimit: i32,
19247 limit: i32,
19248 hev_thr: i32,
19249 flat_thresh: i32,
19250 scale: i32,
19251 smax: i32,
19252 ) {
19253 let p = data.as_mut_ptr();
19254 let mut t = [_mm256_setzero_si256(); 16];
19255 // The taps this length reads, as `t` indices.
19256 let (lo, hi) = match len {
19257 4 => (6, 10),
19258 6 => (5, 11),
19259 8 => (4, 12),
19260 _ => (1, 15),
19261 };
19262 if vertical {
19263 for j in 0..16 {
19264 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
19265 }
19266 transpose16(&mut t);
19267 } else {
19268 let top = base - 8 * stride;
19269 for i in lo..hi {
19270 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
19271 }
19272 }
19273 // lane-deblock2: one monomorphised kernel per edge length, and an
19274 // empty filter mask returns without any write-back at all.
19275 let modified = match len {
19276 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19277 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19278 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19279 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19280 };
19281 if !modified {
19282 return;
19283 }
19284 if vertical {
19285 transpose16(&mut t);
19286 for j in 0..16 {
19287 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
19288 }
19289 } else {
19290 let top = base - 8 * stride;
19291 let (a, b) = match len {
19292 4 | 6 => (6, 10),
19293 8 => (5, 11),
19294 _ => (2, 14),
19295 };
19296 for i in a..b {
19297 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
19298 }
19299 }
19300 }
19301}
19302
19303/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
19304/// output. Returns `false` when this build or CPU has no kernel, leaving the
19305/// caller on the scalar path.
19306#[allow(unused_variables)]
19307fn filter_edge16(
19308 data: &mut [u16],
19309 base: usize,
19310 stride: usize,
19311 vertical: bool,
19312 len: u8,
19313 level: i32,
19314 sharpness: u8, fctx: &crate::decode::FrameCtx,
19315) -> bool {
19316 #[cfg(target_arch = "x86_64")]
19317 {
19318 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
19319 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19320 let shift = bit_depth(fctx) - 8;
19321 // SAFETY: the avx2 arm is reached only when the CPU reports it,
19322 // and `deblock_plane` checks the kernel's edge bounds.
19323 #[allow(unsafe_code)]
19324 unsafe {
19325 deblock_simd::edge16(
19326 data,
19327 base,
19328 stride,
19329 vertical,
19330 len,
19331 blimit << shift,
19332 limit << shift,
19333 hev_thr << shift,
19334 1 << shift,
19335 1 << shift,
19336 sample_max(fctx),
19337 )
19338 };
19339 return true;
19340 }
19341 }
19342 false
19343}
19344
19345/// One plane's worth of spec 7.14: every vertical edge across the plane,
19346/// then every horizontal edge (the order the spec and libaom both use).
19347fn deblock_plane(
19348 plane: &mut PlaneBuf<'static>,
19349 plane_idx: usize,
19350 lf: &LoopFilterParams,
19351 n: &Neighbours,
19352 frame_width: usize,
19353 frame_height: usize, fctx: &crate::decode::FrameCtx,
19354) {
19355 // spec 7.14's order: this plane's whole vertical pass, then its whole
19356 // horizontal one. lane-pipefilt split the two into one row-ranged
19357 // function so the per-superblock-row pipeline can run them a band at a
19358 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
19359 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
19360 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
19361}
19362
19363/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
19364/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
19365///
19366/// A row span is a legal cut of either pass because a band boundary is a
19367/// multiple of 16 rows and every edge's kernel stays inside its own
19368/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
19369/// what keep the two passes in spec order across bands.
19370#[allow(clippy::too_many_arguments)]
19371fn deblock_plane_span(
19372 plane: &mut PlaneBuf<'static>,
19373 plane_idx: usize,
19374 lf: &LoopFilterParams,
19375 n: &Neighbours,
19376 frame_width: usize,
19377 frame_height: usize,
19378 span_lo: usize,
19379 span_hi: usize,
19380 horz: bool,
19381 fctx: &crate::decode::FrameCtx,
19382) {
19383 let chroma = plane_idx != 0;
19384 // r7: libaom clips the deblock loop to the CODED frame's own
19385 // width/height, not the mi-aligned `true_width`/`true_height` margin
19386 // (the padding up to the next 8-pixel/superblock boundary that
19387 // reconstruction still fills in but the loop filter never visits).
19388 // Confirmed against the superres gate: with the margin included, the
19389 // last coded mi column's horizontal edges were filtered when libaom's
19390 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
19391 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
19392 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
19393 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
19394 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
19395 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
19396 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
19397 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
19398 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
19399 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
19400 // all in columns 64..67; frame 0 survived because that edge carried no
19401 // filter level there). r7's superres measurement is preserved: its frame
19402 // was already 8-aligned, so this bound equals `frame_width` there and
19403 // still excludes the superblock padding up to `true_width`.
19404 let (cw, ch) = if chroma {
19405 (frame_width.div_ceil(2), frame_height.div_ceil(2))
19406 } else {
19407 (frame_width, frame_height)
19408 };
19409 let (tw, th, stride) = (
19410 plane.true_width.min(cw),
19411 plane.true_height.min(ch),
19412 plane.width,
19413 );
19414 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
19415 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
19416 }
19417 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
19418 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
19419 // kernel. The swap is order-preserving: a filtered group overlaps only
19420 // groups along the edge it sits on -- the vertical pass's writes at
19421 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
19422 // dependence is on ascending `x0` within a row, which stays the outer
19423 // loop's order, and rows remain independent (horizontal pass mirrored).
19424 let rows = plane.data.len() / stride.max(1);
19425 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
19426 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
19427 // bands along the axis whose writes are disjoint. A vertical edge's
19428 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
19429 // row bands never touch each other; a horizontal edge's groups write rows
19430 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
19431 // read the mode-info grids immutably. The grouping a band starts with is
19432 // free: every 4-row (4-column) group's output is a pure function of that
19433 // group, whether it goes through `filter_edge16` with three neighbours or
19434 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
19435 // group ever straddles one.
19436 // lane-perf10 merge: the output plane is owned (perf10 made mutable
19437 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
19438 // the bands below never clone it concurrently.
19439 plane.data.to_mut();
19440 let threads = crate::par::filter_threads();
19441 let sp = crate::par::Shared::new(plane);
19442 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
19443 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
19444 Vec::new()
19445 } else {
19446 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
19447 .into_iter()
19448 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
19449 .collect()
19450 };
19451 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
19452 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
19453 // no other band touches (see `Shared`'s own corner-cut note).
19454 #[allow(unsafe_code)]
19455 let plane = unsafe { sp.get() };
19456 // lane-deblock2: this band's own level table and pass constants,
19457 // built once per band instead of re-derived per 4-pixel edge.
19458 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
19459 let mut x0 = 4usize;
19460 while x0 < tw {
19461 let mut y0 = y_lo;
19462 while y0 < y_hi {
19463 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
19464 let ps: [Option<(u8, i32)>; 4] =
19465 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
19466 if let Some((len, level)) = ps[0] {
19467 if ps.iter().all(|p| *p == ps[0])
19468 && filter_edge16(
19469 plane.data.to_mut(),
19470 y0 * stride + x0,
19471 stride,
19472 true,
19473 len,
19474 level,
19475 lf.sharpness, fctx,
19476 )
19477 {
19478 y0 += 16;
19479 continue;
19480 }
19481 }
19482 for (k, p) in ps.iter().enumerate() {
19483 if let Some((len, level)) = *p {
19484 filter_edge(
19485 plane.data.to_mut(),
19486 (y0 + 4 * k) * stride + x0,
19487 stride as isize,
19488 1,
19489 len,
19490 level,
19491 lf.sharpness, fctx,
19492 );
19493 }
19494 }
19495 y0 += 16;
19496 continue;
19497 }
19498 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
19499 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
19500 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
19501 }
19502 filter_edge(
19503 plane.data.to_mut(),
19504 y0 * stride + x0,
19505 stride as isize,
19506 1,
19507 len,
19508 level,
19509 lf.sharpness, fctx,
19510 );
19511 }
19512 y0 += 4;
19513 }
19514 x0 += 4;
19515 }
19516 });
19517 // The horizontal pass runs only after the WHOLE vertical pass of this
19518 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
19519 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
19520 Vec::new()
19521 } else {
19522 crate::par::bands(tw.div_ceil(16), threads)
19523 .into_iter()
19524 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19525 .collect()
19526 };
19527 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
19528 // SAFETY: this band writes only columns `x_lo..x_hi`.
19529 #[allow(unsafe_code)]
19530 let plane = unsafe { sp.get() };
19531 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
19532 let mut y0 = sp_lo.max(4);
19533 while y0 < sp_hi {
19534 let mut x0 = x_lo;
19535 while x0 < x_hi {
19536 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
19537 let ps: [Option<(u8, i32)>; 4] =
19538 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
19539 if let Some((len, level)) = ps[0] {
19540 if ps.iter().all(|p| *p == ps[0])
19541 && filter_edge16(
19542 plane.data.to_mut(),
19543 y0 * stride + x0,
19544 stride,
19545 false,
19546 len,
19547 level,
19548 lf.sharpness, fctx,
19549 )
19550 {
19551 x0 += 16;
19552 continue;
19553 }
19554 }
19555 for (k, p) in ps.iter().enumerate() {
19556 if let Some((len, level)) = *p {
19557 filter_edge(
19558 plane.data.to_mut(),
19559 y0 * stride + x0 + 4 * k,
19560 1,
19561 stride as isize,
19562 len,
19563 level,
19564 lf.sharpness, fctx,
19565 );
19566 }
19567 }
19568 x0 += 16;
19569 continue;
19570 }
19571 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
19572 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
19573 && plane_idx == 0
19574 && x0 == 44
19575 {
19576 eprintln!(
19577 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
19578 lf.sharpness
19579 );
19580 }
19581 filter_edge(
19582 plane.data.to_mut(),
19583 y0 * stride + x0,
19584 1,
19585 stride as isize,
19586 len,
19587 level,
19588 lf.sharpness, fctx,
19589 );
19590 }
19591 x0 += 4;
19592 }
19593 y0 += 4;
19594 } });
19595}
19596
19597/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
19598/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
19599/// restoration is active, and a fresh LR destination per plane -- freshly
19600/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
19601/// sample written also takes a first-touch page fault. The buffers are handed
19602/// back here instead and refilled in place.
19603///
19604/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
19605/// stay on one thread: the frame thread allocates the snapshots and a filter
19606/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
19607/// into the pool from whichever worker ran it), so a per-thread pool leaked
19608/// whole-plane buffers into every worker it touched -- 19 MB a set, times
19609/// every pool thread the decode ever created. One shared pool with a hard
19610/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
19611/// many threads cycle through it; anything over the cap is freed.
19612static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
19613
19614/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
19615/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
19616/// flight cycle through far fewer.
19617const SCRATCH_CAP: usize = 32;
19618
19619/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
19620/// CAPACITY so a chroma-sized request does not permanently promote a
19621/// luma-sized allocation (every pooled buffer would drift to the largest
19622/// size otherwise). `None` when the pool is empty.
19623fn scratch_take(n: usize) -> Option<Vec<u16>> {
19624 let mut p = PLANE_SCRATCH.lock().unwrap();
19625 if p.is_empty() {
19626 return None;
19627 }
19628 let fit = p
19629 .iter()
19630 .enumerate()
19631 .filter(|(_, v)| v.capacity() >= n)
19632 .min_by_key(|(_, v)| v.capacity())
19633 .map(|(i, _)| i);
19634 let i = match fit {
19635 Some(i) => i,
19636 // Nothing big enough: grow the largest rather than a small one.
19637 None => p
19638 .iter()
19639 .enumerate()
19640 .max_by_key(|(_, v)| v.capacity())
19641 .map(|(i, _)| i)
19642 .expect("the pool is not empty"),
19643 };
19644 Some(p.swap_remove(i))
19645}
19646
19647/// A pooled buffer holding a copy of `src`.
19648fn scratch_from(src: &[u16]) -> Vec<u16> {
19649 let mut v = scratch_take(src.len()).unwrap_or_default();
19650 v.clear();
19651 v.extend_from_slice(src);
19652 v
19653}
19654
19655/// An empty pooled buffer, for a caller that fills it itself.
19656fn scratch_empty() -> Vec<u16> {
19657 let mut v = scratch_take(0).unwrap_or_default();
19658 v.clear();
19659 v
19660}
19661
19662/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
19663/// for a caller that writes every element it later reads (lane-copy: the
19664/// post-deblock snapshot writes 4 rows in 64 and reads no other).
19665fn scratch_sized(n: usize) -> Vec<u16> {
19666 let mut v = scratch_take(n).unwrap_or_default();
19667 if v.len() > n {
19668 v.truncate(n);
19669 } else if v.len() < n {
19670 v.resize(n, 0);
19671 }
19672 v
19673}
19674
19675/// A plane's post-deblock snapshot, its samples taken from the pool (every
19676/// other field is `usize`).
19677///
19678/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
19679/// boundary substitution reads the post-deblock plane at just four rows
19680/// around each interior stripe boundary (`row` outside
19681/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
19682/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
19683/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
19684/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
19685/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
19686/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
19687/// the pooled buffer keeps whatever a previous frame left there -- an
19688/// initialised value that no reader ever reaches.
19689fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
19690 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
19691}
19692
19693fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
19694 let mut data = scratch_sized(p.data.len());
19695 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
19696 let stripe_h = 64usize >> ss_y;
19697 let offset = 8usize >> ss_y;
19698 let mut b = stripe_h - offset;
19699 while b < rows {
19700 let (lo, hi) = (b - 2, (b + 2).min(rows));
19701 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
19702 b += stripe_h;
19703 }
19704 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
19705}
19706
19707/// The pre-filter reconstruction of one coded frame, plus the per-block state
19708/// the loop filters read.
19709///
19710/// The encoder's filter search ([`crate::filter_search::pick_filters`])
19711/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
19712/// sets to score each one, and the entropy decode and reconstruction it
19713/// repeats are identical every time -- both filters run after it, on the
19714/// finished planes. That re-parse was 24% of the encoder's profile. A caller
19715/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
19716/// alone through [`replay_filters`]; the result is the same picture the full
19717/// decode would have returned, because it is the same two calls on a copy of
19718/// the same planes.
19719pub(crate) struct FilterReplay {
19720 y: PlaneBuf<'static>,
19721 u: PlaneBuf<'static>,
19722 v: PlaneBuf<'static>,
19723 neighbours: Neighbours,
19724 frame_width: usize,
19725 frame_height: usize,
19726 width: usize,
19727 height: usize,
19728 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
19729 /// stash the cropped return path leaves behind.
19730 true_width: usize,
19731 true_height: usize,
19732 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
19733 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
19734 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
19735 /// 1080p frame's wall in allocation, not in filtering. Recycled here
19736 /// instead; the pool holds at most the six planes one candidate has live.
19737 scratch: Vec<Vec<u16>>,
19738 /// The last deblocked planes and the levels that produced them.
19739 /// Deblocking depends on nothing else the search moves, and the search
19740 /// fixes the levels before it walks the CDEF strengths, so every
19741 /// candidate after the first of a level pair replays CDEF alone.
19742 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19743}
19744
19745thread_local! {
19746 /// Set by [`arm_filter_replay`] for the span of one decode.
19747 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
19748 /// What that decode captured, until [`clear_filter_replay`].
19749 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
19750 const { std::cell::RefCell::new(None) };
19751}
19752
19753/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
19754pub(crate) fn arm_filter_replay() {
19755 REPLAY_ARMED.set(true);
19756}
19757
19758/// Test-only: force every filter candidate through a full decode, so a gate
19759/// can hold the replay against the decode it stands in for
19760/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
19761#[cfg(test)]
19762static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
19763
19764#[cfg(test)]
19765pub(crate) fn set_filter_replay_disabled(off: bool) {
19766 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
19767}
19768
19769/// Drop the armed flag and anything captured: the tile it belongs to is done.
19770pub(crate) fn clear_filter_replay() {
19771 REPLAY_ARMED.set(false);
19772 REPLAY.with_borrow_mut(|r| *r = None);
19773}
19774
19775/// The capture itself, called from the decoder's own pre-filter point. Owns
19776/// copies of the planes, since the caller filters them in place.
19777fn capture_filter_replay(
19778 y: &PlaneBuf<'_>,
19779 u: &PlaneBuf<'_>,
19780 v: &PlaneBuf<'_>,
19781 neighbours: &Neighbours,
19782 frame_width: usize,
19783 frame_height: usize,
19784 width: usize,
19785 height: usize,
19786 true_width: usize,
19787 true_height: usize,
19788) {
19789 if !REPLAY_ARMED.replace(false) {
19790 return;
19791 }
19792 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
19793 REPLAY.with_borrow_mut(|slot| {
19794 *slot = Some(FilterReplay {
19795 y: own(y),
19796 u: own(u),
19797 v: own(v),
19798 neighbours: neighbours.clone(),
19799 frame_width,
19800 frame_height,
19801 width,
19802 height,
19803 true_width,
19804 true_height,
19805 scratch: Vec::new(),
19806 deblocked: None,
19807 });
19808 });
19809}
19810
19811/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
19812/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
19813/// allocator and the page fault handler out of the filter search.
19814fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
19815 let mut buf = scratch.pop().unwrap_or_default();
19816 let src: &[u16] = &p.data;
19817 let threads = crate::par::filter_threads();
19818 if buf.len() != src.len() || threads <= 1 {
19819 buf.clear();
19820 buf.extend_from_slice(src);
19821 } else {
19822 // A recycled buffer is already the right length, so the copy is a
19823 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
19824 // candidate is memory bandwidth, not arithmetic, and the halves are
19825 // disjoint `&mut` slices (no `par::Shared` needed).
19826 let per = src.len().div_ceil(threads);
19827 let batch = crate::par::Batch::new("ec-av1-filter");
19828 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
19829 batch.submit(move || dst.copy_from_slice(src));
19830 }
19831 }
19832 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
19833}
19834
19835/// The filter half of a captured decode, under new parameters: exactly the
19836/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
19837/// copy of the captured planes. `None` when nothing is captured (the caller
19838/// then decodes for real).
19839pub(crate) fn replay_filters(
19840 loop_filter: &LoopFilterParams,
19841 cdef: &CdefParams,
19842 fctx: &FrameCtx,
19843) -> Option<Picture> {
19844 #[cfg(test)]
19845 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
19846 return None;
19847 }
19848 REPLAY.with_borrow_mut(|slot| {
19849 let r = slot.as_mut()?;
19850 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
19851 let cpt = crate::par::timer(crate::par::S_COPY);
19852 let (mut y, mut u, mut v) = if hit {
19853 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
19854 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
19855 (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch))
19856 } else {
19857 // The levels moved, so the cached deblocked planes are dead:
19858 // their buffers are this candidate's working copies.
19859 if let Some((_, dy, du, dv)) = r.deblocked.take() {
19860 r.scratch.push(dy.data.into_owned());
19861 r.scratch.push(du.data.into_owned());
19862 r.scratch.push(dv.data.into_owned());
19863 }
19864 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
19865 let (mut y, mut u, mut v) =
19866 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
19867 let _t = crate::par::timer(crate::par::S_DEBLOCK);
19868 apply_deblock(
19869 &mut y,
19870 &mut u,
19871 &mut v,
19872 loop_filter,
19873 &r.neighbours,
19874 r.frame_width,
19875 r.frame_height,
19876 fctx,
19877 );
19878 let scratch = &mut r.scratch;
19879 r.deblocked =
19880 Some((*loop_filter, pooled(&y, scratch), pooled(&u, scratch), pooled(&v, scratch)));
19881 (y, u, v)
19882 };
19883 drop(cpt);
19884 let ct = crate::par::timer(crate::par::S_CDEF);
19885 apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
19886 drop(ct);
19887 // The capture only happens on the shape whose tail is the two
19888 // filter calls and the crop (no superres, no loop restoration), so
19889 // what is left is that crop -- byte for byte the cropped return path
19890 // of the decode this replaces, wide-margin stash included.
19891 //
19892 // lane-av1fpar: the crop is why this arm exists at all. The capture
19893 // used to demand `frame == plane` dimensions, which no editor size
19894 // meets (1080 and 1608 both pad to a superblock row), so every
19895 // candidate of every frame at those sizes fell through to a full
19896 // re-decode -- 57% of a 1080p frame's wall.
19897 let (fw, fh) = (r.frame_width, r.frame_height);
19898 if fw == r.width && fh == r.height {
19899 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
19900 return Some(Picture {
19901 width: r.width,
19902 height: r.height,
19903 y: y.data.into_owned(),
19904 u: u.data.into_owned(),
19905 v: v.data.into_owned(),
19906 });
19907 }
19908 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
19909 let mut out = Vec::with_capacity(w * h);
19910 for row in 0..h {
19911 out.extend(plane.data[row * plane.width..][..w].iter().copied());
19912 }
19913 out
19914 };
19915 let (tw, th) = (r.true_width, r.true_height);
19916 fctx.last_frame_wide_margin.with(|m| {
19917 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
19918 width: tw,
19919 height: th,
19920 y: crop(&y, tw, th),
19921 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
19922 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
19923 });
19924 });
19925 let out = Picture {
19926 width: fw,
19927 height: fh,
19928 y: crop(&y, fw, fh),
19929 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19930 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19931 };
19932 // The working planes outlive the crop, so they go back to the pool.
19933 for plane in [y, u, v] {
19934 if r.scratch.len() < 6 {
19935 r.scratch.push(plane.data.into_owned());
19936 }
19937 }
19938 Some(out)
19939 })
19940}
19941
19942/// The output crop, taking the plane by value: a frame whose width is
19943/// already superblock-aligned (only its height is padded) has a padded
19944/// buffer whose stride equals the visible width, so the crop is a pure
19945/// truncation of the buffer we already own -- no full-plane copy at all
19946/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
19947/// serial tail). Any other shape falls back to the row-by-row copy.
19948fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
19949 let stride = plane.width;
19950 let mut data = plane.data.into_owned();
19951 if stride == w {
19952 data.truncate(w * h);
19953 return data;
19954 }
19955 let mut out = Vec::with_capacity(w * h);
19956 for row in 0..h {
19957 out.extend(data[row * stride..][..w].iter().copied());
19958 }
19959 out
19960}
19961
19962/// Hands a buffer back to the pool; the capacity is what is worth keeping.
19963/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
19964/// what keeps a pool shared by every thread from being an unbounded stash.
19965fn scratch_return(v: Vec<u16>) {
19966 let mut p = PLANE_SCRATCH.lock().unwrap();
19967 if p.len() < SCRATCH_CAP {
19968 p.push(v);
19969 }
19970}
19971
19972/// One CDEF mi-row band, as a real function rather than the body of the
19973/// `run_bands` closure: inside the closure the destination planes are
19974/// `&mut` references derived from a `par::Shared` raw pointer in the same
19975/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
19976/// re-loads through them on every tap. Reference parameters restore `noalias`
19977/// (lane-perf11 (a): -x% instructions at one filter thread).
19978#[allow(clippy::too_many_arguments)]
19979fn cdef_band(
19980 r_lo: usize,
19981 r_hi: usize,
19982 y: &mut PlaneBuf<'static>,
19983 u: &mut PlaneBuf<'static>,
19984 v: &mut PlaneBuf<'static>,
19985 src_y: &[u16],
19986 src_u: &[u16],
19987 src_v: &[u16],
19988 cdef: &CdefParams,
19989 skip_grid: &Neighbours,
19990 idx_grid: &[u8],
19991 sb_cols: usize,
19992 coeff_shift: i32,
19993 damping: i32,
19994 damping_uv: i32,
19995 (frame_w, frame_h): (usize, usize),
19996 fctx: &crate::decode::FrameCtx,
19997) {
19998 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
19999 if sb_cols == 0 {
20000 return 0;
20001 }
20002 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
20003 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
20004 };
20005 // One scratch window per plane kind, reused by every unit (8x8 luma and
20006 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
20007 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
20008 // AVX2 kernel taps the window in place with two-row loads that reach
20009 // past the last sample, and the tail stays zero for every unit.
20010 let mut win_y = [0i16; 256];
20011 let mut win_uv = [0i16; 256];
20012 let mut mi_r = r_lo;
20013 while mi_r < r_hi {
20014 let mut mi_c = 0usize;
20015 while mi_c < skip_grid.mi_cols {
20016 if skip_grid.is_skip_txfm(mi_r, mi_c) {
20017 hit!(CDEF_SKIPPED_UNITS);
20018 }
20019 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
20020 let sidx = strength_idx(mi_r, mi_c);
20021 let (ox, oy) = (mi_c * 4, mi_r * 4);
20022 // Nothing to do for this unit at all: the direction search is
20023 // only ever consumed through a strength, so a unit whose four
20024 // strengths are zero never needs its 8x8 window gathered.
20025 if cdef.y_pri_strength[sidx] == 0
20026 && cdef.y_sec_strength[sidx] == 0
20027 && cdef.uv_pri_strength[sidx] == 0
20028 && cdef.uv_sec_strength[sidx] == 0
20029 {
20030 mi_c += 2;
20031 continue;
20032 }
20033 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
20034 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
20035 // lane-cdef r1: the direction search reads the SAME padded
20036 // block the taps do -- libaom runs `cdef_find_dir` on the
20037 // prepared filter block (`cdef_block.c:296-320` over
20038 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
20039 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
20040 // Clamping to the last real sample instead made every straddling
20041 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
20042 // a different `adjust_strength`, hence a +-1 band at the crop edge.
20043 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
20044
20045 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
20046 // -- each plane zeroes the shared direction when *its own*
20047 // frame-level primary strength is 0, independent of the
20048 // per-block adjusted `t` and of the other plane's strength.
20049 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
20050 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
20051 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
20052 let t = cdef_adjust_strength(y_pri_strength, var);
20053 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
20054 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
20055 eprintln!(
20056 "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}"
20057 );
20058 }
20059 let enable_primary = t != 0;
20060 let enable_secondary = y_sec_strength != 0;
20061 if (ox + 8 > frame_w || oy + 8 > frame_h)
20062 && (enable_primary
20063 || enable_secondary
20064 || cdef.uv_pri_strength[sidx] != 0
20065 || cdef.uv_sec_strength[sidx] != 0)
20066 {
20067 hit!(CDEF_STRADDLE_UNITS);
20068 }
20069 if enable_primary || enable_secondary {
20070 cdef_filter_block(
20071 &win_y,
20072 y,
20073 ox,
20074 oy,
20075 8,
20076 8,
20077 t,
20078 y_sec_strength,
20079 y_dir,
20080 damping,
20081 damping,
20082 enable_primary,
20083 enable_secondary,
20084 coeff_shift, fctx,
20085 );
20086 }
20087
20088 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
20089 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
20090 let uv_dir = if t_uv != 0 { dir } else { 0 };
20091 let enable_primary_uv = t_uv != 0;
20092 let enable_secondary_uv = uv_sec_strength != 0;
20093 if enable_primary_uv || enable_secondary_uv {
20094 let (cox, coy) = (ox / 2, oy / 2);
20095 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
20096 let (tw, th) = (plane.true_width, plane.true_height);
20097 let stride = plane.width;
20098 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
20099 cdef_filter_block(
20100 &win_uv,
20101 plane,
20102 cox,
20103 coy,
20104 4,
20105 4,
20106 t_uv,
20107 uv_sec_strength,
20108 uv_dir,
20109 damping_uv,
20110 damping_uv,
20111 enable_primary_uv,
20112 enable_secondary_uv,
20113 coeff_shift, fctx,
20114 );
20115 }
20116 }
20117 }
20118 mi_c += 2;
20119 }
20120 mi_r += 2;
20121 }
20122}
20123
20124
20125// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
20126//
20127// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
20128// every plane's vertical deblock edges, then every plane's horizontal ones,
20129// then CDEF, then -- unpipelined -- superres and loop restoration).
20130// A band is 64 luma rows, one superblock row (a 128 superblock is two).
20131//
20132// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
20133// band r, so no filter may touch band r before band r+1 is reconstructed.
20134// Hence V(r) waits for `ready >= r + 2`.
20135// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
20136// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
20137// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
20138// side of the band boundary, so H(r-1)'s last edge reaches into band r,
20139// which the whole-frame order has already vertical-filtered -- V(r)
20140// before H(r-1) reproduces exactly that.
20141// * post-deblock finality: band j's own bottom rows are still rewritten by
20142// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
20143// only be taken after H(j+1).
20144// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
20145// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
20146//
20147// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
20148// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
20149// superres upscale, which is a whole-frame refusal for this path) stay in the
20150// frame thread's tail; the snapshot the pipeline built is what LR reads.
20151struct PipeQ {
20152 /// Bands whose reconstruction the frame thread has released.
20153 ready: usize,
20154 abort: bool,
20155}
20156
20157pub(crate) struct PipeSync {
20158 m: std::sync::Mutex<PipeQ>,
20159 cv: std::sync::Condvar,
20160}
20161
20162impl PipeSync {
20163 fn new() -> Self {
20164 Self {
20165 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
20166 cv: std::sync::Condvar::new(),
20167 }
20168 }
20169 fn note(&self, ready: usize) {
20170 let mut q = self.m.lock().unwrap();
20171 if ready > q.ready {
20172 q.ready = ready;
20173 self.cv.notify_all();
20174 }
20175 }
20176 /// Releases every remaining band (`abort` = the tile decoder is bailing
20177 /// out, so the worker returns instead of finishing the frame).
20178 fn close(&self, all: usize, abort: bool) {
20179 let mut q = self.m.lock().unwrap();
20180 q.ready = q.ready.max(all);
20181 q.abort |= abort;
20182 self.cv.notify_all();
20183 }
20184 /// `false` when the frame was aborted.
20185 fn wait_for(&self, want: usize) -> bool {
20186 let mut q = self.m.lock().unwrap();
20187 while q.ready < want && !q.abort {
20188 q = self.cv.wait(q).unwrap();
20189 }
20190 !q.abort
20191 }
20192}
20193
20194/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
20195/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
20196/// otherwise only the four rows around each stripe boundary that loop
20197/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
20198fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
20199 let w = src.width;
20200 if w == 0 {
20201 return;
20202 }
20203 let rows = src.data.len() / w;
20204 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
20205 if lo >= hi {
20206 return;
20207 }
20208 if full {
20209 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
20210 return;
20211 }
20212 let stripe_h = 64usize >> ss_y;
20213 let offset = 8usize >> ss_y;
20214 let mut b = stripe_h - offset;
20215 while b < rows {
20216 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
20217 if a < e {
20218 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
20219 }
20220 b += stripe_h;
20221 }
20222}
20223
20224/// Everything the pipeline worker needs that is not a plane or a grid.
20225struct PipeCfg<'a> {
20226 lf: &'a LoopFilterParams,
20227 cdef: &'a CdefParams,
20228 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
20229 /// entries of the superblock rows the pipeline has not reached; the Vec
20230 /// itself is sized once per frame, so the pointer stays valid.
20231 idx_grid: (*const u8, usize),
20232 sb_cols: usize,
20233 frame_w: usize,
20234 frame_h: usize,
20235 nbands: usize,
20236 cdef_on: bool,
20237 snap_on: bool,
20238}
20239
20240// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
20241// per frame and only ever written at indices the pipeline is three bands
20242// behind (see this module's dependency note).
20243#[allow(unsafe_code)]
20244unsafe impl Send for PipeCfg<'_> {}
20245
20246#[allow(unsafe_code)]
20247#[allow(clippy::too_many_arguments)]
20248fn pipe_run(
20249 sync: &PipeSync,
20250 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20251 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20252 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20253 sn: crate::par::Shared<'_, Neighbours>,
20254 cfg: PipeCfg<'_>,
20255 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20256 lr_sync: Option<&PipeSync>,
20257 fctx: &crate::decode::FrameCtx,
20258) {
20259 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
20260 // is at least two behind, and the two ranges never meet -- see the
20261 // dependency note above and `Shared`'s own corner-cut.
20262 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20263 let n: &Neighbours = unsafe { sn.get() };
20264 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
20265 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
20266 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
20267 let damping_uv = (damping - 1).max(0);
20268 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20269 let nb = cfg.nbands;
20270 for k in 0..nb + 3 {
20271 if !sync.wait_for((k + 2).min(nb)) {
20272 if let Some(ls) = lr_sync {
20273 ls.close(nb, true);
20274 }
20275 return;
20276 }
20277 if k < nb {
20278 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
20279 }
20280 if k >= 1 && k - 1 < nb {
20281 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
20282 }
20283 if cfg.snap_on && k >= 2 && k - 2 < nb {
20284 let j = k - 2;
20285 if let Some((sy2, su2, sv2)) = snap.as_mut() {
20286 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
20287 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20288 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20289 }
20290 }
20291 if cfg.cdef_on && k >= 3 && k - 3 < nb {
20292 let j = k - 3;
20293 if let Some((sy2, su2, sv2)) = snap.as_ref() {
20294 cdef_rows(
20295 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
20296 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
20297 );
20298 }
20299 }
20300 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
20301 // them to the loop restoration worker.
20302 if let Some(ls) = lr_sync {
20303 ls.note(k.saturating_sub(2));
20304 }
20305 }
20306 if let Some(ls) = lr_sync {
20307 ls.close(nb, false);
20308 }
20309}
20310
20311/// The pipeline's loop restoration worker, a second task alongside
20312/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
20313/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
20314/// post-deblock snapshot at most two rows past `v_end` (see
20315/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
20316/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
20317/// iteration `band + 3` and the snapshot band one iteration earlier, so the
20318/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
20319/// indices being at most one band apart. Running it as its own worker (not
20320/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
20321/// critical path: serialised into that loop it measured ~1% slower than the
20322/// whole-frame form, which at least ran its RU rows across the filter pool.
20323#[allow(unsafe_code)]
20324fn pipe_run_lr(
20325 sync: &PipeSync,
20326 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20327 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20328 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20329 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
20330 cfg: LrCfg<'_>,
20331 fctx: &crate::decode::FrameCtx,
20332) {
20333 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
20334 // and writes its own `out` buffers; the final swap happens after the
20335 // last CDEF band, which is `pipe_run`'s last plane write.
20336 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20337 let snap = unsafe { snap.get() };
20338 let grid = unsafe { &*cfg.lr_grid };
20339 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20340 let dims = [
20341 (fw, fh, 0u32, y.width, y.data.len()),
20342 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
20343 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
20344 ];
20345 let mut planes: Vec<LrPlane> = Vec::new();
20346 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
20347 let rows = crate::restoration::lr_unit_rows(
20348 ph,
20349 cfg.lr.loop_restoration_size[p],
20350 ss,
20351 cfg.lr.frame_restoration_type[p],
20352 );
20353 if rows.is_empty() {
20354 continue;
20355 }
20356 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
20357 }
20358 for band in 0..cfg.nbands {
20359 if !sync.wait_for(band + 1) {
20360 return;
20361 }
20362 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
20363 for lp in &mut planes {
20364 let stripe = 64usize >> lp.ss;
20365 let r_lo = lp.next;
20366 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
20367 lp.next += 1;
20368 }
20369 if lp.next == r_lo {
20370 continue;
20371 }
20372 let (src, deb) = match lp.p {
20373 0 => (&y.data, &sy2.data),
20374 1 => (&u.data, &su2.data),
20375 _ => (&v.data, &sv2.data),
20376 };
20377 crate::restoration::apply_loop_restoration_plane(
20378 src,
20379 deb,
20380 lp.stride,
20381 lp.pw,
20382 lp.ph,
20383 lp.ss,
20384 cfg.lr.frame_restoration_type[lp.p],
20385 cfg.lr.loop_restoration_size[lp.p],
20386 grid,
20387 lp.p,
20388 &mut lp.out,
20389 Some((r_lo, lp.next)),
20390 fctx,
20391 );
20392 }
20393 }
20394 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
20395 // untouched by restoration and copied here, then the restored plane
20396 // takes the picture's place (the whole-frame path's own final swap).
20397 for mut lp in planes {
20398 let buf: &mut PlaneBuf<'static> = match lp.p {
20399 0 => &mut *y,
20400 1 => &mut *u,
20401 _ => &mut *v,
20402 };
20403 let tail = lp.ph * lp.stride;
20404 if tail < buf.data.len() {
20405 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
20406 }
20407 scratch_return(
20408 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
20409 );
20410 }
20411}
20412
20413/// Everything [`pipe_run_lr`] needs beyond the planes.
20414struct LrCfg<'a> {
20415 lr: &'a LoopRestorationParams,
20416 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
20417 /// many bands ahead of every unit this worker reads.
20418 lr_grid: *const crate::restoration::RestorationGrid,
20419 frame_w: usize,
20420 frame_h: usize,
20421 nbands: usize,
20422}
20423
20424// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
20425#[allow(unsafe_code)]
20426unsafe impl Send for LrCfg<'_> {}
20427
20428/// One plane's pipelined loop restoration state (see [`pipe_run`]).
20429struct LrPlane {
20430 p: usize,
20431 /// The restored plane, built band by band and swapped in at the end.
20432 out: Vec<u16>,
20433 rows: Vec<(u32, u32)>,
20434 /// The first RU row not yet restored.
20435 next: usize,
20436 pw: usize,
20437 ph: usize,
20438 ss: u32,
20439 stride: usize,
20440}
20441
20442/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
20443/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
20444/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
20445/// pointers into the frame's planes, so it may not outlive them).
20446struct PipeGuard<'a> {
20447 sync: std::sync::Arc<PipeSync>,
20448 batch: Option<crate::par::Batch<'a>>,
20449 nbands: usize,
20450 /// The loop restoration worker's own gate, aborted with the first one.
20451 lr_sync: Option<std::sync::Arc<PipeSync>>,
20452}
20453
20454impl PipeGuard<'_> {
20455 fn note(&self, bands: usize) {
20456 self.sync.note(bands);
20457 }
20458 fn finish(&mut self) {
20459 self.sync.close(self.nbands, false);
20460 // Dropping the batch waits the worker out.
20461 self.batch.take();
20462 }
20463}
20464
20465impl Drop for PipeGuard<'_> {
20466 fn drop(&mut self) {
20467 self.sync.close(self.nbands, true);
20468 if let Some(ls) = &self.lr_sync {
20469 ls.close(self.nbands, true);
20470 }
20471 }
20472}
20473
20474/// Leading superblock rows of the live tile's wavefront that are fully
20475/// reconstructed: parsed out to the last column and with every job that
20476/// carried a write finished. 0 when reconstruction is inline (no wavefront),
20477/// where the caller uses the parse position instead.
20478fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
20479 let st = fctx.wave.with(|w| w.borrow().clone());
20480 let Some(st) = st else { return 0 };
20481 let q = st.q.lock().unwrap();
20482 let mut n = 0;
20483 while n < q.rows.len() {
20484 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
20485 break;
20486 }
20487 n += 1;
20488 }
20489 n
20490}
20491
20492/// Frames whose loop filters ran pipelined, and frames that took the
20493/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
20494static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
20495static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
20496
20497/// Whether this frame's filters may run per superblock row. Everything that
20498/// reads the picture out of band order, or the pipeline's own inputs out of
20499/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
20500/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
20501/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
20502/// frame row is only complete after the last tile column's own parse), and
20503/// every pixel-dump / stage-skip debug flag, whose whole point is the
20504/// unpipelined stage boundary. The pipeline also stays off unless some
20505/// threading is on -- at (1, 1) the filters would run on a worker thread for
20506/// nothing and the crate's `thread_local!` gate counters would miss them.
20507fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
20508 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
20509 return false;
20510 }
20511 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
20512 return false;
20513 }
20514 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
20515 return false;
20516 }
20517 if fctx.seg.with(|s| s.borrow().enabled) {
20518 return false;
20519 }
20520 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
20521 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
20522 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
20523 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
20524 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
20525 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
20526 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
20527 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
20528 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
20529 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
20530 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
20531 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
20532}
20533
20534/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
20535/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
20536/// never enters `apply_cdef`, so it calls this itself).
20537fn cdef_scan_counters(skip_grid: &Neighbours) {
20538 let _ = skip_grid;
20539 hit_do! {
20540 let mut r = 0usize;
20541 while r < skip_grid.mi_rows {
20542 let mut c = 0usize;
20543 while c < skip_grid.mi_cols {
20544 if (0..2).any(|rr| {
20545 (0..2).any(|cc| {
20546 !skip_grid
20547 .blk_grid
20548 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
20549 .map_or(true, |x| x.written)
20550 })
20551 }) {
20552 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
20553 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
20554 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
20555 }
20556 }
20557 let cell = |rr: usize, cc: usize| {
20558 skip_grid
20559 .blk_grid
20560 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
20561 .is_some_and(|x| x.skip)
20562 };
20563 let first = cell(0, 0);
20564 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
20565 hit!(CDEF_MIXED_SKIP_UNITS);
20566 }
20567 c += 2;
20568 }
20569 r += 2;
20570 }
20571 }
20572}
20573
20574/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
20575/// means "no filtering at all" whenever the single (index 0) strength pair
20576/// is all-zero, the fast path every existing gate stream takes.
20577fn cdef_all_zero(cdef: &CdefParams) -> bool {
20578 cdef.bits == 0
20579 && cdef.y_pri_strength[0] == 0
20580 && cdef.y_sec_strength[0] == 0
20581 && cdef.uv_pri_strength[0] == 0
20582 && cdef.uv_sec_strength[0] == 0
20583}
20584
20585/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
20586/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
20587/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
20588/// row range's own pixels.
20589#[allow(clippy::too_many_arguments)]
20590fn cdef_rows(
20591 y: &mut PlaneBuf<'static>,
20592 u: &mut PlaneBuf<'static>,
20593 v: &mut PlaneBuf<'static>,
20594 src_y: &[u16],
20595 src_u: &[u16],
20596 src_v: &[u16],
20597 cdef: &CdefParams,
20598 skip_grid: &Neighbours,
20599 idx_grid: &[u8],
20600 sb_cols: usize,
20601 coeff_shift: i32,
20602 damping: i32,
20603 damping_uv: i32,
20604 (frame_w, frame_h): (usize, usize),
20605 r_lo0: usize,
20606 r_hi0: usize, fctx: &crate::decode::FrameCtx,
20607) {
20608 let mi_rows = skip_grid.mi_rows;
20609 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
20610 if lo >= hi {
20611 return;
20612 }
20613 let (sy, su, sv) = (
20614 crate::par::Shared::new(y),
20615 crate::par::Shared::new(u),
20616 crate::par::Shared::new(v),
20617 );
20618 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
20619 .into_iter()
20620 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
20621 .collect();
20622 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
20623 // SAFETY: this band writes only the plane rows its own mi rows cover,
20624 // disjoint from every other band's (see `Shared`).
20625 #[allow(unsafe_code)]
20626 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20627 cdef_band(
20628 r_lo,
20629 r_hi,
20630 y,
20631 u,
20632 v,
20633 src_y,
20634 src_u,
20635 src_v,
20636 cdef,
20637 skip_grid,
20638 idx_grid,
20639 sb_cols,
20640 coeff_shift,
20641 damping,
20642 damping_uv,
20643 (frame_w, frame_h),
20644 fctx,
20645 );
20646 });
20647}
20648
20649fn apply_cdef(
20650 y: &mut PlaneBuf<'static>,
20651 u: &mut PlaneBuf<'static>,
20652 v: &mut PlaneBuf<'static>,
20653 cdef: &CdefParams,
20654 skip_grid: &Neighbours,
20655 // This frame header's own CROPPED luma size, for the straddling-unit
20656 // counter only -- CDEF itself walks the mi-rounded plane.
20657 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
20658) {
20659 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
20660 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
20661 return;
20662 }
20663 cdef_scan_counters(skip_grid);
20664 // `cdef.bits == 0` still means "no filtering at all" whenever the single
20665 // (index 0) strength pair is all-zero -- the fast path every existing
20666 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
20667 // at every index, but that is rare enough not to special-case; the
20668 // per-superblock lookup below degrades to the same index-0 read anyway
20669 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
20670 if cdef_all_zero(cdef) {
20671 return;
20672 }
20673 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
20674 // One entry per superblock (a few hundred at 4K), so this clone is not
20675 // one of the per-frame copies lane-perf6 pooled below.
20676 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
20677 let src_y = scratch_from(&y.data);
20678 let src_u = scratch_from(&u.data);
20679 let src_v = scratch_from(&v.data);
20680 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
20681 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
20682 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
20683 let damping = i32::from(cdef.damping) + coeff_shift;
20684 let damping_uv = (damping - 1).max(0);
20685 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
20686 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
20687 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
20688 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
20689 // disjoint row range of all three planes.
20690 cdef_rows(
20691 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
20692 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
20693 );
20694 scratch_return(src_y);
20695 scratch_return(src_u);
20696 scratch_return(src_v);
20697}
20698
20699/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
20700/// restoration on both tile paths: hands the encoder's restoration search the
20701/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
20702/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
20703/// a capture is worth three plane copies and nothing else -- and when the
20704/// capture flag is off (every decode but that search) it is worth a bool.
20705fn capture_stages(
20706 y: &PlaneBuf<'_>,
20707 u: &PlaneBuf<'_>,
20708 v: &PlaneBuf<'_>,
20709 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20710 fctx: &FrameCtx,
20711) {
20712 if !fctx.capture_stages.get() {
20713 return;
20714 }
20715 // Without an active restoration type the decoder took no pre-CDEF
20716 // snapshot; the post-CDEF plane then stands in for it, which is exact
20717 // everywhere but LR's own 3-row stripe borders (the encoder's search
20718 // always asks with a type set, so this is the defensive arm).
20719 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
20720 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
20721 None => p.data.to_vec(),
20722 };
20723 *fctx.stages.borrow_mut() = Some(FilterStages {
20724 deblocked: [db(0, y), db(1, u), db(2, v)],
20725 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20726 stride: [y.width, u.width, v.width],
20727 });
20728}
20729
20730/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
20731/// ordering note: libaom also runs `superres_post_decode` between the two,
20732/// but this decoder never implements super-resolution, so there is nothing
20733/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
20734/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
20735/// restoration's stripe-boundary rows read from it instead of the
20736/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
20737#[allow(clippy::too_many_arguments)]
20738fn apply_loop_restoration(
20739 y: &mut PlaneBuf<'static>,
20740 u: &mut PlaneBuf<'static>,
20741 v: &mut PlaneBuf<'static>,
20742 deblocked_y: &PlaneBuf<'_>,
20743 deblocked_u: &PlaneBuf<'_>,
20744 deblocked_v: &PlaneBuf<'_>,
20745 lr: &LoopRestorationParams,
20746 grid: &crate::restoration::RestorationGrid,
20747 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
20748 // restoration is the ONE post-decode filter that does NOT run over the
20749 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
20750 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
20751 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
20752 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
20753 // -- and asserts it equals the buffer's CROP width
20754 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
20755 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
20756 // that cropped edge before any unit is filtered. Deblock and CDEF DO
20757 // walk the mi grid, which is why passing `true_width`/`true_height`
20758 // here went unnoticed until a frame whose size is not a multiple of 8
20759 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
20760 // read this decoder's own decoded samples at columns 68..71 where
20761 // libaom reads column 67 replicated -- +-1 over the straddling band
20762 // (class av1-truesize-lane: true frame size vs mi-rounded).
20763 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
20764) {
20765 let mut out = scratch_empty();
20766 crate::restoration::apply_loop_restoration_plane(
20767 &y.data,
20768 &deblocked_y.data,
20769 y.width,
20770 frame_w,
20771 frame_h,
20772 0,
20773 lr.frame_restoration_type[0],
20774 lr.loop_restoration_size[0],
20775 grid,
20776 0,
20777 &mut out, None, fctx,
20778 );
20779 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
20780 let mut out = scratch_empty();
20781 crate::restoration::apply_loop_restoration_plane(
20782 &u.data,
20783 &deblocked_u.data,
20784 u.width,
20785 frame_w.div_ceil(2),
20786 frame_h.div_ceil(2),
20787 1,
20788 lr.frame_restoration_type[1],
20789 lr.loop_restoration_size[1],
20790 grid,
20791 1,
20792 &mut out, None, fctx,
20793 );
20794 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
20795 let mut out = scratch_empty();
20796 crate::restoration::apply_loop_restoration_plane(
20797 &v.data,
20798 &deblocked_v.data,
20799 v.width,
20800 frame_w.div_ceil(2),
20801 frame_h.div_ceil(2),
20802 1,
20803 lr.frame_restoration_type[2],
20804 lr.loop_restoration_size[2],
20805 grid,
20806 2,
20807 &mut out, None, fctx,
20808 );
20809 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
20810}
20811
20812/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
20813/// returning the picture it reconstructs to.
20814///
20815/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
20816/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
20817/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
20818/// `compute_image_size` derives one from the other, but not losslessly: a
20819/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
20820/// what the reconstruction is cropped to on the way out, mirroring
20821/// [`crate::encode::crop_encoded`].
20822///
20823/// # Errors
20824/// Returns an error when a block's partition, mode, skip flag or transform
20825/// type is anything this decoder does not reconstruct (round 2: inter, tx
20826/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
20827/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
20828/// or when the tile payload runs out of the symbols this decode expects (a
20829/// genuinely foreign stream).
20830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
20831pub(crate) fn decode_key_frame_tile(
20832 data: &[u8],
20833 mi_cols: u32,
20834 mi_rows: u32,
20835 base_q_idx: u8,
20836 frame_width: u32,
20837 frame_height: u32,
20838 enable_filter_intra: bool,
20839 cdef: &CdefParams,
20840 loop_filter: &LoopFilterParams,
20841 tx_select: bool,
20842 reduced_tx_set: bool,
20843 allow_screen_content_tools: bool,
20844 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
20845) -> Result<Picture> {
20846 decode_key_frame_tile_lr(
20847 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
20848 cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
20849 &LoopRestorationParams::default(), fctx,
20850 )
20851}
20852
20853/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
20854/// 5.9.20) instead of the no-restoration default -- the per-unit filters
20855/// themselves live in the tile payload, so the header is all this needs.
20856#[allow(clippy::too_many_arguments)]
20857pub(crate) fn decode_key_frame_tile_lr(
20858 data: &[u8],
20859 mi_cols: u32,
20860 mi_rows: u32,
20861 base_q_idx: u8,
20862 frame_width: u32,
20863 frame_height: u32,
20864 enable_filter_intra: bool,
20865 cdef: &CdefParams,
20866 loop_filter: &LoopFilterParams,
20867 tx_select: bool,
20868 reduced_tx_set: bool,
20869 allow_screen_content_tools: bool,
20870 allow_intrabc: bool,
20871 lr: &LoopRestorationParams,
20872 fctx: &crate::decode::FrameCtx,
20873) -> Result<Picture> {
20874 let single_tile = TileInfo {
20875 mi_col_starts: vec![0, mi_cols],
20876 mi_row_starts: vec![0, mi_rows],
20877 ..TileInfo::default()
20878 };
20879 decode_key_frame_tiles_lr(
20880 &[data],
20881 &single_tile,
20882 mi_cols,
20883 mi_rows,
20884 base_q_idx,
20885 frame_width,
20886 frame_height,
20887 enable_filter_intra,
20888 cdef,
20889 loop_filter,
20890 tx_select,
20891 reduced_tx_set,
20892 allow_screen_content_tools,
20893 allow_intrabc,
20894 lr,
20895 fctx,
20896 )
20897}
20898
20899/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
20900/// encoder's own filter search hands back one payload per tile plus the
20901/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
20902/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
20903#[allow(clippy::too_many_arguments)]
20904pub(crate) fn decode_key_frame_tiles_lr(
20905 tiles: &[&[u8]],
20906 tile_info: &TileInfo,
20907 mi_cols: u32,
20908 mi_rows: u32,
20909 base_q_idx: u8,
20910 frame_width: u32,
20911 frame_height: u32,
20912 enable_filter_intra: bool,
20913 cdef: &CdefParams,
20914 loop_filter: &LoopFilterParams,
20915 tx_select: bool,
20916 reduced_tx_set: bool,
20917 allow_screen_content_tools: bool,
20918 allow_intrabc: bool,
20919 lr: &LoopRestorationParams,
20920 fctx: &crate::decode::FrameCtx,
20921) -> Result<Picture> {
20922 let delta = DeltaParams::default();
20923 decode_key_frame_tile_with_cdfs(
20924 tiles,
20925 tile_info,
20926 mi_cols,
20927 mi_rows,
20928 base_q_idx,
20929 crate::quant::QuantDeltas::default(),
20930 frame_width,
20931 frame_height,
20932 enable_filter_intra,
20933 false,
20934 cdef,
20935 loop_filter,
20936 lr,
20937 None,
20938 tx_select,
20939 reduced_tx_set,
20940 allow_screen_content_tools,
20941 allow_intrabc,
20942 delta, fctx,
20943 )
20944 .map(|(picture, _)| picture)
20945}
20946
20947 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
20948 /// the mi-aligned `true_width`, set by the most recent
20949 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
20950 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
20951 /// their reconstructed buffer down from the same mi-aligned extent, so
20952 /// they share this one slot. See each function's own comment at its
20953 /// write site. `None` when there was no margin to save.
20954
20955/// The margin the most recent key- or inter-frame tile decode stashed
20956/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
20957/// reads this immediately after the call, before any other frame
20958/// decode can overwrite it.
20959#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
20960pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
20961 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
20962}
20963
20964/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
20965/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
20966/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
20967/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
20968/// since a key frame's own header always forces `primary_ref_frame ==
20969/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
20970/// alongside the picture, for the caller to save into whichever reference
20971/// slots this frame's `refresh_frame_flags` names.
20972/// The order the 64x64 superblock quadrants of a tile are decoded in.
20973///
20974/// At `sb_size == 64` this is plain raster order over the tile's own
20975/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
20976/// each 128x128 superblock in raster order and visits its four 64x64
20977/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
20978/// 64-level bodies must run in that nested order. `row_start` marks the first
20979/// item of each *superblock* row (where the left neighbour context resets),
20980/// `sb_start` the first item of each superblock (where the 128 root's own
20981/// loop-restoration units and partition symbol are read).
20982fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
20983 let mut out = Vec::new();
20984 if !sb128 {
20985 for r in r0..r1 {
20986 for c in c0..c1 {
20987 out.push((r, c, c == c0, true));
20988 }
20989 }
20990 return out;
20991 }
20992 let mut r = r0;
20993 while r < r1 {
20994 let mut first_in_row = true;
20995 let mut c = c0;
20996 while c < c1 {
20997 let mut first_in_sb = true;
20998 for qr in 0..2 {
20999 for qc in 0..2 {
21000 let (rr, cc) = (r + qr, c + qc);
21001 if rr >= r1 || cc >= c1 {
21002 continue;
21003 }
21004 out.push((rr, cc, first_in_row, first_in_sb));
21005 first_in_row = false;
21006 first_in_sb = false;
21007 }
21008 }
21009 c += 2;
21010 }
21011 r += 2;
21012 }
21013 out
21014}
21015
21016// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
21017// the inter tile loop. Its loop-restoration units are read once for the whole
21018// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
21019// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
21020// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
21021// decoder codes, the other seven arms refuse by name.
21022thread_local! {
21023 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
21024 /// whole 128x128 block (lane-sb128b r1's gate counter).
21025 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21026 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
21027 /// when the bottom half is out of frame) -- lane-sb128c r7.
21028 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21029 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
21030 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21031 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
21032 /// only shape a 1080p (mi_rows = 270) stream reaches.
21033 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21034 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21035 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
21036 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
21037 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
21038}
21039
21040/// [`PART128_AB_HITS`], for a gate's own before/after delta.
21041pub(crate) fn part128_ab_hits() -> [usize; 4] {
21042 PART128_AB_HITS.with(std::cell::Cell::get)
21043}
21044
21045/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
21046#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21047pub(crate) fn part128_none_hits() -> usize {
21048 PART128_NONE_HITS.with(std::cell::Cell::get)
21049}
21050
21051/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
21052#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21053pub(crate) fn part128_horz_hits() -> usize {
21054 PART128_HORZ_HITS.with(std::cell::Cell::get)
21055}
21056
21057/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
21058#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21059pub(crate) fn part128_vert_hits() -> usize {
21060 PART128_VERT_HITS.with(std::cell::Cell::get)
21061}
21062
21063/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
21064pub(crate) fn part128_edge_horz_hits() -> usize {
21065 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
21066}
21067
21068/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
21069pub(crate) fn part128_edge_vert_hits() -> usize {
21070 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
21071}
21072
21073thread_local! {
21074 /// How many CHROMA transform units were coded inside a block whose uv
21075 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
21076 /// block, four per plane).
21077 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21078}
21079
21080/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
21081#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21082pub(crate) fn chroma_split_tx_hits() -> usize {
21083 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
21084}
21085
21086fn read_sb128_root(
21087 dec: &mut SymbolDecoder,
21088 cdfs: &mut Cdfs,
21089 neighbours: &Neighbours,
21090 lr: &LoopRestorationParams,
21091 lr_grid: &mut crate::restoration::RestorationGrid,
21092 lr_reference: &mut [(
21093 crate::restoration::WienerInfo,
21094 crate::restoration::SgrprojInfo,
21095 ); 3],
21096 sb_r: u32,
21097 sb_c: u32,
21098 mi_cols: u32,
21099 mi_rows: u32, fctx: &crate::decode::FrameCtx,
21100) -> Result<usize> {
21101 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
21102 crate::restoration::read_lr(
21103 dec,
21104 cdfs,
21105 lr,
21106 lr_grid,
21107 lr_reference,
21108 mi_r128,
21109 mi_c128,
21110 SB_MI * 2, fctx,
21111 );
21112 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
21113 let ctx128 = neighbours.partition_ctx(at128, 128);
21114 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
21115 let part128 = if has_cols128 && has_rows128 {
21116 hit!(PART128_SYMBOLS);
21117 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
21118 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21119 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
21120 }
21121 p
21122 } else {
21123 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
21124 // partition, they are not a forced split -- exactly the discarded-bit
21125 // defect the 64 root carries a comment about at `partition_w64`'s
21126 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
21127 // VERT (cols out of frame), which the refusal below then names
21128 // instead of silently reconstructing a split.
21129 hit!(PART128_GATHERED_SYMBOLS);
21130 match (has_cols128, has_rows128) {
21131 (true, false) => {
21132 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
21133 PARTITION_SPLIT
21134 } else {
21135 hit!(PART128_EDGE_HORZ_HITS);
21136 PARTITION_HORZ
21137 }
21138 }
21139 (false, true) => {
21140 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
21141 PARTITION_SPLIT
21142 } else {
21143 hit!(PART128_EDGE_VERT_HITS);
21144 PARTITION_VERT
21145 }
21146 }
21147 _ => {
21148 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
21149 bump_edge_both_cut(3);
21150 PARTITION_SPLIT
21151 }
21152 }
21153 };
21154 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
21155 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
21156 // four AB shapes) still need the rect/AB machinery at this size.
21157 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
21158 // both tile paths. The four AB shapes (libaom `decode_partition`'s
21159 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
21160 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
21161 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
21162 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
21163 // which stops at VERT_B).
21164 match part128 {
21165 PARTITION_SPLIT => hit!(PART128_SPLIT_HITS),
21166 PARTITION_NONE => hit!(PART128_NONE_HITS),
21167 PARTITION_HORZ => hit!(PART128_HORZ_HITS),
21168 PARTITION_VERT => hit!(PART128_VERT_HITS),
21169 // lane-sb128c r9: the four AB shapes at the 128 root -- one
21170 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
21171 // paths below in libaom `decode_partition`'s own visit order.
21172 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
21173 hit_do! {
21174 PART128_AB_HITS.with(|c| {
21175 let mut h = c.get();
21176 h[p - PARTITION_HORZ_A] += 1;
21177 c.set(h);
21178 });
21179 }
21180 }
21181 _ => {
21182 return Err(unsupported(
21183 "a 128x128 superblock partition value outside the 8-symbol alphabet",
21184 ));
21185 }
21186 }
21187 Ok(part128)
21188}
21189
21190pub(crate) fn decode_key_frame_tile_with_cdfs(
21191 tiles: &[&[u8]],
21192 tile_info: &TileInfo,
21193 mi_cols: u32,
21194 mi_rows: u32,
21195 base_q_idx: u8,
21196 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
21197 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
21198 // tile alongside [`CURRENT_Q_IDX`].
21199 deltas: crate::quant::QuantDeltas,
21200 frame_width: u32,
21201 frame_height: u32,
21202 enable_filter_intra: bool,
21203 enable_edge_filter: bool,
21204 cdef: &CdefParams,
21205 loop_filter: &LoopFilterParams,
21206 lr: &LoopRestorationParams,
21207 initial_cdfs: Option<Cdfs>,
21208 tx_select: bool,
21209 reduced_tx_set: bool,
21210 allow_screen_content_tools: bool,
21211 allow_intrabc: bool,
21212 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
21213 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
21214 // `stream.rs` still refuses a frame with `lf_present` set before this
21215 // function is ever called.
21216 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
21217) -> Result<(Picture, Cdfs)> {
21218 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
21219 // only, so a key frame decoded after an inter frame on this thread would
21220 // otherwise inherit it and read its `tx_depth` context off the inter
21221 // frame's stale `TXFM_CONTEXT` bands.
21222 fctx.tx_select_inter.with(|c| c.set(false));
21223 if mi_cols == 0 || mi_rows == 0 {
21224 return Err(unsupported("a frame with no mode-info grid"));
21225 }
21226 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
21227 let sb128 = sb128(fctx);
21228 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
21229 fctx.intrabc_mi_grid.with(|g| {
21230 *g.borrow_mut() = allow_intrabc.then(|| {
21231 (
21232 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
21233 mi_cols as usize,
21234 mi_rows as usize,
21235 )
21236 });
21237 });
21238 fctx.intrabc_dv.with(|c| c.set(None));
21239 fctx.cdef_bits.with(|c| c.set(cdef.bits));
21240 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
21241 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
21242 fctx.delta_q_present.with(|c| c.set(delta.q_present));
21243 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
21244 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
21245 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
21246 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
21247 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
21248 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
21249 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
21250
21251 let mut y = PlaneBuf {
21252 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
21253 width,
21254 height,
21255 true_width,
21256 true_height,
21257 tile_x0: 0,
21258 tile_y0: 0,
21259 tile_x1: width,
21260 tile_y1: height,
21261 };
21262 let mut u = PlaneBuf {
21263 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21264 width: width / 2,
21265 height: height / 2,
21266 true_width: true_width / 2,
21267 true_height: true_height / 2,
21268 tile_x0: 0,
21269 tile_y0: 0,
21270 tile_x1: width / 2,
21271 tile_y1: height / 2,
21272 };
21273 let mut v = PlaneBuf {
21274 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21275 width: width / 2,
21276 height: height / 2,
21277 true_width: true_width / 2,
21278 true_height: true_height / 2,
21279 tile_x0: 0,
21280 tile_y0: 0,
21281 tile_x1: width / 2,
21282 tile_y1: height / 2,
21283 };
21284
21285 let scan32 = default_scan(TX32);
21286 let scan16 = default_scan(TX16);
21287 let scan8 = default_scan(TX8);
21288 let scan4 = default_scan(TX4);
21289
21290 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
21291 let mut result_cdfs = base_cdfs.clone();
21292 let mut neighbours = Neighbours::new(
21293 cols32 as usize * 2,
21294 rows32 as usize * 2,
21295 mi_cols as usize,
21296 mi_rows as usize, fctx,
21297 );
21298 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
21299 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
21300 // loop restoration runs after the superres upscale.
21301 let mut lr_grid = crate::restoration::RestorationGrid::new(
21302 lr,
21303 superres(fctx).map_or(frame_width, |(w, _)| w),
21304 frame_height,
21305 );
21306
21307 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
21308 // own byte range and its own fresh copy of the frame's initial CDFs
21309 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
21310 // `context_update_tile_id` has its end-of-tile adapted table kept as the
21311 // frame's own output (spec `exit_symbol`) -- every other tile's
21312 // adaptation is discarded, matching the refusal this replaces.
21313 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
21314 let tile_num = tile_idx as u32;
21315 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
21316 let mi_row0 = tile_info.mi_row_starts[trow as usize];
21317 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
21318 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
21319 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
21320 // Tile boundaries are always superblock-aligned in mi units (spec
21321 // 5.9.15's uniform/non-uniform derivation both only ever emit
21322 // multiples of the superblock's own mi size), so plain division is
21323 // exact here -- no rounding needed.
21324 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
21325 // tile boundary) are always superblock-aligned by spec 5.9.15; the
21326 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
21327 // last entry) is not, so the upper bound needs `div_ceil` the same
21328 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
21329 // trailing partial superblock row/column in scope.
21330 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
21331 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
21332
21333 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
21334 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
21335 // once per frame. Carried across a tile boundary, the loop-restoration
21336 // coefficients of the next tile decode off the previous tile's
21337 // reference -- same symbol count, so entropy and reconstruction stay
21338 // exact and only the filtered pixels of every tile after the first
21339 // are wrong.
21340 let mut lr_reference = [(
21341 crate::restoration::WienerInfo::default(),
21342 crate::restoration::SgrprojInfo::default(),
21343 ); 3];
21344 let mut cdfs = base_cdfs.clone();
21345 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
21346 // `base_q_idx` at the top of every tile, not once per frame.
21347 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
21348 fctx.quant_deltas.with(|c| c.set(deltas));
21349 fctx.current_delta_lf.with(|c| c.set([0; 4]));
21350 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21351 eprintln!(
21352 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
21353 tile_bytes.len(),
21354 &tile_bytes[..tile_bytes.len().min(8)]
21355 );
21356 }
21357 let mut dec = SymbolDecoder::new(tile_bytes);
21358 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
21359 y.set_tile_origin(
21360 mi_col0 as usize * 4,
21361 mi_row0 as usize * 4,
21362 (mi_col1 as usize * 4).min(y.width),
21363 (mi_row1 as usize * 4).min(y.height),
21364 );
21365 u.set_tile_origin(
21366 mi_col0 as usize * 2,
21367 mi_row0 as usize * 2,
21368 (mi_col1 as usize * 2).min(u.width),
21369 (mi_row1 as usize * 2).min(u.height),
21370 );
21371 v.set_tile_origin(
21372 mi_col0 as usize * 2,
21373 mi_row0 as usize * 2,
21374 (mi_col1 as usize * 2).min(v.width),
21375 (mi_row1 as usize * 2).min(v.height),
21376 );
21377 hit!(TILE_HITS);
21378
21379 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
21380 // its one block covers all four 64x64 quadrants, so the remaining three
21381 // visits of this superblock code nothing at all.
21382 let mut sb128_none = false;
21383 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
21384 // are performed at their push sites (nothing reaches the queue below).
21385 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
21386 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
21387 // when `sb128`, since a 128 block writes across its four 64x64 visits).
21388 let wave_shift = u32::from(sb128);
21389 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
21390 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
21391 (
21392 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
21393 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
21394 )
21395 } else {
21396 (0, 0)
21397 };
21398 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
21399 let waving = fctx.wave.with(|w| w.borrow().is_some());
21400 let mut wave_job = (0usize, 0usize);
21401 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
21402 // lane-wave1: the previous superblock's recorded writes -- handed to
21403 // the wavefront workers, or replayed here at one recon thread (where
21404 // the queue is empty, every write having run at its push site).
21405 if waving {
21406 if sb_start {
21407 wave_submit(fctx, wave_job.0, wave_job.1);
21408 wave_job = (
21409 (sb_r >> wave_shift) as usize - wave_r0,
21410 (sb_c >> wave_shift) as usize - wave_c0,
21411 );
21412 }
21413 } else {
21414 flush_recon(fctx, &mut y, &mut u, &mut v);
21415 }
21416 if row_start {
21417 neighbours.start_row();
21418 }
21419 if sb_start {
21420 sb128_none = false;
21421 }
21422 if sb128_none {
21423 continue;
21424 }
21425 {
21426 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
21427 // once for the whole 128x128 (spec 5.11.57 is called with the
21428 // superblock's own size), then one partition symbol off the
21429 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
21430 // recurses into the four 64x64 quadrants this decoder codes.
21431 if sb128 && sb_start {
21432 let part128 = read_sb128_root(
21433 &mut dec,
21434 &mut cdfs,
21435 &neighbours,
21436 lr,
21437 &mut lr_grid,
21438 &mut lr_reference,
21439 sb_r,
21440 sb_c,
21441 mi_cols,
21442 mi_rows, fctx,
21443 )?;
21444 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
21445 // lane-sb128c r9: the four AB shapes at the 128 root.
21446 // libaom `decode_partition` (decodeframe.c) codes each as
21447 // two `bsize2` (64x64) squares plus one `subsize`
21448 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
21449 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
21450 // half; VERT_B = left half, TR, BR. AB values only come
21451 // from the FULL alphabet symbol, which is only read when
21452 // both halves of the root are inside the frame, so no
21453 // piece needs libaom's `i > 0` frame-edge break (a piece
21454 // may still overhang the bottom/right, which
21455 // `PlaneBuf::reconstruct`'s r8 clip handles).
21456 sb128_none = true;
21457 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
21458 let (br, bc) = (at128.0 + 4, at128.1 + 4);
21459 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
21460 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
21461 // BR), so only they switch libaom's `has_tr_vert_*` /
21462 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
21463 let _vert_ab =
21464 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
21465 .then(crate::encode::Reach::vert_ab_partition);
21466 // One `cdef_idx` literal per CODED BLOCK, at the first
21467 // non-skip one of each 64x64 CDEF unit; the 128x64 /
21468 // 64x128 half covers two units and its read lands in the
21469 // unit holding its origin, so that value is copied to the
21470 // other one (libaom: every mi of the block points at the
21471 // same `MB_MODE_INFO`).
21472 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
21473 fctx.cdef_idx_grid.with(|g| {
21474 let mut g = g.borrow_mut();
21475 let cols = fctx.cdef_sb_cols.with(|c| c.get());
21476 if cols == 0 {
21477 return;
21478 }
21479 let (si, di) = (
21480 (q_r + src.0) * cols + q_c + src.1,
21481 (q_r + dst.0) * cols + q_c + dst.1,
21482 );
21483 if q_c + src.1 < cols
21484 && q_c + dst.1 < cols
21485 && si < g.len()
21486 && di < g.len()
21487 {
21488 g[di] = g[si];
21489 }
21490 });
21491 };
21492 macro_rules! square64 {
21493 ($at:expr) => {{
21494 fctx.cdef_transmitted.with(|c| c.set(false));
21495 decode_block(
21496 &mut dec,
21497 &mut cdfs,
21498 &mut neighbours,
21499 $at,
21500 SB,
21501 TxbSet::Luma64,
21502 TxbSet::Chroma32,
21503 TX32,
21504 TX32,
21505 (&scan32, &scan32),
21506 false,
21507 &mut y,
21508 &mut u,
21509 &mut v,
21510 base_q_idx,
21511 enable_filter_intra,
21512 allow_screen_content_tools,
21513 allow_intrabc,
21514 &scan32,
21515 &scan16,
21516 &scan8,
21517 &scan4,
21518 tx_select,
21519 reduced_tx_set, fctx,
21520 )?
21521 }};
21522 }
21523 macro_rules! half128 {
21524 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
21525 fctx.cdef_transmitted.with(|c| c.set(false));
21526 decode_block_128rect(
21527 &mut dec,
21528 &mut cdfs,
21529 &mut neighbours,
21530 $at,
21531 $bw,
21532 $bh,
21533 &mut y,
21534 &mut u,
21535 &mut v,
21536 base_q_idx,
21537 enable_filter_intra,
21538 allow_screen_content_tools,
21539 tx_select,
21540 reduced_tx_set, fctx,
21541 )?;
21542 cdef_copy($src, $dst);
21543 }};
21544 }
21545 match part128 {
21546 PARTITION_HORZ_A => {
21547 square64!(at128);
21548 square64!((at128.0, bc));
21549 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
21550 }
21551 PARTITION_HORZ_B => {
21552 half128!(at128, 128, 64, (0, 0), (0, 1));
21553 square64!((br, at128.1));
21554 square64!((br, bc));
21555 }
21556 PARTITION_VERT_A => {
21557 square64!(at128);
21558 square64!((br, at128.1));
21559 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
21560 }
21561 _ => {
21562 half128!(at128, 64, 128, (0, 0), (1, 0));
21563 square64!((at128.0, bc));
21564 square64!((br, bc));
21565 }
21566 }
21567 continue;
21568 }
21569 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
21570 // lane-sb128c r8: libaom `decode_partition`
21571 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
21572 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
21573 // plus a second one at (mi_row + hbs, mi_col) only
21574 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
21575 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
21576 // = 16 mi. Both halves together cover the whole root, so
21577 // the remaining three 64x64 quadrant visits code nothing
21578 // (same flag the NONE arm sets).
21579 sb128_none = true;
21580 let horz = part128 == PARTITION_HORZ;
21581 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
21582 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
21583 for i in 0..2 {
21584 let at = if horz {
21585 (at128.0 + i * 4, at128.1)
21586 } else {
21587 (at128.0, at128.1 + i * 4)
21588 };
21589 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
21590 if i > 0
21591 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
21592 {
21593 break;
21594 }
21595 // Each half reads its OWN `cdef_idx` literal
21596 // (libaom `read_cdef` keys the `-1` test on the
21597 // block's own `MB_MODE_INFO`, and the two halves have
21598 // different ones).
21599 fctx.cdef_transmitted.with(|c| c.set(false));
21600 decode_block_128rect(
21601 &mut dec,
21602 &mut cdfs,
21603 &mut neighbours,
21604 at,
21605 bw,
21606 bh,
21607 &mut y,
21608 &mut u,
21609 &mut v,
21610 base_q_idx,
21611 enable_filter_intra,
21612 allow_screen_content_tools,
21613 tx_select,
21614 reduced_tx_set, fctx,
21615 )?;
21616 }
21617 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
21618 // unit it covers (the inter path's own fan-out).
21619 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
21620 fctx.cdef_idx_grid.with(|g| {
21621 let mut g = g.borrow_mut();
21622 let cols = fctx.cdef_sb_cols.with(|c| c.get());
21623 if cols == 0 {
21624 return;
21625 }
21626 for (src, dst) in if horz {
21627 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
21628 } else {
21629 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
21630 } {
21631 let (si, di) = (
21632 (q_r + src.0) * cols + q_c + src.1,
21633 (q_r + dst.0) * cols + q_c + dst.1,
21634 );
21635 if q_c + src.1 < cols
21636 && q_c + dst.1 < cols
21637 && si < g.len()
21638 && di < g.len()
21639 {
21640 g[di] = g[si];
21641 }
21642 }
21643 });
21644 continue;
21645 }
21646 if part128 == PARTITION_NONE {
21647 // One 128x128 intra block: four TX_64X64 luma units and a
21648 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
21649 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
21650 // block). No CfL, no filter intra, no palette at this size --
21651 // [`read_intra_mode`]'s own size gates already say so.
21652 sb128_none = true;
21653 fctx.cdef_transmitted.with(|c| c.set(false));
21654 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
21655 decode_block(
21656 &mut dec,
21657 &mut cdfs,
21658 &mut neighbours,
21659 at128,
21660 SB * 2,
21661 TxbSet::Luma64,
21662 TxbSet::Chroma32,
21663 TX32,
21664 TX32,
21665 (&scan32, &scan32),
21666 false,
21667 &mut y,
21668 &mut u,
21669 &mut v,
21670 base_q_idx,
21671 enable_filter_intra,
21672 allow_screen_content_tools,
21673 allow_intrabc,
21674 &scan32,
21675 &scan16,
21676 &scan8,
21677 &scan4,
21678 tx_select,
21679 reduced_tx_set, fctx,
21680 )?;
21681 // libaom writes one `cdef_strength` into the block's own
21682 // `MB_MODE_INFO`, which every mi cell of the block --
21683 // hence all four 64x64 CDEF units -- points at; our grid
21684 // is per-unit, so the read (which only ever lands in the
21685 // top-left unit, `read_cdef`'s index 0) is copied across.
21686 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
21687 fctx.cdef_idx_grid.with(|g| {
21688 let mut g = g.borrow_mut();
21689 let cols = fctx.cdef_sb_cols.with(|c| c.get());
21690 if cols > 0 && q_r * cols + q_c < g.len() {
21691 let idx = g[q_r * cols + q_c];
21692 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
21693 let i = (q_r + dr) * cols + q_c + dc;
21694 if q_c + dc < cols && i < g.len() {
21695 g[i] = idx;
21696 }
21697 }
21698 }
21699 });
21700 continue;
21701 }
21702 }
21703 if !sb128 {
21704 crate::restoration::read_lr(
21705 &mut dec,
21706 &mut cdfs,
21707 lr,
21708 &mut lr_grid,
21709 &mut lr_reference,
21710 sb_r * SB_MI,
21711 sb_c * SB_MI,
21712 SB_MI, fctx,
21713 );
21714 }
21715 fctx.cdef_transmitted.with(|c| c.set(false));
21716 let at = (sb_r as usize * 4, sb_c as usize * 4);
21717 let ctx = neighbours.partition_ctx(at, SB);
21718 let (has_cols, has_rows) = (
21719 sb_c * SB_MI + SB_MI / 2 < mi_cols,
21720 sb_r * SB_MI + SB_MI / 2 < mi_rows,
21721 );
21722 // Recomputed at this superblock's own half (spec
21723 // `decode_partition`): a full alphabet symbol when both halves are
21724 // inside the true frame, a single gathered bit when just one is
21725 // (the superblock cannot be left whole, so this is forced split),
21726 // and nothing at all (SPLIT inferred, no bits) when neither is —
21727 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
21728 // three-way write exactly.
21729 let part = if has_cols && has_rows {
21730 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
21731 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21732 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
21733 }
21734 p
21735 } else {
21736 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
21737 // the unmerged lane-golomb r1): the gathered bit IS the
21738 // partition -- libaom `ec_read_partition_impl` returns
21739 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
21740 // Forcing SPLIT desynced the last superblock row of every
21741 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
21742 // the first block of that row.
21743 match (has_cols, has_rows) {
21744 (true, false) => {
21745 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
21746 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
21747 bump_edge32(4 + b.min(1) as usize);
21748 bump_edge_part(b.min(1) as usize);
21749 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
21750 }
21751 (false, true) => {
21752 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
21753 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
21754 bump_edge32(4 + b.min(1) as usize);
21755 bump_edge_part(b.min(1) as usize);
21756 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
21757 }
21758 _ => {
21759 bump_edge_both_cut(2);
21760 PARTITION_SPLIT
21761 }
21762 }
21763 };
21764 match part {
21765 PARTITION_NONE => {
21766 decode_block(
21767 &mut dec,
21768 &mut cdfs,
21769 &mut neighbours,
21770 at,
21771 SB,
21772 TxbSet::Luma64,
21773 TxbSet::Chroma32,
21774 TX32,
21775 TX32,
21776 (&scan32, &scan32),
21777 false,
21778 &mut y,
21779 &mut u,
21780 &mut v,
21781 base_q_idx,
21782 enable_filter_intra,
21783 allow_screen_content_tools,
21784 allow_intrabc,
21785 &scan32,
21786 &scan16,
21787 &scan8,
21788 &scan4,
21789 tx_select,
21790 reduced_tx_set, fctx,
21791 )?;
21792 }
21793 PARTITION_SPLIT => {
21794 for q in 0..4 {
21795 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
21796 if r32 >= rows32 || c32 >= cols32 {
21797 continue;
21798 }
21799 let at32 = (r32 as usize * 2, c32 as usize * 2);
21800 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
21801 let (has_cols32, has_rows32) = (
21802 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
21803 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
21804 );
21805 let part32 = if has_cols32 && has_rows32 {
21806 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
21807 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21808 let (rng, _) = dec.debug_state();
21809 eprintln!(
21810 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
21811 r32 * BLOCK_MI,
21812 c32 * BLOCK_MI
21813 );
21814 }
21815 p
21816 } else {
21817 // lane-hgkf r1: the 32-level frame-edge bit is the
21818 // partition too (same libaom reader as the
21819 // superblock level above).
21820 match (has_cols32, has_rows32) {
21821 (true, false) => {
21822 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
21823 let b = dec.symbol_fixed(&gather(
21824 &cdfs.partition_w32[ctx32],
21825 VERT_ALIKE,
21826 ));
21827 bump_edge32(b.min(1) as usize);
21828 bump_edge_part(2 + b.min(1) as usize);
21829 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
21830 }
21831 (false, true) => {
21832 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
21833 let b = dec.symbol_fixed(&gather(
21834 &cdfs.partition_w32[ctx32],
21835 HORZ_ALIKE,
21836 ));
21837 bump_edge32(b.min(1) as usize);
21838 bump_edge_part(2 + b.min(1) as usize);
21839 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
21840 }
21841 _ => {
21842 bump_edge_both_cut(1);
21843 PARTITION_SPLIT
21844 }
21845 }
21846 };
21847 match part32 {
21848 PARTITION_NONE => {
21849 decode_block(
21850 &mut dec,
21851 &mut cdfs,
21852 &mut neighbours,
21853 at32,
21854 BLOCK,
21855 TxbSet::Luma32,
21856 TxbSet::Chroma16,
21857 TX32,
21858 TX16,
21859 (&scan32, &scan16),
21860 true,
21861 &mut y,
21862 &mut u,
21863 &mut v,
21864 base_q_idx,
21865 enable_filter_intra,
21866 allow_screen_content_tools,
21867 allow_intrabc,
21868 &scan32,
21869 &scan16,
21870 &scan8,
21871 &scan4,
21872 tx_select,
21873 reduced_tx_set, fctx,
21874 )?;
21875 }
21876 PARTITION_SPLIT => {
21877 for sub in 0..4 {
21878 let (sr, sc) =
21879 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
21880 if (sr as u32) * SUB_MI >= mi_rows
21881 || (sc as u32) * SUB_MI >= mi_cols
21882 {
21883 continue;
21884 }
21885 let (has_cols16, has_rows16) = (
21886 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
21887 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
21888 );
21889 let at16 = (sr, sc);
21890 let ctx16 = neighbours.partition_ctx(at16, SUB);
21891 if has_cols16 && has_rows16 {
21892 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
21893 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21894 eprintln!(
21895 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
21896 at16.0, at16.1
21897 );
21898 }
21899 if part16 == PARTITION_NONE {
21900 decode_block(
21901 &mut dec,
21902 &mut cdfs,
21903 &mut neighbours,
21904 at16,
21905 SUB,
21906 TxbSet::Luma16,
21907 TxbSet::Chroma8,
21908 TX16,
21909 TX8,
21910 (&scan16, &scan8),
21911 true,
21912 &mut y,
21913 &mut u,
21914 &mut v,
21915 base_q_idx,
21916 enable_filter_intra,
21917 allow_screen_content_tools,
21918 allow_intrabc,
21919 &scan32,
21920 &scan16,
21921 &scan8,
21922 &scan4,
21923 tx_select,
21924 reduced_tx_set, fctx,
21925 )?;
21926 continue;
21927 }
21928 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
21929 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
21930 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
21931 // `decode_partition` visit order (decodeframe.c):
21932 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
21933 // HORZ_B: top 16x8, BL 8x8, BR 8x8
21934 // VERT_A: TL 8x8, BL 8x8, right 8x16
21935 // VERT_B: left 8x16, TR 8x8, BR 8x8
21936 // The squares go through `decode_leaf8`, the strip through
21937 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
21938 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
21939 // used refuses the non-skip case at this size). Both writers keep
21940 // mi-granular mode/skip/palette records, so a later block's
21941 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
21942 // 16x16 cell.
21943 //
21944 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
21945 // top-right neighbour is the partition's own not-yet-decoded
21946 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
21947 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
21948 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
21949 let arm = part16 - PARTITION_HORZ_A;
21950 bump_ab16(arm);
21951 if part16 == PARTITION_VERT_B {
21952 hit!(VERT_B_INTRA_HITS);
21953 }
21954 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
21955 Some(crate::encode::Reach::vert_ab_partition())
21956 } else {
21957 None
21958 };
21959 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
21960 macro_rules! ab_leaf8 {
21961 ($mi:expr, $prev:expr) => {
21962 decode_leaf8(
21963 &mut dec,
21964 &mut cdfs,
21965 &mut neighbours,
21966 at16,
21967 $mi,
21968 (&scan8, &scan4),
21969 $prev,
21970 &mut y,
21971 &mut u,
21972 &mut v,
21973 base_q_idx,
21974 enable_filter_intra,
21975 allow_screen_content_tools,
21976 allow_intrabc,
21977 tx_select,
21978 reduced_tx_set, fctx,
21979 )?
21980 };
21981 }
21982 macro_rules! ab_strip {
21983 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
21984 decode_leaf_rect(
21985 &mut dec,
21986 &mut cdfs,
21987 &mut neighbours,
21988 at16,
21989 $mi,
21990 $bw,
21991 $bh,
21992 $prev,
21993 &mut y,
21994 &mut u,
21995 &mut v,
21996 enable_filter_intra,
21997 allow_screen_content_tools,
21998 base_q_idx,
21999 tx_select,
22000 reduced_tx_set, fctx,
22001 )?
22002 };
22003 }
22004 let tl = (mi_row0, mi_col0);
22005 let tr = (mi_row0, mi_col0 + 2);
22006 let bl = (mi_row0 + 2, mi_col0);
22007 let br = (mi_row0 + 2, mi_col0 + 2);
22008 let mut done: Vec<((usize, usize), usize)> = Vec::new();
22009 match part16 {
22010 PARTITION_HORZ_A => {
22011 let m_tl = ab_leaf8!(tl, done.last().copied());
22012 done.push((tl, m_tl));
22013 let m_tr = ab_leaf8!(tr, done.last().copied());
22014 done.push((tr, m_tr));
22015 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
22016 done.push((bl, m_bot));
22017 }
22018 PARTITION_HORZ_B => {
22019 let m_top = ab_strip!(tl, 16, 8, None);
22020 done.push((tl, m_top));
22021 let m_bl = ab_leaf8!(bl, done.last().copied());
22022 done.push((bl, m_bl));
22023 let m_br = ab_leaf8!(br, done.last().copied());
22024 done.push((br, m_br));
22025 }
22026 PARTITION_VERT_A => {
22027 let m_tl = ab_leaf8!(tl, done.last().copied());
22028 done.push((tl, m_tl));
22029 let m_bl = ab_leaf8!(bl, done.last().copied());
22030 done.push((bl, m_bl));
22031 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
22032 done.push((tr, m_right));
22033 }
22034 _ => {
22035 let m_left = ab_strip!(tl, 8, 16, None);
22036 done.push((tl, m_left));
22037 let m_tr = ab_leaf8!(tr, done.last().copied());
22038 done.push((tr, m_tr));
22039 let m_br = ab_leaf8!(br, done.last().copied());
22040 done.push((br, m_br));
22041 }
22042 }
22043 // Same coarse-slot write-back the real SPLIT path takes: the
22044 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
22045 // sub-block on the parent's bottom / right edge (the mi-exact map
22046 // above wins wherever it has an entry).
22047 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
22048 continue;
22049 }
22050 if part16 == PARTITION_HORZ {
22051 hit!(HORZ_VERT_INTRA_HITS);
22052 let (mi_row0, mi_col0) = (
22053 sr as u32 * SUB_MI,
22054 sc as u32 * SUB_MI,
22055 );
22056 let top = (mi_row0 as usize, mi_col0 as usize);
22057 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
22058 let mode_top = decode_leaf_rect(
22059 &mut dec,
22060 &mut cdfs,
22061 &mut neighbours,
22062 at16,
22063 top,
22064 16,
22065 8,
22066 None,
22067 &mut y,
22068 &mut u,
22069 &mut v,
22070 enable_filter_intra,
22071 allow_screen_content_tools,
22072 base_q_idx,
22073 tx_select,
22074 reduced_tx_set, fctx,
22075 )?;
22076 let mode_bot = decode_leaf_rect(
22077 &mut dec,
22078 &mut cdfs,
22079 &mut neighbours,
22080 at16,
22081 bot,
22082 16,
22083 8,
22084 Some((top, mode_top)),
22085 &mut y,
22086 &mut u,
22087 &mut v,
22088 enable_filter_intra,
22089 allow_screen_content_tools,
22090 base_q_idx,
22091 tx_select,
22092 reduced_tx_set, fctx,
22093 )?;
22094 neighbours.above_mode[sc] = mode_bot;
22095 neighbours.left_mode[sr] = mode_bot;
22096 continue;
22097 }
22098 if part16 == PARTITION_VERT {
22099 hit!(HORZ_VERT_INTRA_HITS);
22100 let (mi_row0, mi_col0) = (
22101 sr as u32 * SUB_MI,
22102 sc as u32 * SUB_MI,
22103 );
22104 let left = (mi_row0 as usize, mi_col0 as usize);
22105 let right = (mi_row0 as usize, mi_col0 as usize + 2);
22106 let mode_left = decode_leaf_rect(
22107 &mut dec,
22108 &mut cdfs,
22109 &mut neighbours,
22110 at16,
22111 left,
22112 8,
22113 16,
22114 None,
22115 &mut y,
22116 &mut u,
22117 &mut v,
22118 enable_filter_intra,
22119 allow_screen_content_tools,
22120 base_q_idx,
22121 tx_select,
22122 reduced_tx_set, fctx,
22123 )?;
22124 let mode_right = decode_leaf_rect(
22125 &mut dec,
22126 &mut cdfs,
22127 &mut neighbours,
22128 at16,
22129 right,
22130 8,
22131 16,
22132 Some((left, mode_left)),
22133 &mut y,
22134 &mut u,
22135 &mut v,
22136 enable_filter_intra,
22137 allow_screen_content_tools,
22138 base_q_idx,
22139 tx_select,
22140 reduced_tx_set, fctx,
22141 )?;
22142 neighbours.above_mode[sc] = mode_right;
22143 neighbours.left_mode[sr] = mode_right;
22144 continue;
22145 }
22146 if part16 == PARTITION_HORZ_4
22147 || part16 == PARTITION_VERT_4
22148 {
22149 decode_rect4_16(
22150 &mut dec,
22151 &mut cdfs,
22152 &mut neighbours,
22153 at16,
22154 part16 == PARTITION_HORZ_4,
22155 &mut y,
22156 &mut u,
22157 &mut v,
22158 enable_filter_intra,
22159 allow_screen_content_tools,
22160 base_q_idx,
22161 tx_select,
22162 reduced_tx_set, fctx,
22163 )?;
22164 continue;
22165 }
22166 // lane-r14 r2 (verifier note): every
22167 // one of the 10 symbols this CDF can
22168 // produce is handled above, so SPLIT
22169 // is the only value that reaches
22170 // here -- the refusal that used to
22171 // stand here was unreachable and is
22172 // gone from `refusal_inventory`.
22173 debug_assert_eq!(part16, PARTITION_SPLIT);
22174 // A real (non-straddle) SPLIT of a
22175 // whole 16x16 into four 8x8 leaves --
22176 // the same recursion the straddle
22177 // path below already runs when the
22178 // true frame edge forces it, just
22179 // over all four positions instead of
22180 // the one or two the edge leaves.
22181 let (mi_row0, mi_col0) =
22182 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22183 // Each 8x8 leaf's intra-mode context
22184 // must see its own siblings: the
22185 // bottom-left leaf's ABOVE neighbour
22186 // is leaf 0, not the previously
22187 // decoded leaf 1 (and the bottom-right
22188 // leaf's above is leaf 1, while
22189 // `prev_leaf` only ever carried the
22190 // immediately preceding one). The
22191 // coarse `above_mode`/`left_mode`
22192 // arrays hold one slot per 16x16, so
22193 // the sibling modes are swapped in
22194 // around each leaf call and restored
22195 // after; the loop tail writes the last
22196 // leaf's mode as before.
22197 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22198 for i in 0..4 {
22199 let (mr, mc) =
22200 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
22201 let leaf_mi = (mr as usize, mc as usize);
22202 let li = i as usize;
22203 let saved_modes =
22204 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22205 if li >= 2 {
22206 if let Some((below, _)) = sib_modes[li - 2] {
22207 neighbours.above_mode[sc] = below;
22208 }
22209 }
22210 if li % 2 == 1 {
22211 if let Some((_, right)) = sib_modes[li - 1] {
22212 neighbours.left_mode[sr] = right;
22213 }
22214 }
22215 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22216 let part8 =
22217 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22218 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22219 eprintln!(
22220 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
22221 );
22222 }
22223 let leaf_mode = if part8 == PARTITION_NONE {
22224 decode_leaf8(
22225 &mut dec,
22226 &mut cdfs,
22227 &mut neighbours,
22228 at16,
22229 leaf_mi,
22230 (&scan8, &scan4),
22231 None,
22232 &mut y,
22233 &mut u,
22234 &mut v,
22235 base_q_idx,
22236 enable_filter_intra,
22237 allow_screen_content_tools,
22238 allow_intrabc,
22239 tx_select,
22240 reduced_tx_set, fctx,
22241 ).map(|m| (m, m))?
22242 } else if part8 == PARTITION_SPLIT {
22243 decode_leaf_split4(
22244 &mut dec,
22245 &mut cdfs,
22246 &mut neighbours,
22247 at16,
22248 leaf_mi,
22249 &scan4,
22250 None,
22251 &mut y,
22252 &mut u,
22253 &mut v,
22254 base_q_idx,
22255 enable_filter_intra,
22256 allow_intrabc,
22257 reduced_tx_set, fctx,
22258 )?
22259 } else if part8 == PARTITION_HORZ
22260 || part8 == PARTITION_VERT
22261 {
22262 decode_leaf_rect8(
22263 &mut dec,
22264 &mut cdfs,
22265 &mut neighbours,
22266 at16,
22267 leaf_mi,
22268 part8 == PARTITION_VERT,
22269 &scan4,
22270 &mut y,
22271 &mut u,
22272 &mut v,
22273 base_q_idx,
22274 enable_filter_intra,
22275 allow_intrabc,
22276 tx_select,
22277 reduced_tx_set, fctx,
22278 )?
22279 } else {
22280 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
22281 };
22282 neighbours.above_mode[sc] = saved_modes.0;
22283 neighbours.left_mode[sr] = saved_modes.1;
22284 sib_modes[li] = Some(leaf_mode);
22285 }
22286 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
22287 neighbours.above_mode[sc] = below;
22288 }
22289 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
22290 neighbours.left_mode[sr] = right;
22291 }
22292 continue;
22293 }
22294 // The true edge falls inside this 16x16
22295 // leaf itself (mod-32==8 target sizes,
22296 // lane-av1-rect): one axis only -- an 8x8
22297 // leaf never itself straddles, so the
22298 // block splits cleanly along whichever
22299 // axis is short.
22300 // lane-edgeboth r1: when the true frame
22301 // edge cuts BOTH axes libaom's
22302 // `decode_partition` takes
22303 // `else if (!has_rows && !has_cols)
22304 // partition = PARTITION_SPLIT;` -- no
22305 // symbol of any kind is read, and the four
22306 // 8x8 children are then visited by the
22307 // same loop below, whose
22308 // `mr < mi_rows && mc < mi_cols` filter IS
22309 // libaom's own
22310 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
22311 // early return, so the three out-of-frame
22312 // quadrants get no neighbour or tx-grid
22313 // write.
22314 if !has_cols16 && !has_rows16 {
22315 bump_edge_both_cut(0);
22316 } else {
22317 // lane-golomb r1 (class
22318 // `parsed-then-discarded`): the gathered
22319 // bit IS the partition -- 0 names
22320 // PARTITION_HORZ (resp. VERT), only 1 is
22321 // SPLIT (libaom `ec_read_partition_impl`).
22322 // This path can only walk the four SPLIT
22323 // leaves, so a 0 refuses by name instead
22324 // of desyncing.
22325 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
22326 let edge_split = if has_cols16 {
22327 dec.symbol_fixed(&gather(
22328 &cdfs.partition_w16[ctx16],
22329 VERT_ALIKE,
22330 ))
22331 } else {
22332 dec.symbol_fixed(&gather(
22333 &cdfs.partition_w16[ctx16],
22334 HORZ_ALIKE,
22335 ))
22336 };
22337 // lane-hgkf r1: slots 2/3 of
22338 // [`EDGE_PART_HITS`], the gate's proof the
22339 // non-SPLIT edge arm actually decoded.
22340 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
22341 if edge_split == 0 {
22342 // lane-oddh r1: the strip IS decodable
22343 // -- libaom's `decode_partition` codes
22344 // only the FIRST half of an edge
22345 // HORZ/VERT (the second call is
22346 // guarded by the same has_rows/
22347 // has_cols test that made the
22348 // partition non-square), so one
22349 // 16x8 (resp. 8x16) strip covers the
22350 // whole visible band of a frame whose
22351 // height (resp. width) is 8 mod 16 --
22352 // the user's 3840x1608 film.
22353 hit!(HORZ_VERT_INTRA_HITS);
22354 hit!(EDGE_RECT_STRIP_HITS);
22355 let (mi_row0, mi_col0) =
22356 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22357 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
22358 let mode = decode_leaf_rect(
22359 &mut dec,
22360 &mut cdfs,
22361 &mut neighbours,
22362 at16,
22363 (mi_row0 as usize, mi_col0 as usize),
22364 bw,
22365 bh,
22366 None,
22367 &mut y,
22368 &mut u,
22369 &mut v,
22370 enable_filter_intra,
22371 allow_screen_content_tools,
22372 base_q_idx,
22373 tx_select,
22374 reduced_tx_set, fctx,
22375 )?;
22376 neighbours.above_mode[sc] = mode;
22377 neighbours.left_mode[sr] = mode;
22378 continue;
22379 }
22380 }
22381 let (mi_row0, mi_col0) =
22382 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22383 let leaf_positions: Vec<(u32, u32)> = (0..4)
22384 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
22385 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
22386 .collect();
22387 // See the sibling-mode note in the clean
22388 // SPLIT path above.
22389 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22390 for (mr, mc) in leaf_positions {
22391 let leaf_mi = (mr as usize, mc as usize);
22392 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
22393 as usize;
22394 let saved_modes =
22395 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22396 if li >= 2 {
22397 if let Some((below, _)) = sib_modes[li - 2] {
22398 neighbours.above_mode[sc] = below;
22399 }
22400 }
22401 if li % 2 == 1 {
22402 if let Some((_, right)) = sib_modes[li - 1] {
22403 neighbours.left_mode[sr] = right;
22404 }
22405 }
22406 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22407 let pre8 = dec.debug_state().0;
22408 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22409 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22410 eprintln!(
22411 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
22412 );
22413 }
22414 let leaf_mode = if part8 == PARTITION_NONE {
22415 decode_leaf8(
22416 &mut dec,
22417 &mut cdfs,
22418 &mut neighbours,
22419 at16,
22420 leaf_mi,
22421 (&scan8, &scan4),
22422 None,
22423 &mut y,
22424 &mut u,
22425 &mut v,
22426 base_q_idx,
22427 enable_filter_intra,
22428 allow_screen_content_tools,
22429 allow_intrabc,
22430 tx_select,
22431 reduced_tx_set, fctx,
22432 ).map(|m| (m, m))?
22433 } else if part8 == PARTITION_SPLIT {
22434 decode_leaf_split4(
22435 &mut dec,
22436 &mut cdfs,
22437 &mut neighbours,
22438 at16,
22439 leaf_mi,
22440 &scan4,
22441 None,
22442 &mut y,
22443 &mut u,
22444 &mut v,
22445 base_q_idx,
22446 enable_filter_intra,
22447 allow_intrabc,
22448 reduced_tx_set, fctx,
22449 )?
22450 } else if part8 == PARTITION_HORZ
22451 || part8 == PARTITION_VERT
22452 {
22453 decode_leaf_rect8(
22454 &mut dec,
22455 &mut cdfs,
22456 &mut neighbours,
22457 at16,
22458 leaf_mi,
22459 part8 == PARTITION_VERT,
22460 &scan4,
22461 &mut y,
22462 &mut u,
22463 &mut v,
22464 base_q_idx,
22465 enable_filter_intra,
22466 allow_intrabc,
22467 tx_select,
22468 reduced_tx_set, fctx,
22469 )?
22470 } else {
22471 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
22472 };
22473 neighbours.above_mode[sc] = saved_modes.0;
22474 neighbours.left_mode[sr] = saved_modes.1;
22475 sib_modes[li] = Some(leaf_mode);
22476 }
22477 // `record()`'s `above_mode`/`left_mode`
22478 // write is a no-op at an 8x8 leaf's own
22479 // side, so force the write once the whole
22480 // 16x16 slot's leaves are done, from the
22481 // last leaf (mirrors the writer's r15
22482 // fix).
22483 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
22484 neighbours.above_mode[sc] = below;
22485 }
22486 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
22487 neighbours.left_mode[sr] = right;
22488 }
22489 }
22490 }
22491 PARTITION_HORZ => {
22492 // lane-intradisp r1: two true 32x16 strips.
22493 decode_block_rect(
22494 &mut dec,
22495 &mut cdfs,
22496 &mut neighbours,
22497 at32,
22498 32,
22499 16,
22500 &mut y,
22501 &mut u,
22502 &mut v,
22503 enable_filter_intra,
22504 allow_screen_content_tools,
22505 base_q_idx,
22506 tx_select,
22507 reduced_tx_set, fctx,
22508 )?;
22509 if !has_rows32 {
22510 bump_edge32(2);
22511 }
22512 // lane-hgkf r1: at the frame edge only the first half of the strip is
22513 // coded (libaom `decode_partition` guards the second half with the same
22514 // test that made this partition non-square).
22515 if has_rows32 {
22516 decode_block_rect(
22517 &mut dec,
22518 &mut cdfs,
22519 &mut neighbours,
22520 (at32.0 + 1, at32.1),
22521 32,
22522 16,
22523 &mut y,
22524 &mut u,
22525 &mut v,
22526 enable_filter_intra,
22527 allow_screen_content_tools,
22528 base_q_idx,
22529 tx_select,
22530 reduced_tx_set, fctx,
22531 )?;
22532 }
22533 }
22534 PARTITION_VERT => {
22535 // lane-intradisp r1: mirror of PARTITION_HORZ
22536 // above with width/height swapped.
22537 decode_block_rect(
22538 &mut dec,
22539 &mut cdfs,
22540 &mut neighbours,
22541 at32,
22542 16,
22543 32,
22544 &mut y,
22545 &mut u,
22546 &mut v,
22547 enable_filter_intra,
22548 allow_screen_content_tools,
22549 base_q_idx,
22550 tx_select,
22551 reduced_tx_set, fctx,
22552 )?;
22553 if !has_cols32 {
22554 bump_edge32(3);
22555 }
22556 // lane-hgkf r1: at the frame edge only the first half of the strip is
22557 // coded (libaom `decode_partition` guards the second half with the same
22558 // test that made this partition non-square).
22559 if has_cols32 {
22560 decode_block_rect(
22561 &mut dec,
22562 &mut cdfs,
22563 &mut neighbours,
22564 (at32.0, at32.1 + 1),
22565 16,
22566 32,
22567 &mut y,
22568 &mut u,
22569 &mut v,
22570 enable_filter_intra,
22571 allow_screen_content_tools,
22572 base_q_idx,
22573 tx_select,
22574 reduced_tx_set, fctx,
22575 )?;
22576 }
22577 }
22578 PARTITION_HORZ_A => {
22579 // lane-part32 r1: two 16x16 squares on top +
22580 // a true 32x16 strip below (mirrors
22581 // decode_inter_block's cd6cb6d HORZ_A: TL,
22582 // TR, bottom strip).
22583 hit!(INTRA_HORZ_A_HITS);
22584 decode_block(
22585 &mut dec,
22586 &mut cdfs,
22587 &mut neighbours,
22588 at32,
22589 SUB,
22590 TxbSet::Luma16,
22591 TxbSet::Chroma8,
22592 TX16,
22593 TX8,
22594 (&scan16, &scan8),
22595 true,
22596 &mut y,
22597 &mut u,
22598 &mut v,
22599 base_q_idx,
22600 enable_filter_intra,
22601 allow_screen_content_tools,
22602 allow_intrabc,
22603 &scan32,
22604 &scan16,
22605 &scan8,
22606 &scan4,
22607 tx_select,
22608 reduced_tx_set, fctx,
22609 )?;
22610 decode_block(
22611 &mut dec,
22612 &mut cdfs,
22613 &mut neighbours,
22614 (at32.0, at32.1 + 1),
22615 SUB,
22616 TxbSet::Luma16,
22617 TxbSet::Chroma8,
22618 TX16,
22619 TX8,
22620 (&scan16, &scan8),
22621 true,
22622 &mut y,
22623 &mut u,
22624 &mut v,
22625 base_q_idx,
22626 enable_filter_intra,
22627 allow_screen_content_tools,
22628 allow_intrabc,
22629 &scan32,
22630 &scan16,
22631 &scan8,
22632 &scan4,
22633 tx_select,
22634 reduced_tx_set, fctx,
22635 )?;
22636 decode_block_rect(
22637 &mut dec,
22638 &mut cdfs,
22639 &mut neighbours,
22640 (at32.0 + 1, at32.1),
22641 32,
22642 16,
22643 &mut y,
22644 &mut u,
22645 &mut v,
22646 enable_filter_intra,
22647 allow_screen_content_tools,
22648 base_q_idx,
22649 tx_select,
22650 reduced_tx_set, fctx,
22651 )?;
22652 }
22653 PARTITION_HORZ_B => {
22654 // lane-part32 r1: a true 32x16 strip on top +
22655 // two 16x16 squares below (mirrors HORZ_A
22656 // with the strip/squares order flipped, same
22657 // shape as libaom decode_partition's HORZ_B).
22658 hit!(INTRA_HORZ_B_HITS);
22659 decode_block_rect(
22660 &mut dec,
22661 &mut cdfs,
22662 &mut neighbours,
22663 at32,
22664 32,
22665 16,
22666 &mut y,
22667 &mut u,
22668 &mut v,
22669 enable_filter_intra,
22670 allow_screen_content_tools,
22671 base_q_idx,
22672 tx_select,
22673 reduced_tx_set, fctx,
22674 )?;
22675 decode_block(
22676 &mut dec,
22677 &mut cdfs,
22678 &mut neighbours,
22679 (at32.0 + 1, at32.1),
22680 SUB,
22681 TxbSet::Luma16,
22682 TxbSet::Chroma8,
22683 TX16,
22684 TX8,
22685 (&scan16, &scan8),
22686 true,
22687 &mut y,
22688 &mut u,
22689 &mut v,
22690 base_q_idx,
22691 enable_filter_intra,
22692 allow_screen_content_tools,
22693 allow_intrabc,
22694 &scan32,
22695 &scan16,
22696 &scan8,
22697 &scan4,
22698 tx_select,
22699 reduced_tx_set, fctx,
22700 )?;
22701 decode_block(
22702 &mut dec,
22703 &mut cdfs,
22704 &mut neighbours,
22705 (at32.0 + 1, at32.1 + 1),
22706 SUB,
22707 TxbSet::Luma16,
22708 TxbSet::Chroma8,
22709 TX16,
22710 TX8,
22711 (&scan16, &scan8),
22712 true,
22713 &mut y,
22714 &mut u,
22715 &mut v,
22716 base_q_idx,
22717 enable_filter_intra,
22718 allow_screen_content_tools,
22719 allow_intrabc,
22720 &scan32,
22721 &scan16,
22722 &scan8,
22723 &scan4,
22724 tx_select,
22725 reduced_tx_set, fctx,
22726 )?;
22727 }
22728 PARTITION_VERT_A => {
22729 // lane-part32 r1: mirror of HORZ_A with
22730 // width/height swapped (TL, BL, right 16x32
22731 // strip).
22732 hit!(INTRA_VERT_A_HITS);
22733 let _vert_ab = crate::encode::Reach::vert_ab_partition();
22734 decode_block(
22735 &mut dec,
22736 &mut cdfs,
22737 &mut neighbours,
22738 at32,
22739 SUB,
22740 TxbSet::Luma16,
22741 TxbSet::Chroma8,
22742 TX16,
22743 TX8,
22744 (&scan16, &scan8),
22745 true,
22746 &mut y,
22747 &mut u,
22748 &mut v,
22749 base_q_idx,
22750 enable_filter_intra,
22751 allow_screen_content_tools,
22752 allow_intrabc,
22753 &scan32,
22754 &scan16,
22755 &scan8,
22756 &scan4,
22757 tx_select,
22758 reduced_tx_set, fctx,
22759 )?;
22760 decode_block(
22761 &mut dec,
22762 &mut cdfs,
22763 &mut neighbours,
22764 (at32.0 + 1, at32.1),
22765 SUB,
22766 TxbSet::Luma16,
22767 TxbSet::Chroma8,
22768 TX16,
22769 TX8,
22770 (&scan16, &scan8),
22771 true,
22772 &mut y,
22773 &mut u,
22774 &mut v,
22775 base_q_idx,
22776 enable_filter_intra,
22777 allow_screen_content_tools,
22778 allow_intrabc,
22779 &scan32,
22780 &scan16,
22781 &scan8,
22782 &scan4,
22783 tx_select,
22784 reduced_tx_set, fctx,
22785 )?;
22786 decode_block_rect(
22787 &mut dec,
22788 &mut cdfs,
22789 &mut neighbours,
22790 (at32.0, at32.1 + 1),
22791 16,
22792 32,
22793 &mut y,
22794 &mut u,
22795 &mut v,
22796 enable_filter_intra,
22797 allow_screen_content_tools,
22798 base_q_idx,
22799 tx_select,
22800 reduced_tx_set, fctx,
22801 )?;
22802 }
22803 PARTITION_VERT_B => {
22804 // lane-part32 r1: a true 16x32 strip on the
22805 // left + two 16x16 squares on the right
22806 // (libaom decode_partition VERT_B: left
22807 // strip, TR, BR).
22808 hit!(INTRA_VERT_B_HITS);
22809 let _vert_ab = crate::encode::Reach::vert_ab_partition();
22810 decode_block_rect(
22811 &mut dec,
22812 &mut cdfs,
22813 &mut neighbours,
22814 at32,
22815 16,
22816 32,
22817 &mut y,
22818 &mut u,
22819 &mut v,
22820 enable_filter_intra,
22821 allow_screen_content_tools,
22822 base_q_idx,
22823 tx_select,
22824 reduced_tx_set, fctx,
22825 )?;
22826 decode_block(
22827 &mut dec,
22828 &mut cdfs,
22829 &mut neighbours,
22830 (at32.0, at32.1 + 1),
22831 SUB,
22832 TxbSet::Luma16,
22833 TxbSet::Chroma8,
22834 TX16,
22835 TX8,
22836 (&scan16, &scan8),
22837 true,
22838 &mut y,
22839 &mut u,
22840 &mut v,
22841 base_q_idx,
22842 enable_filter_intra,
22843 allow_screen_content_tools,
22844 allow_intrabc,
22845 &scan32,
22846 &scan16,
22847 &scan8,
22848 &scan4,
22849 tx_select,
22850 reduced_tx_set, fctx,
22851 )?;
22852 decode_block(
22853 &mut dec,
22854 &mut cdfs,
22855 &mut neighbours,
22856 (at32.0 + 1, at32.1 + 1),
22857 SUB,
22858 TxbSet::Luma16,
22859 TxbSet::Chroma8,
22860 TX16,
22861 TX8,
22862 (&scan16, &scan8),
22863 true,
22864 &mut y,
22865 &mut u,
22866 &mut v,
22867 base_q_idx,
22868 enable_filter_intra,
22869 allow_screen_content_tools,
22870 allow_intrabc,
22871 &scan32,
22872 &scan16,
22873 &scan8,
22874 &scan4,
22875 tx_select,
22876 reduced_tx_set, fctx,
22877 )?;
22878 }
22879 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
22880 // lane-tx64x16 r3: the 1:4 pair at the 32x32
22881 // level -- four 32x8 (or 8x32) strips in
22882 // raster order, `quarter_step` = 2 mi, with
22883 // libaom `decode_partition`'s own `i > 0`
22884 // frame-edge break.
22885 let horz = part32 == PARTITION_HORZ_4;
22886 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
22887 let mut prev: Option<((usize, usize), usize)> = None;
22888 for i in 0..4 {
22889 let strip_mi = if horz {
22890 (base_mi.0 + i * 2, base_mi.1)
22891 } else {
22892 (base_mi.0, base_mi.1 + i * 2)
22893 };
22894 if i > 0
22895 && (strip_mi.0 >= mi_rows as usize
22896 || strip_mi.1 >= mi_cols as usize)
22897 {
22898 break;
22899 }
22900 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
22901 let (mode, _uv) = decode_block_rect4(
22902 &mut dec,
22903 &mut cdfs,
22904 &mut neighbours,
22905 strip_mi,
22906 bw,
22907 bh,
22908 prev,
22909 &mut y,
22910 &mut u,
22911 &mut v,
22912 enable_filter_intra,
22913 allow_screen_content_tools,
22914 base_q_idx,
22915 tx_select, fctx,
22916 )?;
22917 prev = Some((strip_mi, mode));
22918 }
22919 }
22920 _ => {
22921 return Err(unsupported(format!(
22922 "a 32x32 partition type this decoder does not code (value={part32})"
22923 )));
22924 }
22925 }
22926 }
22927 }
22928 PARTITION_HORZ => {
22929 // lane-sbpart r2: two true 64x32 strips.
22930 decode_block_rect64(
22931 &mut dec,
22932 &mut cdfs,
22933 &mut neighbours,
22934 at,
22935 64,
22936 32,
22937 &mut y,
22938 &mut u,
22939 &mut v,
22940 enable_filter_intra,
22941 allow_screen_content_tools,
22942 base_q_idx,
22943 tx_select,
22944 reduced_tx_set, fctx,
22945 )?;
22946 if !has_rows {
22947 bump_edge32(6);
22948 }
22949 // lane-golomb r1: at the frame edge only the first half of the
22950 // strip is coded (libaom `decode_partition` guards the second
22951 // with the same has_rows test that made this partition non-square).
22952 if has_rows {
22953 decode_block_rect64(
22954 &mut dec,
22955 &mut cdfs,
22956 &mut neighbours,
22957 (at.0 + 2, at.1),
22958 64,
22959 32,
22960 &mut y,
22961 &mut u,
22962 &mut v,
22963 enable_filter_intra,
22964 allow_screen_content_tools,
22965 base_q_idx,
22966 tx_select,
22967 reduced_tx_set, fctx,
22968 )?;
22969 }
22970 }
22971 PARTITION_VERT => {
22972 // lane-sbpart r2: mirror of PARTITION_HORZ above with
22973 // width/height swapped.
22974 decode_block_rect64(
22975 &mut dec,
22976 &mut cdfs,
22977 &mut neighbours,
22978 at,
22979 32,
22980 64,
22981 &mut y,
22982 &mut u,
22983 &mut v,
22984 enable_filter_intra,
22985 allow_screen_content_tools,
22986 base_q_idx,
22987 tx_select,
22988 reduced_tx_set, fctx,
22989 )?;
22990 if !has_cols {
22991 bump_edge32(7);
22992 }
22993 // lane-golomb r1: at the frame edge only the first half of the
22994 // strip is coded (libaom `decode_partition` guards the second
22995 // with the same has_cols test that made this partition non-square).
22996 if has_cols {
22997 decode_block_rect64(
22998 &mut dec,
22999 &mut cdfs,
23000 &mut neighbours,
23001 (at.0, at.1 + 2),
23002 32,
23003 64,
23004 &mut y,
23005 &mut u,
23006 &mut v,
23007 enable_filter_intra,
23008 allow_screen_content_tools,
23009 base_q_idx,
23010 tx_select,
23011 reduced_tx_set, fctx,
23012 )?;
23013 }
23014 }
23015 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
23016 // lane-part32 r4: the four superblock-level AB arms, each
23017 // two 32x32 squares plus one 64x32/32x64 strip, in
23018 // libaom's own `decode_partition` order (decodeframe.c:
23019 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
23020 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
23021 // TR, BR). The pieces are exactly the ones already proven
23022 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
23023 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
23024 hit_do! {
23025 SB_AB_HITS.with(|c| {
23026 let mut h = c.get();
23027 h[part - PARTITION_HORZ_A] += 1;
23028 c.set(h);
23029 });
23030 }
23031 // lane-part32 r5: only the two VERTICAL arms reorder the
23032 // square sub-blocks (TL, BL, TR, BR), so only they switch
23033 // libaom's `has_tr`/`has_bl` tables.
23034 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
23035 .then(crate::encode::Reach::vert_ab_partition);
23036 macro_rules! square32 {
23037 ($at:expr) => {
23038 decode_block(
23039 &mut dec,
23040 &mut cdfs,
23041 &mut neighbours,
23042 $at,
23043 BLOCK,
23044 TxbSet::Luma32,
23045 TxbSet::Chroma16,
23046 TX32,
23047 TX16,
23048 (&scan32, &scan16),
23049 true,
23050 &mut y,
23051 &mut u,
23052 &mut v,
23053 base_q_idx,
23054 enable_filter_intra,
23055 allow_screen_content_tools,
23056 allow_intrabc,
23057 &scan32,
23058 &scan16,
23059 &scan8,
23060 &scan4,
23061 tx_select,
23062 reduced_tx_set, fctx,
23063 )?
23064 };
23065 }
23066 macro_rules! strip64 {
23067 ($at:expr, $bw:expr, $bh:expr) => {
23068 decode_block_rect64(
23069 &mut dec,
23070 &mut cdfs,
23071 &mut neighbours,
23072 $at,
23073 $bw,
23074 $bh,
23075 &mut y,
23076 &mut u,
23077 &mut v,
23078 enable_filter_intra,
23079 allow_screen_content_tools,
23080 base_q_idx,
23081 tx_select,
23082 reduced_tx_set, fctx,
23083 )?
23084 };
23085 }
23086 let (br, bc) = (at.0 + 2, at.1 + 2);
23087 match part {
23088 PARTITION_HORZ_A => {
23089 square32!(at);
23090 square32!((at.0, bc));
23091 strip64!((br, at.1), 64, 32);
23092 }
23093 PARTITION_HORZ_B => {
23094 strip64!(at, 64, 32);
23095 square32!((br, at.1));
23096 square32!((br, bc));
23097 }
23098 PARTITION_VERT_A => {
23099 square32!(at);
23100 square32!((br, at.1));
23101 strip64!((at.0, bc), 32, 64);
23102 }
23103 _ => {
23104 strip64!(at, 32, 64);
23105 square32!((at.0, bc));
23106 square32!((br, bc));
23107 }
23108 }
23109 }
23110 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
23111 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
23112 // 16x64) strips in raster order. `decode_partition`
23113 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
23114 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
23115 // frame edge for `i > 0`, so a partial superblock codes
23116 // only the strips whose origin is inside the frame.
23117 let horz = part == PARTITION_HORZ_4;
23118 for i in 0..4 {
23119 let step_mi = i * (SB_MI as usize / 4);
23120 let (this_r_mi, this_c_mi) = if horz {
23121 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
23122 } else {
23123 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
23124 };
23125 if i > 0
23126 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
23127 {
23128 break;
23129 }
23130 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
23131 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
23132 decode_block_rect64(
23133 &mut dec,
23134 &mut cdfs,
23135 &mut neighbours,
23136 strip_at,
23137 bw,
23138 bh,
23139 &mut y,
23140 &mut u,
23141 &mut v,
23142 enable_filter_intra,
23143 allow_screen_content_tools,
23144 base_q_idx,
23145 tx_select,
23146 reduced_tx_set, fctx,
23147 )?;
23148 }
23149 }
23150 _ => {
23151 return Err(unsupported(
23152 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
23153 ));
23154 }
23155 }
23156 }
23157 }
23158 if waving {
23159 wave_submit(fctx, wave_job.0, wave_job.1);
23160 }
23161 // lane-timeline: this tile's last symbol is read here; its wavefront
23162 // workers are drained by `_wave`'s drop at the end of the iteration.
23163 crate::timeline::tile_done();
23164 flush_recon(fctx, &mut y, &mut u, &mut v);
23165
23166 if tile_num == tile_info.context_update_tile_id {
23167 result_cdfs = cdfs;
23168 }
23169 }
23170 crate::timeline::recon_done();
23171
23172 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
23173 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
23174 // that isolate whether a decode-order frame's mismatch already exists
23175 // in reconstruction (this dump) vs is introduced by the loop filter
23176 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
23177 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
23178 if crate::envflags::env_flag!("EC_OBMC")
23179 || crate::envflags::env_flag!("EC_TRACE_MODE")
23180 || crate::envflags::env_flag!("EC_PRED")
23181 {
23182 eprintln!(
23183 "EC_PICT idx={}",
23184 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
23185 );
23186 }
23187 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
23188 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") {
23189 use std::io::Write;
23190 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
23191 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
23192 let narrow = |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
23193 let _ = f.write_all(&narrow(&y));
23194 let _ = f.write_all(&narrow(&u));
23195 let _ = f.write_all(&narrow(&v));
23196 }
23197 } else {
23198 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
23199 }
23200 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") {
23201 use std::io::Write;
23202 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
23203 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
23204 let crop_wide = |plane: &PlaneBuf<'_>| -> Vec<u8> {
23205 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
23206 for row in 0..plane.true_height {
23207 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
23208 }
23209 out
23210 };
23211 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
23212 let _ = f.write_all(&crop_wide(&y));
23213 let _ = f.write_all(&crop_wide(&u));
23214 let _ = f.write_all(&crop_wide(&v));
23215 }
23216 }
23217 // lane-av1fwd: the encoder's filter search re-decodes this same key
23218 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
23219 // on the shape whose tail is the two filter calls and nothing else.
23220 if superres(fctx).is_none()
23221 && !(0..3).any(|p| {
23222 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
23223 && lr.loop_restoration_size[p] != 0
23224 })
23225 {
23226 capture_filter_replay(
23227 &y,
23228 &u,
23229 &v,
23230 &neighbours,
23231 frame_width as usize,
23232 frame_height as usize,
23233 width,
23234 height,
23235 true_width,
23236 true_height,
23237 );
23238 }
23239 apply_deblock(
23240 &mut y,
23241 &mut u,
23242 &mut v,
23243 loop_filter,
23244 &neighbours,
23245 frame_width as usize,
23246 frame_height as usize, fctx,
23247 );
23248 // lane-perf4: loop restoration is the only reader of the pre-CDEF planes,
23249 // and a frame that restores nothing copied every plane twice for nothing
23250 // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside
23251 // [`crate::restoration::apply_loop_restoration_plane`], which returns its
23252 // input unchanged when the plane's type is `None`). Clone only when some
23253 // plane actually restores.
23254 let lr_active = (0..3).any(|p| {
23255 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
23256 && lr.loop_restoration_size[p] != 0
23257 });
23258 let deblocked =
23259 lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1)));
23260 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
23261 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
23262 // dump above these bisect WHICH filter stage introduced a mismatch.
23263 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
23264 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
23265 apply_cdef(
23266 &mut y,
23267 &mut u,
23268 &mut v,
23269 cdef,
23270 &neighbours,
23271 (frame_width as usize, frame_height as usize), fctx,
23272 );
23273 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
23274 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
23275 capture_stages(&y, &u, &v, deblocked.as_ref(), fctx);
23276 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
23277 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
23278 // the horizontal upscale runs HERE -- after CDEF, before loop
23279 // restoration, not after the whole filter chain. Both the post-CDEF
23280 // frame and the post-deblock frame that LR substitutes at its stripe
23281 // boundaries are upscaled (`save_deblock_boundary_lines` runs
23282 // `av1_upscale_normative_rows` over its saved rows when the frame is
23283 // scaled), so every LR coordinate from here on is in upscaled space.
23284 let mut deblocked = deblocked;
23285 let mut lr_w = frame_width as usize;
23286 if let Some((upscaled_w, _)) = superres(fctx) {
23287 let bd = u32::from(bit_depth(fctx));
23288 let (uw, fw, fh) = (upscaled_w as usize, frame_width as usize, frame_height as usize);
23289 let up = |p: &PlaneBuf<'_>, in_w: usize, in_h: usize, out_w: usize| PlaneBuf {
23290 data: std::borrow::Cow::Owned(crate::superres::upscale_plane_strided(
23291 &p.data, p.width, in_w, in_h, p.true_width, out_w, bd,
23292 )),
23293 width: out_w,
23294 height: in_h,
23295 true_width: out_w,
23296 true_height: in_h,
23297 tile_x0: 0,
23298 tile_y0: 0,
23299 tile_x1: out_w,
23300 tile_y1: in_h,
23301 };
23302 let (cw, ch, cuw) = (fw.div_ceil(2), fh.div_ceil(2), uw.div_ceil(2));
23303 y = up(&y, fw, fh, uw);
23304 u = up(&u, cw, ch, cuw);
23305 v = up(&v, cw, ch, cuw);
23306 if let Some((dy, du, dv)) = deblocked.take() {
23307 deblocked = Some((up(&dy, fw, fh, uw), up(&du, cw, ch, cuw), up(&dv, cw, ch, cuw)));
23308 }
23309 lr_w = uw;
23310 crate::superres::note_upscaled_picture();
23311 }
23312 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {
23313 apply_loop_restoration(
23314 &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,
23315 (lr_w, frame_height as usize), fctx,
23316 );
23317 }
23318 if let Some((db_y, db_u, db_v)) = deblocked {
23319 // LIFO pool: return in reverse so the next frame's `y`/`u`/`v`
23320 // snapshots pop buffers of their own size and never resize.
23321 scratch_return(db_v.data.into_owned());
23322 scratch_return(db_u.data.into_owned());
23323 scratch_return(db_y.data.into_owned());
23324 }
23325 crate::timeline::filters_done();
23326
23327 let (fw, fh) = (lr_w, frame_height as usize);
23328 // An upscaled frame is already at its final size with no mi-aligned
23329 // margin beyond it (the upscale consumed those columns), so the
23330 // wide-margin stash below has nothing left to hand out.
23331 let (true_width, true_height) = if superres(fctx).is_some() {
23332 (fw, fh)
23333 } else {
23334 (true_width, true_height)
23335 };
23336 if fw == width && fh == height {
23337 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
23338 return Ok((
23339 Picture {
23340 width,
23341 height,
23342 y: y.data.into_owned(),
23343 u: u.data.into_owned(),
23344 v: v.data.into_owned(),
23345 },
23346 result_cdfs,
23347 ));
23348 }
23349 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
23350 let mut out = Vec::with_capacity(w * h);
23351 for row in 0..h {
23352 out.extend(plane.data[row * plane.width..][..w].iter().copied());
23353 }
23354 out
23355 };
23356 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
23357 // is the real reconstructed extent -- columns `[fw, true_width)` hold
23358 // genuine decoded samples (the last coding block straddles the frame
23359 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
23360 // libaom's superres upscale runs on that buffer's own border-extended
23361 // margin, so it reads those real columns, not a synthetic replicate of
23362 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
23363 // aomenc 43->64 stream pinned column-by-column against libaom's own
23364 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
23365 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
23366 // decoder used before was off by 1 at the columns the tap window
23367 // reaches into that real margin; `None` when there is no margin (this
23368 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
23369 // non-superres frame whose width just isn't 32-block aligned).
23370 fctx.last_frame_wide_margin.with(|m| {
23371 *m.borrow_mut() = if true_width > fw || true_height > fh {
23372 let yc = crop(&y, true_width, true_height);
23373 if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") {
23374 use std::io::Write;
23375 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
23376 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
23377 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
23378 // corner-cut: this diagnostic dump stays 8-bit-narrowed
23379 // regardless of the stream's real bit depth (debug-only,
23380 // never read by a gate); widen if a >8-bit margin dump
23381 // is ever needed.
23382 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
23383 }
23384 }
23385 Some(Picture {
23386 width: true_width,
23387 height: true_height,
23388 y: yc,
23389 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
23390 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
23391 })
23392 } else {
23393 None
23394 }
23395 });
23396 Ok((
23397 Picture {
23398 width: fw,
23399 height: fh,
23400 y: crop_owned(y, fw, fh),
23401 u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)),
23402 v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)),
23403 },
23404 result_cdfs,
23405 ))
23406}
23407
23408/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
23409/// -- `above`/`left` are the neighbour's own resolved index for this
23410/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
23411/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
23412/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
23413/// block itself has a second reference) -- lane-av1idx: a stale "this
23414/// decoder never codes a compound reference" assumption baked this to
23415/// always-0, which desynced the CDF context bucket (not the decoded value
23416/// outright, hence small pixel deltas rather than a hard desync) the moment
23417/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
23418/// filter frame.
23419fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
23420 let base = dir * 8 + if is_compound { 4 } else { 0 };
23421 let term = if left == above {
23422 left
23423 } else if left == 3 {
23424 above
23425 } else if above == 3 {
23426 left
23427 } else {
23428 3
23429 };
23430 base + term as usize
23431}
23432
23433/// Resolves the interpolation filter kernel(s) an inter block's motion
23434/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
23435/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
23436/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
23437/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
23438/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
23439/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
23440/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
23441/// which forces `EIGHTTAP` without reading anything.
23442#[allow(clippy::too_many_arguments)]
23443fn resolve_interp_filter(
23444 dec: &mut SymbolDecoder,
23445 cdfs: &mut Cdfs,
23446 interp_fixed: Option<mc::InterpFilterKind>,
23447 enable_dual_filter: bool,
23448 force_regular: bool,
23449 above: [u8; 2],
23450 left: [u8; 2],
23451 is_compound: bool,
23452) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
23453 if let Some(kind) = interp_fixed {
23454 return (kind, kind, [3, 3]);
23455 }
23456 if force_regular {
23457 return (
23458 mc::InterpFilterKind::Regular,
23459 mc::InterpFilterKind::Regular,
23460 [0, 0],
23461 );
23462 }
23463 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
23464 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
23465 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
23466 // "horizontal then vertical" despite `predict_with_filters`' own
23467 // `h_kind`/`v_kind` argument order, which is why this function returns
23468 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
23469 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
23470 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
23471 eprintln!(
23472 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
23473 &cdfs.switchable_interp[ctx0][..3]
23474 );
23475 }
23476 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
23477 let sym1 = if enable_dual_filter {
23478 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
23479 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
23480 eprintln!(
23481 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
23482 &cdfs.switchable_interp[ctx1][..3]
23483 );
23484 }
23485 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
23486 } else {
23487 sym0
23488 };
23489 if enable_dual_filter && sym0 != sym1 {
23490 hit!(DUAL_FILTER_DIFF_HITS);
23491 }
23492 if crate::envflags::env_flag!("EC_TRACE_MODE") {
23493 eprintln!(
23494 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
23495 dec.debug_state().0
23496 );
23497 }
23498 (
23499 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
23500 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
23501 [sym0, sym1],
23502 )
23503}
23504
23505/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
23506/// duplicating [`crate::tile`]'s private copy of the same rule.
23507pub(crate) fn intra_inter_ctx(
23508 has_above: bool,
23509 has_left: bool,
23510 above_inter: bool,
23511 left_inter: bool,
23512) -> usize {
23513 match (has_above, has_left) {
23514 (true, true) => {
23515 let (above_intra, left_intra) = (!above_inter, !left_inter);
23516 if above_intra && left_intra {
23517 3
23518 } else {
23519 usize::from(above_intra || left_intra)
23520 }
23521 }
23522 (true, false) => 2 * usize::from(!above_inter),
23523 (false, true) => 2 * usize::from(!left_inter),
23524 (false, false) => 0,
23525 }
23526}
23527
23528/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
23529/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
23530/// bits start counting from.
23531fn mv_class_base(class: usize) -> i32 {
23532 if class == 0 { 0 } else { 2i32 << (class + 2) }
23533}
23534
23535/// One motion vector component's non-zero diff (spec 5.11.32
23536/// `read_mv_component`), the inverse of [`crate::tile`]'s private
23537/// `write_mv_component`.
23538fn read_mv_component(
23539 dec: &mut SymbolDecoder,
23540 c: &mut MvComponentCdfs,
23541 allow_high_precision_mv: bool,
23542 force_integer_mv: bool,
23543) -> i32 {
23544 let sign = dec.symbol(&mut c.sign);
23545 let class = dec.symbol(&mut c.class);
23546 let local = if class == 0 {
23547 let bit = dec.symbol(&mut c.class0_bit);
23548 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
23549 // forces integer motion vectors -- implicitly `3` (the top
23550 // fractional value) rather than read, else every symbol after it
23551 // in the tile desyncs by one read.
23552 let fr = if force_integer_mv {
23553 3
23554 } else {
23555 dec.symbol(&mut c.class0_fr[bit])
23556 };
23557 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
23558 // high-precision motion vectors, else implicitly 1 (the low bit
23559 // stays at half-pel precision) -- this crate's own writer always
23560 // leaves the flag off, but a foreign stream can set it per frame.
23561 let hp = if allow_high_precision_mv {
23562 dec.symbol(&mut c.class0_hp)
23563 } else {
23564 1
23565 };
23566 (bit << 3) | (fr << 1) | hp
23567 } else {
23568 let mut d = 0;
23569 for i in 0..class {
23570 d |= dec.symbol(&mut c.bit[i]) << i;
23571 }
23572 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
23573 // `mv_class0_fr` above.
23574 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
23575 let hp = if allow_high_precision_mv {
23576 dec.symbol(&mut c.hp)
23577 } else {
23578 1
23579 };
23580 (d << 3) | (fr << 1) | hp
23581 };
23582 let mag = mv_class_base(class) + local as i32 + 1;
23583 if sign == 1 { -mag } else { mag }
23584}
23585
23586/// A motion vector coded as a residual against `pred` (spec 5.11.32

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