forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB68cf7a6Tahinli2 months ago2975 commits

decode.rs23506 lines, 1.7 MiBHistoryRawDownload
1//! Software decoder for this crate's own key-frame tile payloads (spec 5.11),
2//! the reader half of [`crate::tile`]'s writer.
3//!
4//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is
5//! touching its partition search), so nothing here imports its private
6//! helpers: the handful of `pub(crate)` items it already exposes
7//! ([`crate::tile::block_grid`], [`crate::tile::has_half`],
8//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused,
9//! and everything else (the partition/coefficient context arithmetic, the
10//! scan table) is a from-spec reimplementation kept in step with the writer by
11//! the gate tests below rather than by sharing code with it.
12//!
13//! # Scope (round 1)
14//! Key frames only, and only the shapes the encoder actually still needs to
15//! prove itself against: every coded block is `DC_PRED` (this crate's mode
16//! search names other intra modes, but a decoder for those needs the
17//! directional-prediction edge-reach plumbing [`crate::intra::predict`]
18//! already carries; wiring it up is round 2), never skipped, and every
19//! superblock is a whole number of 64x64 units (a frame whose true edge falls
20//! inside one, forcing the gathered-CDF partial-superblock path, is round 2
21//! too). Anything outside that refuses with [`Error::unsupported`] rather than
22//! silently miscoding.
23use crate::hits::{hit, hit_do};
24
25use ec_av1_syntax::{
26 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
27 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
28};
29use ec_core::{Error, Result};
30
31/// Per-frame decode state, one instance per decoded stream (lane-thread1).
32///
33/// Every field here used to be a `thread_local!` static, which made a decode a
34/// function of the calling THREAD's history rather than of the bitstream alone
35/// -- and made frame-parallel decoding impossible, since a worker thread sees
36/// empty state. The cells keep exactly the interior mutability the statics
37/// had, so every read/write site is byte-identical; what changes is WHERE the
38/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
39/// the decode call graph.
40///
41/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
42/// exactly one thread's decode, and is never shared between workers.
43/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
44/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
45/// (pre-restoration) samples, at the decoder's own plane stride.
46pub(crate) struct FilterStages {
47 /// Post-deblock, pre-CDEF planes (Y, U, V).
48 pub(crate) deblocked: [Vec<u16>; 3],
49 /// Post-CDEF, pre-restoration planes (Y, U, V).
50 pub(crate) cdefed: [Vec<u16>; 3],
51 /// Each plane's stride (and so its width in the buffers above).
52 pub(crate) stride: [usize; 3],
53}
54
55/// Takes whatever the last capturing decode left (see
56/// [`FrameCtx::capture_stages`]).
57#[allow(dead_code)] // read from the encoder's loop restoration search
58pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
59 fctx.stages.borrow_mut().take()
60}
61
62pub(crate) struct FrameCtx {
63 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
64 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
65 /// restoration search (spec 7.17 reads both: the stripe interior from
66 /// the post-CDEF plane, its 3-row border from the post-deblock one).
67 /// Off for every decode but that search, and off it costs one bool read
68 /// per frame and not a single copy.
69 pub(crate) capture_stages: std::cell::Cell<bool>,
70 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
71 pub(crate) sb128_flag: std::cell::Cell<bool>,
72 /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
73 /// motion compensation of THIS frame runs, already resolved to a kernel.
74 /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
75 /// trial and recon could only ever build a REGULAR prediction whatever
76 /// the frame header said; it lives here (and is copied by
77 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
78 /// kernel the frame header wrote instead of the default.
79 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
80 /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
81 /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
82 /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
83 /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
84 /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
85 /// (`blockd.h`)).
86 pub(crate) lossless_flag: std::cell::Cell<bool>,
87 pub(crate) cdef_bits: std::cell::Cell<u8>,
88 pub(crate) bit_depth: std::cell::Cell<u8>,
89 pub(crate) superres: std::cell::Cell<(u32, u32)>,
90 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
91 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
92 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
93 pub(crate) delta_q_present: std::cell::Cell<bool>,
94 pub(crate) delta_q_res: std::cell::Cell<i32>,
95 pub(crate) current_q_idx: std::cell::Cell<i32>,
96 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
97 pub(crate) delta_lf_present: std::cell::Cell<bool>,
98 pub(crate) delta_lf_res: std::cell::Cell<i32>,
99 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
100 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
101 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
102 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
103 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
104 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
105 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
106 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
107 pub(crate) cur_segment_id: std::cell::Cell<u8>,
108 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
109 pub(crate) tx_select_inter: std::cell::Cell<bool>,
110 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
111 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
112 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
113 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
114 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
115 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
116 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
117 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
118 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
119 pub(crate) inter_last_mc:
120 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
121 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
122 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
123 pub(crate) reach_sb_px: std::cell::Cell<usize>,
124 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
125 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
126 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
127 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
128 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
129 /// so a superblock's records do not regrow the vector from nothing.
130 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
131 /// lane-recoparse: the coefficient grids of the recorded ops above, one
132 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
133 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
134 /// before the op is published, read only by whoever replays that op, and
135 /// handed over WITH the ops at every drain point ([`wave_submit`],
136 /// [`flush_recon`]), so offsets are always relative to the live arena.
137 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
138 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
139 /// path (a submitted job's arena travels to its worker instead).
140 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
141 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
142 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
143 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
144 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
145 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
146 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
147 /// `None` while the queue is in use (wavefront workers) and outside a
148 /// tile. See [`push_op`].
149 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
150 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
151 /// writes are handed to, at more than one reconstruction thread.
152 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
153 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
154 /// thread last handed a superblock to the wavefront.
155 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
156}
157
158impl std::fmt::Debug for FrameCtx {
159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 f.write_str("FrameCtx")
161 }
162}
163
164impl FrameCtx {
165 /// A fresh context, every field at the default its thread-local
166 /// predecessor was born with.
167 pub(crate) fn new() -> Self {
168 Self {
169 // A DECODER context is seeded from the stream alone: every real
170 // decode overwrites this from the parsed sequence header
171 // (`set_sb128`, stream.rs). The encoder's own contexts start at
172 // the size this process encodes -- see [`FrameCtx::for_encoder`].
173 sb128_flag: std::cell::Cell::new(false),
174 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
175 lossless_flag: std::cell::Cell::new(false),
176 cdef_bits: std::cell::Cell::new(0),
177 bit_depth: std::cell::Cell::new(8),
178 superres: std::cell::Cell::new((0, 8)),
179 cdef_transmitted: std::cell::Cell::new(false),
180 cdef_sb_cols: std::cell::Cell::new(0),
181 capture_stages: std::cell::Cell::new(false),
182 stages: std::cell::RefCell::new(None),
183 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
184 delta_q_present: std::cell::Cell::new(false),
185 delta_q_res: std::cell::Cell::new(1),
186 current_q_idx: std::cell::Cell::new(0),
187 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
188 y_dc: 0,
189 u_dc: 0,
190 u_ac: 0,
191 v_dc: 0,
192 v_ac: 0,
193 }),
194 delta_lf_present: std::cell::Cell::new(false),
195 delta_lf_res: std::cell::Cell::new(1),
196 delta_lf_multi: std::cell::Cell::new(false),
197 current_delta_lf: std::cell::Cell::new([0; 4]),
198 seg: std::cell::RefCell::new(SegmentationParams::default()),
199 seg_ids: std::cell::RefCell::new(Vec::new()),
200 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
201 seg_mi_dims: std::cell::Cell::new((0, 0)),
202 above_seg_pred: std::cell::RefCell::new(Vec::new()),
203 left_seg_pred: std::cell::RefCell::new(Vec::new()),
204 cur_segment_id: std::cell::Cell::new(0),
205 seg_tile_origin: std::cell::Cell::new((0, 0)),
206 tx_select_inter: std::cell::Cell::new(false),
207 reduced_tx_set_inter: std::cell::Cell::new(true),
208 enable_filter_intra_inter: std::cell::Cell::new(false),
209 palette_pred: std::cell::RefCell::new(None),
210 intrabc_mi_grid: std::cell::RefCell::new(None),
211 intrabc_dv: std::cell::Cell::new(None),
212 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
213 intrabc_chroma_tx: std::cell::Cell::new(None),
214 intra_in_inter_mode: std::cell::Cell::new(None),
215 inter_strip_chroma: std::cell::Cell::new(None),
216 inter_last_mc: std::cell::Cell::new(None),
217 enable_edge_filter: std::cell::Cell::new(false),
218 last_frame_wide_margin: std::cell::RefCell::new(None),
219 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
220 grain_bit_depth: std::cell::Cell::new(8),
221 recon_ops: std::cell::RefCell::new(Vec::new()),
222 recon_spare: std::cell::RefCell::new(Vec::new()),
223 coeff_arena: std::cell::RefCell::new(Vec::new()),
224 coeff_spare: std::cell::RefCell::new(Vec::new()),
225 pred_arena: std::cell::RefCell::new(Vec::new()),
226 pred_spare: std::cell::RefCell::new(Vec::new()),
227 recon_planes: std::cell::Cell::new(None),
228 wave: std::cell::RefCell::new(None),
229 wave_mark: std::cell::Cell::new(None),
230 }
231 }
232
233 /// A context for the ENCODER's own trial decodes: it starts at the
234 /// superblock size this process encodes (`crate::encode::sb128_on`) so
235 /// the mode search's `Reach` and the filter search's internal decodes
236 /// agree with the tile writer. A decoder never reads that knob -- doing
237 /// so coupled every decode to the encoder's process-global and raced the
238 /// 128-superblock decode gates against the encoder witness.
239 pub(crate) fn for_encoder() -> Self {
240 let ctx = Self::new();
241 let on = crate::encode::sb128_on();
242 ctx.sb128_flag.set(on);
243 ctx.reach_sb_px.set(if on { 128 } else { crate::encode::SUPERBLOCK });
244 ctx
245 }
246}
247
248/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
249/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
250/// `with` still wins for the scratch pools and gate counters that stay
251/// thread-local.
252pub(crate) trait WithRef {
253 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
254 f(self)
255 }
256}
257impl<T: ?Sized> WithRef for T {}
258
259/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
260///
261/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
262/// and the post-decode filter chain reads exactly these fields: the bit depth
263/// (every kernel's clamp and threshold shift), the segmentation table
264/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
265/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
266/// default -- a field that turns out to be read after all shows up as a hash
267/// mismatch in
268/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
269pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
270 let out = FrameCtx::new();
271 out.bit_depth.set(fctx.bit_depth.get());
272 out.interp_filter.set(fctx.interp_filter.get());
273 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
274 out.superres.set(fctx.superres.get());
275 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
276 out.seg.replace(fctx.seg.borrow().clone());
277 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
278 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
279 // worker (`encode::search_tiles`) gets its context from here, so dropping
280 // it made every worker search at 64 while the calling thread searched at
281 // 128 -- the bytes a frame came out as then depended on the tile thread
282 // count under `EC_AV1_SB128`.
283 out.sb128_flag.set(fctx.sb128_flag.get());
284 out.reach_sb_px.set(fctx.reach_sb_px.get());
285 out
286}
287
288use crate::cdf;
289use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
290use crate::encode::{Picture, Reach};
291use crate::intra::predict;
292use crate::mc;
293use crate::msac::SymbolDecoder;
294use crate::mvstack::{
295 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
296 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
297 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
298 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
299 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
300};
301use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
302use crate::transform::{TxType, dequant_and_inverse_typed_wh};
303
304const PARTITION_NONE: usize = 0;
305const PARTITION_HORZ: usize = 1;
306const PARTITION_VERT: usize = 2;
307const PARTITION_SPLIT: usize = 3;
308const PARTITION_HORZ_A: usize = 4;
309const PARTITION_HORZ_B: usize = 5;
310const PARTITION_VERT_A: usize = 6;
311const PARTITION_VERT_B: usize = 7;
312const PARTITION_HORZ_4: usize = 8;
313const PARTITION_VERT_4: usize = 9;
314const SB_MI: u32 = 16;
315const BLOCK_MI: u32 = 8;
316
317// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
318// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
319// superblock's own top-left mi?", the loop-restoration read's unit span, the
320// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
321// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
322// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
323// inside a 128 superblock).
324thread_local! {
325 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
326 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
327 /// prints gigabytes otherwise). Unset = every frame, as before.
328 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
329 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
330}
331
332/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
333/// that frame's DECODE-order index.
334pub fn set_coeff_trace_frame(idx: usize) {
335 COEFF_TRACE_FRAME.with(|c| {
336 if c.get().is_none() {
337 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
338 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
339 // unset: keep tracing every frame, as before this rung existed
340 Err(_) => usize::MAX - 1,
341 };
342 c.set(Some(want));
343 }
344 });
345 COEFF_TRACE_CUR.with(|c| c.set(idx));
346 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
347 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
348 }
349}
350
351pub(crate) fn coeff_trace_on() -> bool {
352 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
353 return false;
354 }
355 match COEFF_TRACE_FRAME.with(|c| c.get()) {
356 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
357 // env var unset: trace every frame.
358 None => true,
359 Some(w) if w >= usize::MAX - 1 => true,
360 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
361 }
362}
363
364
365/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
366pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
367 fctx.sb128_flag.with(|c| c.set(v));
368 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
369}
370
371/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
372pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
373 fctx.lossless_flag.with(|c| c.set(v));
374}
375
376/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
377pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
378 fctx.lossless_flag.with(|c| c.get())
379}
380
381/// The transform side a block of `side` pixels codes: its own (capped at the
382/// caller's own largest) normally, 4 on a lossless frame, where libaom's
383/// `read_tx_size` returns TX_4X4 before it looks at anything else
384/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
385/// TX_4X4;`).
386pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
387 if lossless(fctx) { 4 } else { px }
388}
389
390/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
391/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
392/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
393/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
394/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
395pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
396 if lossless(fctx) {
397 bw <= 8 && bh <= 8
398 } else {
399 bw <= 32 && bh <= 32
400 }
401}
402
403fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
404 fctx.sb128_flag.with(|c| c.get())
405}
406
407/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
408pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
409 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
410}
411
412// How many real 128-level partition symbols this decoder has read, and how
413// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
414// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
415thread_local! {
416 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
417 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
418 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
419}
420
421/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
422/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
423/// 5.11.4), which this decoder used to read and throw away.
424#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
425pub(crate) fn part128_gathered_symbols() -> usize {
426 PART128_GATHERED_SYMBOLS.with(|c| c.get())
427}
428
429/// Current value of [`PART128_SYMBOLS`].
430#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
431pub(crate) fn part128_symbols() -> usize {
432 PART128_SYMBOLS.with(|c| c.get())
433}
434
435/// Current value of [`PART128_SPLIT_HITS`].
436#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
437pub(crate) fn part128_split_hits() -> usize {
438 PART128_SPLIT_HITS.with(|c| c.get())
439}
440
441/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
442/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
443/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
444/// the 64/32 levels sum 6.
445pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
446 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
447 [32768 - split, 32768, 0]
448}
449
450/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
451pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
452pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
453
454// How many `use_filter_intra` symbols this decoder has read as `1`, across
455// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
456// tests read (before/after, not the absolute value) to prove a stream
457// actually exercised the filter-intra predictor rather than silently
458// skipping it.
459thread_local! {
460 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
461 const { std::cell::Cell::new(0) };
462}
463
464/// Current value of [`FILTER_INTRA_HITS`].
465#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
466pub(crate) fn filter_intra_hits() -> usize {
467 FILTER_INTRA_HITS.with(|c| c.get())
468}
469
470// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
471// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
472// `read_filter_intra_mode_info` call), which no gate exercised before this
473// round -- every inter gate recipe passed `--enable-filter-intra=0`.
474thread_local! {
475 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
476 const { std::cell::Cell::new(0) };
477}
478
479/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
480#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
481pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
482 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
483}
484
485// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
486// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
487// arms refused a nonzero luma delta before this round, and no inter gate
488// enabled `--enable-angle-delta` (aomenc's own default is 1).
489thread_local! {
490 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
491 const { std::cell::Cell::new(0) };
492 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
493 const { std::cell::Cell::new(0) };
494}
495
496/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
497#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
498pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
499 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
500}
501
502/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
503#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
504pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
505 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
506}
507
508// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
509// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
510// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
511// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
512thread_local! {
513 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
514 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
515 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
516}
517
518thread_local! {
519 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
520}
521
522/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
523/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
525pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
526 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
527}
528
529/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
530/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
531#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
532pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
533 (
534 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
535 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
536 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
537 )
538}
539
540// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
541// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
542// frame-level flag through the recursive block decode -- `0` (the default)
543// makes every call a true no-op, matching every existing gate stream's
544// `cdef_bits == 0` behaviour exactly.
545// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
546// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
547// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
548// blocks every non-8-bit stream from reaching a decode call, so this is `8`
549// on every path that runs today -- threading it now (rather than the literal
550// `8`) is stage 1 of widening past that refusal without re-deriving every
551// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
552// depth (this decoder's own internal choice, matches dav1d/libaom).
553/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
554/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
555pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
556 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
557}
558/// The current stream's bit depth, for callers (e.g. dequant) that need the
559/// raw value rather than the derived clamp bound.
560pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
561 fctx.bit_depth.with(std::cell::Cell::get)
562}
563/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
564/// [`crate::stream`]'s decode loop.
565pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
566 fctx.bit_depth.with(|c| c.set(bit_depth));
567}
568
569 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
570 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
571 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
572 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
573 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
574 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
575 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
576 /// superres arms). Set once per frame from [`crate::stream`]'s decode
577 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
578 /// so a later frame never inherits it.
579
580/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
581/// `denom` 8) for a frame that is not superres-scaled.
582pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
583 fctx.superres.with(|c| c.set((upscaled_width, denom)));
584}
585
586/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
587/// (libaom `av1_superres_scaled`), else `None`.
588pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
589 let (w, d) = fctx.superres.with(std::cell::Cell::get);
590 (w > 0 && d != 8).then_some((w, d))
591}
592// Whether this superblock's single CDEF unit (this decoder has no 128x128
593// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
594// read -- reset to `false` at the top of each superblock in the two tile
595// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
596// Number of superblock columns in the current tile's grid, so
597// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
598// [`CDEF_IDX_GRID`].
599// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
600// which of the header's `1 << cdef.bits` strength pairs applies to that
601// superblock's samples.
602// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
603// has read, across every call on the current thread -- the gate's proof that a
604// `cdef_bits > 0` stream actually reached the new reader rather than every
605// superblock coincidentally being all-skip.
606thread_local! {
607 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
608}
609
610// How many times a warp was suppressed for one PLANE because that plane's own
611// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
612// reconinter.c) -- the gate's proof that a stream really carries the shape,
613// since the square `side`/`chroma_side` can be 8 or more while the plane's
614// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
615thread_local! {
616 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
617}
618
619/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
620#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
621pub(crate) fn warp_plane_suppress_hits() -> usize {
622 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
623}
624
625/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
626/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
627/// block dimensions decide it -- never the square `side`/`chroma_side`, which
628/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
629/// bigger than the real block in one axis.
630pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
631 if w >= 8 && h >= 8 {
632 return true;
633 }
634 hit!(WARP_PLANE_SUPPRESS_HITS);
635 false
636}
637
638/// Current value of [`CDEF_IDX_HITS`].
639#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
640pub(crate) fn cdef_idx_hits() -> usize {
641 CDEF_IDX_HITS.with(|c| c.get())
642}
643
644// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
645// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
646// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
647// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
648// instead of from the coarse 16x16 cell.
649thread_local! {
650 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
651 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
652 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
653}
654
655/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
656#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
657pub(crate) fn intra_in_inter_txctx_hits() -> usize {
658 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
659}
660
661/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
662#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
663pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
664 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
665}
666
667/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
668#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
669pub(crate) fn edge_filter_mi_fix_hits() -> usize {
670 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
671}
672
673// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
674// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
675// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
676// true no-op, matching every existing gate stream's `delta_q_present == 0`
677// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
678// The running quantizer index (spec `CurrentQIndex`, libaom
679// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
680// top of every tile (spec `decode_tile`), carried across superblocks within
681// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
682// dequantization call sites instead of the frame-constant `base_q_idx`.
683// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
684// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
685// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
686// back at every dequantization call site keyed on which plane it is doing.
687// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
688// read, across every call on the current thread -- the gate's proof that a
689// `delta_q_present` stream actually reached the new reader.
690thread_local! {
691 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
692}
693
694/// Current value of [`DELTA_Q_HITS`].
695#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
696pub(crate) fn delta_q_hits() -> usize {
697 DELTA_Q_HITS.with(|c| c.get())
698}
699
700/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
701/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
702/// one), so it is always `0` here.
703fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
704 let d = fctx.quant_deltas.with(|c| c.get());
705 match plane_idx {
706 0 => (d.y_dc, 0),
707 1 => (d.u_dc, d.u_ac),
708 _ => (d.v_dc, d.v_ac),
709 }
710}
711
712/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
713/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
714/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
715/// A no-op when `delta_q_present` is unset, or when this block is not at the
716/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
717/// libaom, collapsed here to a position check since a partition tree's
718/// top-left leaf is the only block that can ever land there), or when that
719/// leaf both *is* the whole superblock and is `skip` (the one case libaom
720/// itself skips the read, state carrying over unchanged).
721fn 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) {
722 if !fctx.delta_q_present.with(|c| c.get()) {
723 return;
724 }
725 let sb_mi = sb_mi_cur(fctx) as usize;
726 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
727 return;
728 }
729 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
730 // computed against the sequence's own superblock size (lane-sb128b r1:
731 // it used to be hardcoded against 64 and disabled under `sb128`, which a
732 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
733 // wrong).
734 if is_whole_sb && skip {
735 return;
736 }
737 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
738 const DELTA_Q_SMALL: i32 = 3;
739 if abs >= DELTA_Q_SMALL {
740 let rem_bits = dec.literal(3) + 1;
741 let thr = (1i32 << rem_bits) + 1;
742 abs = dec.literal(rem_bits) as i32 + thr;
743 }
744 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
745 let reduced = if sign_negative { -abs } else { abs };
746 hit!(DELTA_Q_HITS);
747 let res = fctx.delta_q_res.with(|c| c.get());
748 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
749}
750
751// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
752// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
753// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
754// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
755// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
756// updates index 0 and every reader treats that as the value for all 4
757// indices (spec `read_delta_lf_params`'s own single-cdf branch).
758// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
759// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
760thread_local! {
761 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
762}
763
764/// Current value of [`DELTA_LF_HITS`].
765#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
766pub(crate) fn delta_lf_hits() -> usize {
767 DELTA_LF_HITS.with(|c| c.get())
768}
769
770/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
771/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
772/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
773/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
774/// read once into index 0 otherwise.
775fn 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) {
776 if !fctx.delta_lf_present.with(|c| c.get()) {
777 return;
778 }
779 let sb_mi = sb_mi_cur(fctx) as usize;
780 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
781 return;
782 }
783 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
784 // computed against the sequence's own superblock size (lane-sb128b r1:
785 // it used to be hardcoded against 64 and disabled under `sb128`, which a
786 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
787 // wrong).
788 if is_whole_sb && skip {
789 return;
790 }
791 let multi = fctx.delta_lf_multi.with(|c| c.get());
792 let res = fctx.delta_lf_res.with(|c| c.get());
793 let count = if multi { 4 } else { 1 };
794 let mut cur = fctx.current_delta_lf.with(|c| c.get());
795 for i in 0..count {
796 let mut abs = if multi {
797 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
798 } else {
799 dec.symbol(&mut cdfs.delta_lf) as i32
800 };
801 const DELTA_LF_SMALL: i32 = 3;
802 if abs >= DELTA_LF_SMALL {
803 let rem_bits = dec.literal(3) + 1;
804 let thr = (1i32 << rem_bits) + 1;
805 abs = dec.literal(rem_bits) as i32 + thr;
806 }
807 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
808 let reduced = if sign_negative { -abs } else { abs };
809 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
810 hit!(DELTA_LF_HITS);
811 }
812 fctx.current_delta_lf.with(|c| c.set(cur));
813}
814
815/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
816/// after `skip` is known at every block-decode call site. A no-op at
817/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
818/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
819/// `allow_intrabc`, so neither needs a separate check here. Reads once per
820/// superblock, at the first non-skip block.
821fn maybe_read_cdef_idx(
822 dec: &mut SymbolDecoder,
823 mi_r: usize,
824 mi_c: usize,
825 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
826 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
827 // unit it covers, so its one literal drives all of them (lane-b128r).
828 (w_mi, h_mi): (usize, usize),
829 skip: bool,
830 fctx: &crate::decode::FrameCtx,
831) {
832 let bits = fctx.cdef_bits.with(|c| c.get());
833 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
834 return;
835 }
836 let idx = dec.literal(u32::from(bits)) as u8;
837 fctx.cdef_transmitted.with(|c| c.set(true));
838 hit!(CDEF_IDX_HITS);
839 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
840 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
841 if sb_cols > 0 {
842 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
843 // their strength off the MB_MODE_INFO of the first non-skip block in
844 // their own unit -- and a block that COVERS several units (the 128
845 // root's own 128x128 block, the only one there is) is that block for
846 // every unit it covers, so one literal drives all four. This grid is
847 // per 64x64 unit, so the read stamps every unit the block covers; one
848 // that is smaller than a unit stamps exactly the cell it always did.
849 let (rows, cols) = (
850 (h_mi / SB_MI as usize).max(1),
851 (w_mi / SB_MI as usize).max(1),
852 );
853 fctx.cdef_idx_grid.with(|g| {
854 let mut g = g.borrow_mut();
855 for dr in 0..rows {
856 for dc in 0..cols {
857 let i = (sb_r + dr) * sb_cols + sb_c + dc;
858 if sb_c + dc < sb_cols && i < g.len() {
859 g[i] = idx;
860 }
861 }
862 }
863 });
864 }
865}
866
867// ---------------------------------------------------------------------------
868// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
869// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
870// the two consumers a real stream exercises: the per-segment quantizer index
871// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
872// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
873// `read_intra_segment_id`/`read_inter_segment_id` and
874// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
875// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
876// is what the oracle every gate here compares against actually does.
877thread_local! {
878 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
879 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
880 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
881 /// this frame has no primary reference (spec `load_previous_segment_ids`).
882 /// `(mi_rows, mi_cols)` for both maps above.
883 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
884 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
885 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
886 /// The block currently being decoded -- read back by [`block_q_idx`].
887 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
888 /// How many real `segment_id` symbols were read, and the set of segment
889 /// ids any block ended up with -- the gate's proof the feature fired.
890 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
891 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
892 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
893 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
894 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
895 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
896 /// nothing about the segments carrying distinct quantizers.
897 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
898 /// How many `seg_id_predicted` symbols were read (temporal update).
899 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
900}
901
902/// Installs this frame's segmentation parameters and allocates its map, with
903/// `prev` the primary reference frame's saved map (spec
904/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
905/// slot). Called once per frame, whether or not segmentation is enabled.
906pub(crate) fn set_segmentation(
907 seg: SegmentationParams,
908 mi_rows: usize,
909 mi_cols: usize,
910 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
911) {
912 if crate::envflags::env_flag!("EC_HDR") {
913 eprintln!(
914 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
915 seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data
916 );
917 }
918 fctx.seg.with(|s| *s.borrow_mut() = seg);
919 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
920 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
921 fctx.prev_seg_ids.with(|m| {
922 let mut m = m.borrow_mut();
923 m.clear();
924 if let Some(p) = prev {
925 if p.len() == mi_rows * mi_cols {
926 m.extend_from_slice(p);
927 }
928 }
929 });
930 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
931 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
932 fctx.cur_segment_id.with(|c| c.set(0));
933}
934
935/// This frame's decoded segment map, to be stored into whichever reference
936/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
937pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
938 fctx.seg_ids.with(|m| m.borrow().clone())
939}
940
941/// How many `segment_id` symbols have been read (never reset per frame).
942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
943pub(crate) fn segment_id_hits() -> usize {
944 SEG_ID_HITS.with(|c| c.get())
945}
946
947/// How many distinct segment ids any decoded block has carried.
948#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
949pub(crate) fn segment_ids_seen() -> usize {
950 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
951}
952
953/// The lowest and highest quantizer index any decoded block was dequantized
954/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
955#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
956pub(crate) fn block_q_span() -> (i32, i32) {
957 BLOCK_Q_SPAN.with(|c| c.get())
958}
959
960/// How many `seg_id_predicted` symbols have been read (temporal update).
961#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
962pub(crate) fn segment_pred_hits() -> usize {
963 SEG_PRED_HITS.with(|c| c.get())
964}
965
966/// Resets the segmentation hit counters (gate setup).
967#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
968pub(crate) fn reset_segment_hits() {
969 SEG_ID_HITS.with(|c| c.set(0));
970 SEG_IDS_SEEN.with(|c| c.set(0));
971 SEG_PRED_HITS.with(|c| c.set(0));
972 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
973}
974
975/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
976/// being decoded, with its `FeatureData` value.
977fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
978 fctx.seg.with(|s| {
979 let s = s.borrow();
980 s.feature_active(segment_id, feature)
981 .then(|| i32::from(s.feature_data[segment_id][feature]))
982 })
983}
984
985/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
986/// `av1_get_qindex`) for the block currently being decoded: the running
987/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
988/// Every dequant call site reads the block's quantizer through here.
989fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
990 let base = fctx.current_q_idx.with(|c| c.get());
991 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
992 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
993 Some(data) => (base + data).clamp(0, 255),
994 None => base,
995 };
996 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
997 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
998 // already proven equal is a segment-id defect, not a quantizer one.
999 if crate::envflags::env_flag!("EC_DQCOEFF") {
1000 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
1001 }
1002 hit_do!(BLOCK_Q_SPAN.with(|c| {
1003 let (lo, hi) = c.get();
1004 c.set((lo.min(q), hi.max(q)));
1005 }););
1006 q
1007}
1008
1009/// The segment id recorded for one mi cell of the current frame's map.
1010fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1011 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1012 if mi_r >= mi_rows || mi_c >= mi_cols {
1013 return 0;
1014 }
1015 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1016}
1017
1018/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1019fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
1020 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1021 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1022 fctx.seg_ids.with(|m| {
1023 let mut m = m.borrow_mut();
1024 for y in 0..y_mis {
1025 for x in 0..x_mis {
1026 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1027 }
1028 }
1029 });
1030 fctx.cur_segment_id.with(|c| c.set(id));
1031 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1032}
1033
1034/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1035/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1036/// block's own mi footprint. `0` when there is no previous map.
1037fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1038 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1039 fctx.prev_seg_ids.with(|m| {
1040 let m = m.borrow();
1041 if m.is_empty() {
1042 return 0;
1043 }
1044 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1045 let mut id = u8::MAX;
1046 for y in 0..y_mis {
1047 for x in 0..x_mis {
1048 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1049 }
1050 }
1051 if id == u8::MAX { 0 } else { id }
1052 })
1053}
1054
1055/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1056fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1057 if reference == 0 {
1058 return diff;
1059 }
1060 if reference >= max - 1 {
1061 return max - diff - 1;
1062 }
1063 let half = if 2 * reference < max {
1064 diff <= 2 * reference
1065 } else {
1066 diff <= 2 * (max - reference - 1)
1067 };
1068 if half {
1069 return if diff & 1 != 0 {
1070 reference + ((diff + 1) >> 1)
1071 } else {
1072 reference - (diff >> 1)
1073 };
1074 }
1075 if 2 * reference < max { diff } else { max - (diff + 1) }
1076}
1077
1078/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1079/// frame's already-decoded above/left/above-left neighbours.
1080fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1081 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1082 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1083 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1084 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1085 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1086 let ctx = match prev_ul {
1087 None => 0,
1088 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1089 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1090 Some(_) => 0,
1091 };
1092 let pred = match (prev_u, prev_l) {
1093 (None, l) => l.unwrap_or(0),
1094 (Some(u), None) => u,
1095 (Some(u), Some(l)) => {
1096 if prev_ul == Some(u) {
1097 u
1098 } else {
1099 l
1100 }
1101 }
1102 };
1103 (pred, ctx)
1104}
1105
1106/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1107/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1108/// that prediction. Does NOT write the map -- callers do.
1109fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
1110 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1111 if skip {
1112 return pred as u8;
1113 }
1114 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1115 hit!(SEG_ID_HITS);
1116 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1117 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1118 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1119 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1120 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1121 eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0);
1122 }
1123 id as u8
1124}
1125
1126/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1127/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1128/// caller decides which by passing `pre_skip`).
1129fn intra_segment_id(
1130 dec: &mut SymbolDecoder,
1131 cdfs: &mut Cdfs,
1132 mi_r: usize,
1133 mi_c: usize,
1134 w_mi: usize,
1135 h_mi: usize,
1136 skip: bool, fctx: &crate::decode::FrameCtx,
1137) {
1138 if !fctx.seg.with(|s| s.borrow().enabled) {
1139 return;
1140 }
1141 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1142 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1143}
1144
1145/// Whether this frame's intra blocks read their `segment_id` before `skip`
1146/// (`SegIdPreSkip`); `false` also when segmentation is off.
1147fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1148 fctx.seg.with(|s| {
1149 let s = s.borrow();
1150 s.enabled && s.seg_id_pre_skip
1151 })
1152}
1153
1154/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1155/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1156/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1157fn inter_segment_id(
1158 dec: &mut SymbolDecoder,
1159 cdfs: &mut Cdfs,
1160 mi_r: usize,
1161 mi_c: usize,
1162 w_mi: usize,
1163 h_mi: usize,
1164 skip: bool,
1165 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1166) {
1167 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1168 let s = s.borrow();
1169 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1170 });
1171 if !enabled {
1172 return;
1173 }
1174 if !update_map {
1175 // The map is inherited wholesale from the previous frame.
1176 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1177 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1178 return;
1179 }
1180 if pre_skip && !pre_skip_frame {
1181 return;
1182 }
1183 if !pre_skip && skip {
1184 // libaom: a skipped block never codes `seg_id_predicted`, and its
1185 // segment id is the spatial prediction.
1186 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1187 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1188 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1189 return;
1190 }
1191 let id = if temporal_update {
1192 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1193 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1194 hit!(SEG_PRED_HITS);
1195 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1196 if predicted {
1197 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1198 } else {
1199 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1200 }
1201 } else {
1202 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1203 };
1204 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1205}
1206
1207/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1208fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1209 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1210 // so contribute 0) outside the tile -- the availability check here is
1211 // what keeps a previous tile's stamps out of this tile's context.
1212 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1213 let above = if mi_r > row0 {
1214 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1215 } else {
1216 0
1217 };
1218 let left = if mi_c > col0 {
1219 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1220 } else {
1221 0
1222 };
1223 usize::from(above + left)
1224}
1225
1226/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1227fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1228 fctx.above_seg_pred.with(|m| {
1229 let mut m = m.borrow_mut();
1230 for i in 0..w_mi {
1231 if let Some(cell) = m.get_mut(mi_c + i) {
1232 *cell = value;
1233 }
1234 }
1235 });
1236 fctx.left_seg_pred.with(|m| {
1237 let mut m = m.borrow_mut();
1238 for i in 0..h_mi {
1239 if let Some(cell) = m.get_mut(mi_r + i) {
1240 *cell = value;
1241 }
1242 }
1243 });
1244}
1245
1246// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1247// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1248// counter, proving a stream actually put a directional block next to a
1249// smooth-predicted neighbour rather than every block reading the (previously
1250// hardcoded `false`) edge-filter strength bucket unchanged.
1251thread_local! {
1252 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1253 const { std::cell::Cell::new(0) };
1254}
1255
1256/// Current value of [`SMOOTH_LUMA_HITS`].
1257#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1258pub(crate) fn smooth_luma_hits() -> usize {
1259 SMOOTH_LUMA_HITS.with(|c| c.get())
1260}
1261
1262thread_local! {
1263 /// lane-band46 r1: how many split-transform units answered their intra
1264 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1265 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1266 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1267 /// transform unit whose above-right / below-left reference samples would
1268 /// be wrong without that fix.
1269 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1270 const { std::cell::Cell::new(0) };
1271}
1272
1273/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1274#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1275pub(crate) fn split_tu_reach_fix_hits() -> usize {
1276 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1277}
1278
1279/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1280/// answer differs from the standalone-block answer the call sites used before
1281/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1282/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1283/// block's top-left `(px, py)`.
1284#[allow(clippy::too_many_arguments)]
1285fn tu_reach(
1286 bw: usize,
1287 bh: usize,
1288 col_off: usize,
1289 row_off: usize,
1290 tx: usize,
1291 block: Reach,
1292 px: usize,
1293 py: usize,
1294 width: usize,
1295 height: usize, fctx: &crate::decode::FrameCtx,
1296) -> Reach {
1297 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1298 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1299 if fixed != standalone {
1300 hit!(SPLIT_TU_REACH_FIX_HITS);
1301 }
1302 fixed
1303}
1304
1305// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1306// across every call on the current thread -- lane-chroma r3's own before/after
1307// counter, proving a stream actually exercised chroma's smooth/paeth
1308// predictor (the previously-refused round-2 gap) rather than every block
1309// landing on DC/CFL/directional.
1310thread_local! {
1311 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1312 const { std::cell::Cell::new(0) };
1313}
1314
1315/// Current value of [`SMOOTH_UV_HITS`].
1316#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1317pub(crate) fn smooth_uv_hits() -> usize {
1318 SMOOTH_UV_HITS.with(|c| c.get())
1319}
1320
1321// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1322// full superblock walk over, across every call on the current thread --
1323// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1324// multi-tile stream must prove more than one tile actually fired, not just
1325// that the stream carried tile_info.cols > 1.
1326thread_local! {
1327 static TILE_HITS: std::cell::Cell<usize> =
1328 const { std::cell::Cell::new(0) };
1329}
1330/// Current value of [`TILE_HITS`].
1331#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1332pub(crate) fn tile_hits() -> usize {
1333 TILE_HITS.with(|c| c.get())
1334}
1335
1336// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1337// selected for filtering, across every call on the current thread -- the same
1338// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1339// exercised `apply_deblock` rather than every edge landing on level 0.
1340thread_local! {
1341 static DEBLOCK_HITS: std::cell::Cell<usize> =
1342 const { std::cell::Cell::new(0) };
1343}
1344/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1345/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1346/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1347static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1348 std::sync::atomic::AtomicUsize::new(0);
1349
1350/// Current value of [`DEBLOCK_HITS`].
1351#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1352pub(crate) fn deblock_hits() -> usize {
1353 DEBLOCK_HITS.with(|c| c.get())
1354}
1355
1356// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1357// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1358// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1359// stream built with `--enable-onesided-comp=1` really exercised the
1360// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1361thread_local! {
1362 static UNI_COMP_HITS: std::cell::Cell<usize> =
1363 const { std::cell::Cell::new(0) };
1364}
1365
1366/// Current value of [`UNI_COMP_HITS`].
1367#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1368pub(crate) fn uni_comp_hits() -> usize {
1369 UNI_COMP_HITS.with(|c| c.get())
1370}
1371
1372// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1373// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1374// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1375// blend and not only the wedge arm.
1376thread_local! {
1377 static DIFFWTD_HITS: std::cell::Cell<usize> =
1378 const { std::cell::Cell::new(0) };
1379}
1380
1381/// Current value of [`DIFFWTD_HITS`].
1382#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1383pub(crate) fn diffwtd_hits() -> usize {
1384 DIFFWTD_HITS.with(|c| c.get())
1385}
1386
1387// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1388// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1389// this decoder's square inter path reaches), so no `compound_type` symbol is
1390// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1391// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1392thread_local! {
1393 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1394 const { std::cell::Cell::new(0) };
1395}
1396
1397/// Current value of [`DIFFWTD_INFERRED_HITS`].
1398#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1399pub(crate) fn diffwtd_inferred_hits() -> usize {
1400 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1401}
1402
1403// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1404// with `show_frame == 0`, output later by a `show_existing_frame` header
1405// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1406// `stream::decode_stream`, which is where the frame header is consumed; the
1407// gate's proof that the on-value really reached the bitstream rather than
1408// being dropped by the rate control.
1409thread_local! {
1410 static FWD_KF_HITS: std::cell::Cell<usize> =
1411 const { std::cell::Cell::new(0) };
1412}
1413
1414/// Current value of [`FWD_KF_HITS`].
1415#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1416pub(crate) fn fwd_kf_hits() -> usize {
1417 FWD_KF_HITS.with(|c| c.get())
1418}
1419
1420/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1421pub(crate) fn note_fwd_kf() {
1422 hit!(FWD_KF_HITS);
1423}
1424
1425// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1426// the block's own side, across every call on the current thread -- the same
1427// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1428// actually exercised a *split* transform under `TxMode::Select` rather than
1429// every block coincidentally resolving `depth=0` (indistinguishable from
1430// `TxMode::Largest` pixel-wise).
1431thread_local! {
1432 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1433 const { std::cell::Cell::new(0) };
1434}
1435
1436// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1437// transform smaller than their own side (`tx_depth != 0`) while coding a
1438// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1439// only exercises with aomenc's tx-size search left ON (its default), which
1440// every older recipe in this file pins off. Counted at the block, so a stream
1441// where RD happened to give every split-transform block a DC chroma mode
1442// reads as zero rather than silently passing for free.
1443thread_local! {
1444 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1445 const { std::cell::Cell::new(0) };
1446}
1447
1448/// Current value of [`SQ_CHROMA_TX_HITS`].
1449#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1450pub(crate) fn sq_chroma_tx_hits() -> usize {
1451 SQ_CHROMA_TX_HITS.with(|c| c.get())
1452}
1453
1454/// Current value of [`TX_DEPTH_HITS`].
1455#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1456pub(crate) fn tx_depth_hits() -> usize {
1457 TX_DEPTH_HITS.with(|c| c.get())
1458}
1459
1460// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1461// read, and how many of those actually took the split, on the current thread
1462// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1463// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1464// coincidentally coding one whole-block transform.
1465thread_local! {
1466 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1467 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1468 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1469 // strips coded one whole-block rect transform unit, and how many split
1470 // their rect max transform into square sub-transforms.
1471 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1472 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1473 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1474 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1475 // truncated low-32 corner.
1476 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1477 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1478 // inter strip, `[32x8, 8x32]`.
1479 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1480 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1481 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1482 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1483 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1484 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1485 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1486 // frame -- 16x8 and 8x16 inter leaves.
1487 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1488 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1489 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1490 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1491 // `decode_inter_block` already carries forty parameters and both are
1492 // frame-constant.
1493 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1494 // frame-constant like the two above and stashed the same way -- an intra
1495 // block inside an inter frame reads `use_filter_intra` under it.
1496}
1497
1498/// Current value of [`TXFM_SPLIT_READS`].
1499#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1500pub(crate) fn txfm_split_reads() -> usize {
1501 TXFM_SPLIT_READS.with(|c| c.get())
1502}
1503
1504/// Current value of [`TXFM_SPLIT_HITS`].
1505#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1506pub(crate) fn txfm_split_hits() -> usize {
1507 TXFM_SPLIT_HITS.with(|c| c.get())
1508}
1509
1510/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1511#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1512pub(crate) fn inter_leaf16_horz_hits() -> usize {
1513 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1514}
1515
1516/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1517#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1518pub(crate) fn inter_leaf16_vert_hits() -> usize {
1519 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1520}
1521
1522/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1523pub(crate) fn rect_inter_tu_hits() -> usize {
1524 RECT_INTER_TU_HITS.with(|c| c.get())
1525}
1526
1527/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1528pub(crate) fn rect_inter_txsplit_hits() -> usize {
1529 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1530}
1531
1532/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1533pub(crate) fn rect64_inter_tu_hits() -> usize {
1534 RECT64_INTER_TU_HITS.with(|c| c.get())
1535}
1536
1537/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1538/// whole-block luma units of a 32x32-level 1:4 inter strip.
1539pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1540 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1541}
1542
1543/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1544/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1545pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1546 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1547}
1548
1549/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1550/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1551pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1552 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1553}
1554
1555/// Records one rectangular var-tx leaf.
1556fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1557 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1558 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1559 }
1560 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1561 cell.with(|c| {
1562 let mut h = c.get();
1563 h[usize::from(th > tw)] += 1;
1564 c.set(h);
1565 });
1566}
1567
1568/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1569/// [`ENABLE_FILTER_INTRA_INTER`].
1570pub(crate) fn set_inter_tx_mode(
1571 tx_select: bool,
1572 reduced_tx_set: bool,
1573 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1574) {
1575 fctx.tx_select_inter.with(|c| c.set(tx_select));
1576 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1577 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1578}
1579
1580// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1581// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1582// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1583// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1584// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1585// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1586// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1587// path above).
1588thread_local! {
1589 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1590 const { std::cell::Cell::new(0) };
1591}
1592
1593/// Current value of [`VERT_B_INTRA_HITS`].
1594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1595pub(crate) fn vert_b_intra_hits() -> usize {
1596 VERT_B_INTRA_HITS.with(|c| c.get())
1597}
1598
1599// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1600// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1601// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1602// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1603// every arm separately so a run where aomenc's RD only picked one cannot
1604// pass as proof of four.
1605thread_local! {
1606 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1607}
1608
1609// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1610thread_local! {
1611 /// 4x4 transform units decoded inside an 8x8 square of a
1612 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1613 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1614 /// a real `--enable-tx-size-search=1` stream reaches it.
1615 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1616}
1617
1618#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1619pub(crate) fn vert_ab_tx4_hits() -> usize {
1620 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1621}
1622
1623#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1624pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1625 AB16_HITS.with(std::cell::Cell::get)
1626}
1627
1628fn bump_ab16(arm: usize) {
1629 hit_do! {
1630 AB16_HITS.with(|c| {
1631 let mut v = c.get();
1632 v[arm] += 1;
1633 c.set(v);
1634 });
1635 }
1636}
1637
1638// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1639// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1640// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1641// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1642// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1643// superblock's z-order recursion, not raster mi position).
1644thread_local! {
1645 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1646 const { std::cell::Cell::new(0) };
1647}
1648
1649/// Current value of [`HORZ_VERT_INTRA_HITS`].
1650#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1651pub(crate) fn horz_vert_intra_hits() -> usize {
1652 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1653}
1654
1655// How many blocks were decoded as a frame-edge rect strip -- the single
1656// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1657// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1658// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1659// paths share the counter.
1660thread_local! {
1661 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1662 const { std::cell::Cell::new(0) };
1663}
1664
1665/// Current value of [`EDGE_RECT_STRIP_HITS`].
1666#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1667pub(crate) fn edge_rect_strip_hits() -> usize {
1668 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1669}
1670
1671// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1672// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1673// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1674// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1675// are height mod 16 == 8, so every inter frame crosses these nodes.
1676thread_local! {
1677 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1678 const { std::cell::Cell::new([0; 6]) };
1679}
1680
1681/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1682pub(crate) fn bump_inter_edge_strip(idx: usize) {
1683 hit_do! {
1684 INTER_EDGE_STRIP_HITS.with(|c| {
1685 let mut v = c.get();
1686 v[idx] += 1;
1687 c.set(v);
1688 });
1689 }
1690}
1691
1692// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1693// forced split -- libaom `decode_partition` (decodeframe.c):
1694// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1695// straddle case that reads NO symbol at all. Indexed by level:
1696// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1697thread_local! {
1698 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1699 const { std::cell::Cell::new([0; 4]) };
1700}
1701
1702fn bump_edge_both_cut(level: usize) {
1703 hit_do! {
1704 EDGE_BOTH_CUT_HITS.with(|c| {
1705 let mut v = c.get();
1706 v[level] += 1;
1707 c.set(v);
1708 });
1709 }
1710}
1711
1712/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1713pub fn inter_edge_strip_hits() -> [usize; 6] {
1714 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1715}
1716
1717/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1718/// into the next one (class `counter-from-refused-stream`).
1719pub fn reset_inter_edge_strip_hits() {
1720 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1721}
1722
1723/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1725pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1726 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1727}
1728
1729/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1731pub(crate) fn reset_edge_both_cut_hits() {
1732 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1733}
1734
1735// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1736// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1737// the case every rect path here refused by name before, and the first
1738// refusal the user's ReelB extract (600s in) stops at.
1739thread_local! {
1740 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1741 const { std::cell::Cell::new(0) };
1742}
1743
1744/// Current value of [`RECT_SPLIT_TX_HITS`].
1745#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1746pub(crate) fn rect_split_tx_hits() -> usize {
1747 RECT_SPLIT_TX_HITS.with(|c| c.get())
1748}
1749
1750// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1751// side 64) AND split past the first depth, i.e. tiled more than one unit in
1752// each axis -- the only shape with a transform unit that has neighbours on
1753// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1754// no gate fired before lane-rectsplit r2 (the shared counter above also
1755// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1756thread_local! {
1757 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1758 const { std::cell::Cell::new(0) };
1759}
1760
1761/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1762#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1763pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1764 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1765}
1766
1767// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1768// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1769// chroma half takes that had no coefficient tables before (index order:
1770// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1771// proves the pair it happens to hit cannot catch a transposed scan/context
1772// table (class scan-weights-cross-axis).
1773thread_local! {
1774 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1775 const { std::cell::Cell::new([0; 4]) };
1776}
1777
1778/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1779#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1780pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1781 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1782}
1783
1784// How many HORZ/VERT intra strips actually predicted with filter intra
1785// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1786// ("this decoder predicts square-only") until `predict_filter_intra` took
1787// `bw`x`bh`.
1788thread_local! {
1789 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1790 const { std::cell::Cell::new(0) };
1791}
1792
1793/// Current value of [`FILTER_INTRA_RECT_HITS`].
1794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1795pub(crate) fn filter_intra_rect_hits() -> usize {
1796 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1797}
1798
1799// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1800// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1801// was never read at all before that round, so a gate needs to prove the flag
1802// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1803// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1804// carry different probabilities (18101 vs 20229), so a transposed pair is
1805// only caught by a gate that sees the flag fire on BOTH shapes (class
1806// scan-weights-cross-axis).
1807thread_local! {
1808 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1809 const { std::cell::Cell::new(0) };
1810 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1811 const { std::cell::Cell::new(0) };
1812}
1813
1814/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1816pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1817 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1818}
1819
1820/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1821#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1822pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1823 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1824}
1825
1826// How many rectangular transform units actually coded coefficients through
1827// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1828// exercised the rect coefficient reader at all rather than passing on
1829// all-skip blocks.
1830thread_local! {
1831 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1832 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1833}
1834
1835/// Current value of [`RECT_COEFF_TU_HITS`].
1836#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1837pub(crate) fn rect_coeff_tu_hits() -> usize {
1838 RECT_COEFF_TU_HITS.with(|c| c.get())
1839}
1840
1841/// Rectangular transform units whose resolved `tx_type` is a 1D class
1842/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1843/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1844/// for the square reader's own 1D types.
1845#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1846pub(crate) fn rect_class1_hits() -> usize {
1847 RECT_CLASS1_HITS.with(|c| c.get())
1848}
1849
1850// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1851// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1852// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1853// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1854// prove nothing about the new shapes.
1855thread_local! {
1856 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1857 const { std::cell::Cell::new(0) };
1858}
1859
1860/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1862pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1863 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1864}
1865
1866// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1867// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1868// counter would be satisfied by a 16x8 strip and prove nothing here.
1869thread_local! {
1870 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1871 const { std::cell::Cell::new(0) };
1872}
1873
1874/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1875#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1876pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1877 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1878}
1879
1880// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1881// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1882// call on the current thread -- the same before/after counter pattern as
1883// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1884// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1885// landing on `DCT_DCT`.
1886thread_local! {
1887 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1888 const { std::cell::Cell::new(0) };
1889}
1890
1891// How many `uv_mode` reads resolved to a directional chroma mode (neither
1892// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1893// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1894// actually exercised chroma's own directional predictor.
1895thread_local! {
1896 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1897 const { std::cell::Cell::new(0) };
1898}
1899
1900/// Current value of [`DIRECTIONAL_UV_HITS`].
1901#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1902pub(crate) fn directional_uv_hits() -> usize {
1903 DIRECTIONAL_UV_HITS.with(|c| c.get())
1904}
1905
1906// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1907// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1908// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1909// proving a stream actually exercised a nonzero angle delta.
1910thread_local! {
1911 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1912 const { std::cell::Cell::new(0) };
1913}
1914
1915// How many [`read_single_ref`] reads resolved to a reference other than
1916// `LAST_FRAME`, across every call on the current thread -- the same before/after
1917// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1918// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1919// only other supported one so far) rather than every block coincidentally
1920// resolving `LAST_FRAME`.
1921thread_local! {
1922 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1923 const { std::cell::Cell::new(0) };
1924}
1925
1926/// Current value of [`NON_LAST_REF_HITS`].
1927#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1928pub(crate) fn non_last_ref_hits() -> usize {
1929 NON_LAST_REF_HITS.with(|c| c.get())
1930}
1931
1932// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1933// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1934// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1935// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1936// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1937// `GOLDEN_FRAME` draw it did not ask for.
1938thread_local! {
1939 static LAST2_HITS: std::cell::Cell<usize> =
1940 const { std::cell::Cell::new(0) };
1941}
1942thread_local! {
1943 static LAST3_HITS: std::cell::Cell<usize> =
1944 const { std::cell::Cell::new(0) };
1945}
1946thread_local! {
1947 static GOLDEN_HITS: std::cell::Cell<usize> =
1948 const { std::cell::Cell::new(0) };
1949}
1950thread_local! {
1951 static BWDREF_HITS: std::cell::Cell<usize> =
1952 const { std::cell::Cell::new(0) };
1953}
1954thread_local! {
1955 static ALTREF2_HITS: std::cell::Cell<usize> =
1956 const { std::cell::Cell::new(0) };
1957}
1958thread_local! {
1959 static ALTREF_HITS: std::cell::Cell<usize> =
1960 const { std::cell::Cell::new(0) };
1961}
1962
1963// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1964// -- proves a `reference_select` stream actually reached a block that picked
1965// compound, not just that the header bit was set. Every such block is
1966// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1967// so this only ever counts attempted reads, never a completed decode.
1968thread_local! {
1969 static COMP_MODE_HITS: std::cell::Cell<usize> =
1970 const { std::cell::Cell::new(0) };
1971}
1972
1973/// Current value of [`COMP_MODE_HITS`].
1974#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1975pub(crate) fn comp_mode_hits() -> usize {
1976 COMP_MODE_HITS.with(|c| c.get())
1977}
1978
1979// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1980// use for, across every call on the current thread -- the same before/after
1981// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1982// exercised palette reconstruction rather than only reading and refusing the
1983// `palette_y_mode` symbol.
1984thread_local! {
1985 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1986}
1987
1988/// Current value of [`PALETTE_HITS`].
1989#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1990pub(crate) fn palette_hits() -> usize {
1991 PALETTE_HITS.with(|c| c.get())
1992}
1993
1994// lane-tiles r12: of those, how many sat at their own TILE's left column --
1995// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1996// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1997// palette gate that never hits one proves nothing about the tile guard.
1998thread_local! {
1999 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2000}
2001
2002/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2004pub(crate) fn palette_tile_left_hits() -> usize {
2005 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2006}
2007
2008// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2009// palette use -- proves a stream actually reconstructed UV palette pixels,
2010// not just read and refused the `palette_uv_mode` symbol.
2011thread_local! {
2012 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2013}
2014
2015/// Current value of [`PALETTE_UV_HITS`].
2016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2017pub(crate) fn palette_uv_hits() -> usize {
2018 PALETTE_UV_HITS.with(|c| c.get())
2019}
2020
2021// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2022// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2023// (not just the square path's) actually fired.
2024thread_local! {
2025 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2026}
2027
2028/// Current value of [`PALETTE_RECT_HITS`].
2029#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2030pub(crate) fn palette_rect_hits() -> usize {
2031 PALETTE_RECT_HITS.with(|c| c.get())
2032}
2033
2034// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2035// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2036// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2037// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2038// RD, almost always refused-on-use because the block doesn't end up USING a
2039// palette -- see r5's report). This is the site the removed refusal
2040// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2041// fired here whether or not the block picked a palette, so this is the
2042// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2043// never observes.
2044thread_local! {
2045 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2046}
2047
2048/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2049#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2050pub(crate) fn rect_screen_content_hits() -> usize {
2051 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2052}
2053
2054// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2055// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2056// windowing actually ran, not just that the whole-block path stayed exact.
2057// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2058// first actually incremented in r7, when the refusal it guarded was lifted.
2059thread_local! {
2060 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2061}
2062
2063thread_local! {
2064 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2065 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2066 /// (16x8/8x16), the two shapes the lifted refusals named.
2067 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2068}
2069
2070/// Current value of [`RECT4_PALETTE_HITS`].
2071#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2072pub(crate) fn rect4_palette_hits() -> usize {
2073 RECT4_PALETTE_HITS.with(|c| c.get())
2074}
2075
2076/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2077#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2078pub(crate) fn palette_split_tx_hits() -> usize {
2079 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2080}
2081
2082thread_local! {
2083 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2084 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2085 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2086 /// `--min-partition-size=8` puts them on this leaf path.
2087 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2088}
2089
2090/// Current value of [`PALETTE_LEAF8_HITS`].
2091#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2092pub(crate) fn palette_leaf8_hits() -> usize {
2093 PALETTE_LEAF8_HITS.with(|c| c.get())
2094}
2095
2096/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2097#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2098pub(crate) fn reset_palette_leaf8_hits() {
2099 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2100}
2101
2102thread_local! {
2103 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2104 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2105 /// block that also carries a real, corner-cropped luma transform.
2106 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2107}
2108
2109/// Current value of [`PALETTE_SB_STRIP_HITS`].
2110#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2111pub(crate) fn palette_sb_strip_hits() -> usize {
2112 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2113}
2114
2115/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2116#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2117pub(crate) fn reset_palette_sb_strip_hits() {
2118 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2119}
2120
2121// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2122// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2123// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2124// capability rather than the key frame's, which every screen stream also
2125// carries.
2126thread_local! {
2127 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2128 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2129}
2130
2131// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2132// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2133// shared counter too, so only this one proves a gate really reached the leaf
2134// where the refusal used to sit.
2135thread_local! {
2136 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2137 const { std::cell::Cell::new((0, 0)) };
2138}
2139
2140/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2141pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2142 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2143}
2144
2145/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2146pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2147 (
2148 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2149 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2150 )
2151}
2152
2153// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2154// and which are therefore predicted one transform unit at a time (a skipped
2155// block codes no coefficients, so nothing else in the stream witnesses this
2156// path -- only the pixels do).
2157thread_local! {
2158 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2159}
2160
2161/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2162pub fn skip_split_tx_hits() -> usize {
2163 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2164}
2165
2166// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2167// `tx_depth` split the luma transform -- the arm that predicted DC off the
2168// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2169// witness this path, so a gate that wants it needs the counter.
2170thread_local! {
2171 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2172}
2173
2174/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2175pub fn skip_split_tx_override_hits() -> usize {
2176 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2177}
2178
2179/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2180pub fn reset_skip_split_tx_override_hits() {
2181 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2182}
2183
2184// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2185// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2186// really are smaller than the block and FEWER symbols are read than the
2187// block has cells (class map-read-past-frame-edge).
2188thread_local! {
2189 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2190}
2191
2192/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2193pub fn palette_onscreen_cut_hits() -> usize {
2194 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2195}
2196
2197/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2198pub fn reset_palette_onscreen_cut_hits() {
2199 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2200}
2201
2202/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2203pub fn reset_skip_split_tx_hits() {
2204 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2205}
2206
2207// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2208// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2209// the gate's proof that the lifted path actually ran, per size.
2210thread_local! {
2211 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2212 const { std::cell::Cell::new([0; 4]) };
2213}
2214
2215/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2216#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2217pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2218 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2219}
2220
2221 /// A just-decoded palette-Y block's own predicted pixels
2222 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2223 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2224 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2225 /// per-block override through `read_plane`'s two dozen call sites is the
2226 /// alternative this avoids). Always empty again once that call consumes
2227 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2228 /// sees stale state.
2229
2230
2231/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2232/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2233/// site whose reconstruct never runs would be picked up by the NEXT block's
2234/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2235/// lane-lossless2: one transform unit's window on a block-sized palette
2236/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2237/// handing it the whole-block buffer makes every unit reconstruct the block's
2238/// top-left corner (the luma split-transform paths already window; the chroma
2239/// ones did not, which is invisible until a lossless frame codes a palette
2240/// block as 4x4 chroma units).
2241fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> {
2242 (0..h)
2243 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2244 .collect()
2245}
2246
2247/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2248#[track_caller]
2249fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2250 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2251 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2252 eprintln!(
2253 "PALSET len={} stale={stale} at {}",
2254 buf.len(),
2255 std::panic::Location::caller()
2256 );
2257 }
2258 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2259}
2260
2261#[track_caller]
2262fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2263 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2264 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2265 eprintln!(
2266 "PALTAKE len={:?} at {}",
2267 got.as_ref().map(Vec::len),
2268 std::panic::Location::caller()
2269 );
2270 }
2271 got
2272}
2273
2274/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2275/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2276/// pixels, because at parse time this block's own luma is still queued.
2277#[derive(Clone, Copy, Debug)]
2278pub(crate) struct CflSrc {
2279 px: usize,
2280 py: usize,
2281 bw: usize,
2282 bh: usize,
2283 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2284 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2285 rect: bool,
2286}
2287
2288fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2289 CflSrc { px, py, bw: side, bh: side, rect: false }
2290}
2291
2292fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2293 CflSrc { px, py, bw, bh, rect: true }
2294}
2295
2296/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2297/// instead of executed. Each variant is the resolved argument tuple of the
2298/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2299/// order performs exactly the same writes in exactly the same order --
2300/// entropy parsing no longer touches the frame's own planes (except the two
2301/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2302/// the replay on a superblock-row wavefront worker.
2303/// The dequantization + inverse transform of one transform unit, kept as its
2304/// INPUTS so that a recorded write carries the work instead of its result
2305/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2306/// recon worker, not on the parsing thread. `stride == 0` means the dense
2307/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2308/// `reconstruct_mc_rect` reads both of its buffers at.
2309#[derive(Clone, Copy)]
2310pub(crate) struct TxParams {
2311 pub(crate) w: usize,
2312 pub(crate) h: usize,
2313 pub(crate) bit_depth: u8,
2314 pub(crate) q_idx: i32,
2315 pub(crate) dc_delta: i32,
2316 pub(crate) ac_delta: i32,
2317 pub(crate) tx_type: TxType,
2318 pub(crate) stride: usize,
2319 /// lane-lossless: this transform unit belongs to a lossless frame, so the
2320 /// residual comes off the 4x4 Walsh-Hadamard
2321 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2322 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2323 pub(crate) lossless: bool,
2324}
2325
2326impl TxParams {
2327 /// The one copy of the produce-the-residual code: the inline path calls it
2328 /// on the parse thread, the wavefront worker calls it on its own, so both
2329 /// are the same function on the same inputs and byte-identical.
2330 fn run(self, grid: &[i32]) -> Vec<i32> {
2331 let residual = if self.lossless {
2332 debug_assert_eq!((self.w, self.h), (4, 4));
2333 debug_assert_eq!(self.tx_type, TxType::DctDct);
2334 crate::transform::dequant_and_inverse_wht4x4(
2335 grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2336 )
2337 } else {
2338 dequant_and_inverse_typed_wh(
2339 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2340 self.tx_type,
2341 )
2342 };
2343 // An all-zero grid transforms to the empty marker, and a strided copy
2344 // of zeros is still zeros: the marker passes straight through.
2345 if residual.is_empty() {
2346 return residual;
2347 }
2348 if self.stride == 0 {
2349 return residual;
2350 }
2351 let mut strided = vec![0i32; self.stride * self.stride];
2352 for row in 0..self.h {
2353 strided[row * self.stride..][..self.w]
2354 .copy_from_slice(&residual[row * self.w..][..self.w]);
2355 }
2356 strided
2357 }
2358}
2359
2360/// A recorded write's residual: already transformed, or the coefficients and
2361/// [`TxParams`] the worker transforms itself.
2362pub(crate) enum Residual {
2363 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2364 /// `len` is the all-zero marker [`dense_residual`] expands.
2365 Done(u32, u32),
2366 /// The coefficients live in the pushing tile's arena
2367 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2368 /// len)` in it.
2369 Coeffs(TxParams, u32, u32),
2370}
2371
2372impl Residual {
2373 /// The record for a transform unit whose coefficient grid is all zero:
2374 /// the empty marker, so neither the grid nor the residual is cloned and
2375 /// the worker never runs the transform (60% of the 4K segment's units).
2376 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2377 if is_zero_grid(grid) {
2378 return Self::Done(0, 0);
2379 }
2380 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2381 }
2382
2383 /// A residual the parse thread already transformed, kept in the arena
2384 /// instead of its own `Vec`.
2385 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2386 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2387 // which is exactly the all-zero marker -- one pointer compare instead
2388 // of copying up to 64 KB of zeros into the arena per block.
2389 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2390 return Self::Done(0, 0);
2391 }
2392 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2393 }
2394
2395 /// The residual to reconstruct with; `scratch` is where a transform run
2396 /// on this thread lands, so the caller owns that buffer.
2397 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2398 match self {
2399 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2400 Self::Coeffs(p, off, len) => {
2401 *scratch = p.run(&arena[off as usize..][..len as usize]);
2402 scratch
2403 }
2404 }
2405 }
2406}
2407
2408/// Appends to the tile's coefficient arena, returning the offset the record
2409/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2410fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2411 fctx.coeff_arena.with(|a| {
2412 let mut a = a.borrow_mut();
2413 let off = a.len();
2414 a.extend_from_slice(v);
2415 off as u32
2416 })
2417}
2418
2419/// [`push_coeffs`] for a recorded prediction.
2420fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2421 fctx.pred_arena.with(|a| {
2422 let mut a = a.borrow_mut();
2423 let off = a.len();
2424 a.extend_from_slice(v);
2425 off as u32
2426 })
2427}
2428
2429/// An all-zero residual, for the transform units that code no coefficient:
2430/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2431/// and the reconstruction loops below read this instead of a per-unit
2432/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2433/// (a 128-wide inter block's prediction stride).
2434pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2435
2436/// lane-blockscratch: one plane's coefficient levels as the block-tail
2437/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2438/// strip with no chroma, luma under a var-tx split whose units already wrote
2439/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2440/// zeroing up to 64 KB of its own per block.
2441#[derive(Clone)]
2442enum Grid {
2443 Zero(usize),
2444 Own(Vec<i32>),
2445}
2446
2447/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2448/// unit that writes into it. Only a block wider or taller than 64 px codes its
2449/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2450/// collectors per block and then drop them untouched.
2451fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2452 if v.is_empty() {
2453 *v = vec![0i32; n];
2454 }
2455 v
2456}
2457
2458impl std::ops::Deref for Grid {
2459 type Target = [i32];
2460 fn deref(&self) -> &[i32] {
2461 match self {
2462 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2463 Grid::Own(v) => v,
2464 }
2465 }
2466}
2467
2468/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2469/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2470/// transform units that code no coefficient without the scan (lane-coefgrid).
2471pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2472 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2473}
2474
2475/// `residual`, or `n` zeros when it is the empty all-zero marker.
2476fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2477 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2478}
2479
2480/// Where a recorded motion-compensated write reads its prediction from.
2481///
2482/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2483/// the parse thread's single biggest reconstruction cost, so at
2484/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2485/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2486/// runs it into its own three-plane slot, and every transform unit of that
2487/// block then reads its window out of that slot ([`Pred::Cur`]).
2488#[derive(Clone, Copy)]
2489pub(crate) enum Pred<'a> {
2490 /// A prediction the parse thread already built, at its own stride
2491 /// (`stride == 0` means "the reader's own `stride` argument").
2492 Inline(&'a [u16], usize),
2493 /// The current block's deferred prediction: plane, its stride, and this
2494 /// unit's offset into it.
2495 Cur { plane: usize, stride: usize, off: usize },
2496}
2497
2498impl<'a> Pred<'a> {
2499 /// The same prediction read at an explicit stride.
2500 fn view(self, stride: usize) -> Self {
2501 match self {
2502 Self::Inline(b, _) => Self::Inline(b, stride),
2503 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2504 }
2505 }
2506 /// The materialised buffer and the stride to read it at (`stride` is the
2507 /// reader's own when this prediction was built dense); `None` for a
2508 /// deferred prediction, which only a recorded op can carry.
2509 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2510 match self {
2511 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2512 Self::Cur { .. } => None,
2513 }
2514 }
2515 /// This prediction's window starting `n` samples in.
2516 fn offset(self, n: usize) -> Self {
2517 match self {
2518 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2519 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2520 }
2521 }
2522}
2523
2524/// [`Pred`], resolved into what a recorded op carries.
2525pub(crate) enum PredSrc {
2526 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2527 Owned(u32, u32),
2528 /// A window of the block prediction: its plane, its offset, and the
2529 /// stride it is read at -- which is the block's, not necessarily the
2530 /// op's (a transform unit's residual stays dense, so the worker takes
2531 /// its window out of the block prediction itself).
2532 Cur { plane: usize, off: usize, src: usize },
2533}
2534
2535/// One block's whole-block prediction build, deferred to a recon worker.
2536///
2537/// The closure borrows the tile's reference pictures and its own frame-level
2538/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2539/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2540/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2541pub(crate) struct PredBuild(
2542 Box<
2543 dyn FnOnce(
2544 &mut PlaneBuf<'static>,
2545 &mut PlaneBuf<'static>,
2546 &mut PlaneBuf<'static>,
2547 &crate::decode::FrameCtx,
2548 // lane-blockmem: the previous block's three prediction buffers,
2549 // refilled in place -- the build used to return three fresh
2550 // `Vec`s per block and drop these.
2551 &mut [Vec<u16>; 3],
2552 ),
2553 >,
2554);
2555
2556// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2557// pictures and frame tables, and the closure runs on exactly one worker.
2558#[allow(unsafe_code)]
2559unsafe impl Send for PredBuild {}
2560
2561/// `true` when this tile's writes are recorded for the wavefront instead of
2562/// performed at the push site, i.e. when a prediction may be deferred.
2563fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2564 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2565}
2566
2567/// The previous block's prediction buffer, cleared and zero-filled to `n`
2568/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2569/// without the per-block allocation and free.
2570fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2571 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2572 // than resized element by element -- which is every block on the inline
2573 // path, where there is no previous buffer to reuse.
2574 if v.capacity() < n {
2575 return vec![0u16; n];
2576 }
2577 v.clear();
2578 v.resize(n, 0);
2579 v
2580}
2581
2582/// Records one block's prediction build for the worker that reconstructs it.
2583#[allow(unsafe_code)]
2584fn push_pred<'a>(
2585 fctx: &crate::decode::FrameCtx,
2586 f: impl FnOnce(
2587 &mut PlaneBuf<'static>,
2588 &mut PlaneBuf<'static>,
2589 &mut PlaneBuf<'static>,
2590 &crate::decode::FrameCtx,
2591 &mut [Vec<u16>; 3],
2592 ) + 'a,
2593) {
2594 type Dyn<'x> = dyn FnOnce(
2595 &mut PlaneBuf<'static>,
2596 &mut PlaneBuf<'static>,
2597 &mut PlaneBuf<'static>,
2598 &crate::decode::FrameCtx,
2599 &mut [Vec<u16>; 3],
2600 ) + 'x;
2601 let boxed: Box<Dyn<'a>> = Box::new(f);
2602 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2603 // before the borrows the closure holds go out of scope.
2604 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2605 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2606}
2607
2608/// One superblock's recorded writes plus the two arenas they index -- the
2609/// unit a wavefront worker takes off the queue (lane-recoparse).
2610pub(crate) struct ReconJob {
2611 ops: Vec<ReconOp>,
2612 coeffs: Vec<i32>,
2613 preds: Vec<u16>,
2614}
2615
2616pub(crate) enum ReconOp {
2617 /// lane-wave4: build this block's prediction into the worker's slot.
2618 Pred(PredBuild),
2619 Intra {
2620 plane: usize,
2621 x: usize,
2622 y: usize,
2623 bw: usize,
2624 bh: usize,
2625 /// `true` when the parse site called `reconstruct_rect` (whose
2626 /// `edges_rect` differs from `edges` even at `bw == bh`).
2627 rect: bool,
2628 mode: usize,
2629 angle_delta: i32,
2630 reach: Reach,
2631 residual: Residual,
2632 cfl: Option<(i32, CflSrc)>,
2633 filter_intra: Option<usize>,
2634 smooth_neighbor: bool,
2635 /// The palette/intrabc prediction override, taken off
2636 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2637 /// from that slot by the replay.
2638 pred: Option<Vec<u16>>,
2639 },
2640 Mc {
2641 plane: usize,
2642 x: usize,
2643 y: usize,
2644 stride: usize,
2645 w: usize,
2646 h: usize,
2647 prediction: PredSrc,
2648 residual: Residual,
2649 },
2650}
2651
2652/// The three planes of the tile currently being decoded, as raw pointers.
2653///
2654/// corner-cut: at one reconstruction thread a recorded write must cost
2655/// nothing -- deferring it to the end of the superblock is +1.2%
2656/// instructions and +4.5% wall on 4K, because the residual is written at
2657/// parse and read back cache-cold at replay. So the recorded op is performed
2658/// at the push site instead, through the pointers the tile decoder registers
2659/// once ([`ReconInline`]), which is the same thread, the same order and the
2660/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2661/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2662/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2663/// threading the three planes down every `read_plane`/`read_inter_plane`
2664/// call site (~40) so the push site owns the borrow it writes through.
2665#[derive(Clone, Copy)]
2666pub(crate) struct ReconPlanes(
2667 *mut PlaneBuf<'static>,
2668 *mut PlaneBuf<'static>,
2669 *mut PlaneBuf<'static>,
2670);
2671
2672// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2673// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2674// value travelling is `None`; the pointers never leave the tile decoder's
2675// own thread.
2676#[allow(unsafe_code)]
2677unsafe impl Send for ReconPlanes {}
2678// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2679// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2680// contract, one superblock per band instead of one row band.
2681#[allow(unsafe_code)]
2682unsafe impl Sync for ReconPlanes {}
2683
2684/// Registers the tile's planes for inline reconstruction and unregisters them
2685/// on every exit from the tile decoder, including the `?` ones -- a stale
2686/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2687/// tile.
2688pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2689
2690#[allow(unsafe_code)]
2691impl<'a> ReconInline<'a> {
2692 /// Installs the guard for this tile when reconstruction is inline
2693 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2694 /// to the queue instead, for the wavefront workers to replay.
2695 fn install(
2696 fctx: &'a crate::decode::FrameCtx,
2697 y: &mut PlaneBuf<'static>,
2698 u: &mut PlaneBuf<'static>,
2699 v: &mut PlaneBuf<'static>,
2700 ) -> Option<Self> {
2701 if crate::par::recon_threads() != 1 {
2702 return None;
2703 }
2704 // SAFETY: the planes are locals of the tile decoder and outlive the
2705 // guard, which is dropped on every exit from it (including `?`); see
2706 // [`ReconPlanes`] for the aliasing trade-off.
2707 let planes = ReconPlanes(
2708 std::ptr::from_mut(y),
2709 std::ptr::from_mut(u),
2710 std::ptr::from_mut(v),
2711 );
2712 fctx.recon_planes.with(|c| c.set(Some(planes)));
2713 Some(Self(fctx))
2714 }
2715}
2716
2717impl Drop for ReconInline<'_> {
2718 fn drop(&mut self) {
2719 self.0.recon_planes.with(|c| c.set(None));
2720 }
2721}
2722
2723#[allow(unsafe_code)]
2724fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2725 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2726 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2727 // the parse site would have performed itself before lane-wave1.
2728 // The inline path never records coefficients (the transform runs at
2729 // the push site), so the arena is not read here.
2730 unsafe {
2731 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2732 };
2733 return;
2734 }
2735 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2736}
2737
2738/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2739/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2740///
2741/// The parser keeps parsing and never touches the planes; each superblock's
2742/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2743/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2744/// four of their 64x64 visits, since a 128 block writes across quadrants).
2745/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2746/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2747/// every pixel an intra predictor can read (its edges reach one block right
2748/// along the row above and one block down the column to the left, both
2749/// inside those two neighbours) and every CfL AC read (this block's own
2750/// luma, written by this same job). Jobs are handed out in raster order, so
2751/// the oldest outstanding one always has its dependencies met: no deadlock.
2752///
2753/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2754/// `thread_local!` and miss every worker, which is why the default is 1.
2755pub(crate) struct WaveState {
2756 q: std::sync::Mutex<WaveQueue>,
2757 cv: std::sync::Condvar,
2758 planes: ReconPlanes,
2759 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2760 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2761 bit_depth: u8,
2762 enable_edge_filter: bool,
2763 last_col: usize,
2764}
2765
2766struct WaveQueue {
2767 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2768 /// row's front job can ever be runnable -- a job waits on its own left
2769 /// neighbour -- so a worker takes the lowest row whose front job's
2770 /// dependencies are met. Popping the raster-oldest job instead (what
2771 /// this replaced) put every worker on the SAME row, where the wavefront
2772 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2773 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
2774 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2775 /// walking it.
2776 queued: usize,
2777 /// Per superblock row, the last column reconstructed (-1 = none yet).
2778 done: Vec<isize>,
2779 /// Per superblock row, the last column PARSED (submitted, whether or not
2780 /// it recorded any write) and the last column actually pushed as a job
2781 /// (-1 = none). A row is fully reconstructed once it has been parsed to
2782 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2783 /// reads that to release the row's filters (see [`wave_rows_complete`]).
2784 last_sub: Vec<isize>,
2785 last_push: Vec<isize>,
2786 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2787 active: usize,
2788 closed: bool,
2789 /// lane-sballoc: the three per-superblock buffers a finished job hands
2790 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
2791 /// first-touch page faults) instead of the `Vec::with_capacity` it used
2792 /// to make per superblock -- 3 allocations and 3 frees per superblock,
2793 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
2794 /// inside the queue's own mutex, which both sides already take.
2795 free: Vec<JobBufs>,
2796 free_cap: usize,
2797}
2798
2799/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
2800type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
2801
2802impl WaveQueue {
2803 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2804 /// or `None` (with the blocking condition counted when instrumented).
2805 fn take_runnable(
2806 &mut self,
2807 last_col: usize,
2808 stats: bool,
2809 ) -> Option<(usize, usize, ReconJob)> {
2810 let mut blocked: Option<bool> = None;
2811 for r in 0..self.rows.len() {
2812 let Some(front) = self.rows[r].front() else {
2813 continue;
2814 };
2815 let c = front.0;
2816 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2817 let left = c == 0 || self.done[r] >= c as isize - 1;
2818 if above && left {
2819 let (c, job) = self.rows[r].pop_front().expect("front checked above");
2820 self.queued -= 1;
2821 return Some((r, c, job));
2822 }
2823 if blocked.is_none() {
2824 blocked = Some(above);
2825 }
2826 }
2827 if stats {
2828 match blocked {
2829 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2830 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2831 None => 0,
2832 };
2833 }
2834 None
2835 }
2836}
2837
2838/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2839/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2840/// empty queue), how far ahead the parse thread is, and how often the two
2841/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2842/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2843/// whole run.
2844const WS_SLOTS: usize = 16;
2845use std::sync::atomic::AtomicU64;
2846use std::sync::atomic::Ordering::Relaxed;
2847static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2848static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2849static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2850static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2851static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2852static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2853/// Parse-thread time between two submits, i.e. everything parse still does
2854/// itself (symbol decode plus the predictions not deferred).
2855static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2856/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2857/// (the intrabc/interintra reads) and at the tile's end.
2858static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2859static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2860static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2861static WS_TILES: AtomicU64 = AtomicU64::new(0);
2862
2863fn wave_stats() -> bool {
2864 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2865 match ON.load(Relaxed) {
2866 0 => {
2867 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2868 .map(|v| v.trim() == "1")
2869 .unwrap_or(false);
2870 ON.store(1 + u8::from(on), Relaxed);
2871 on
2872 }
2873 n => n == 2,
2874 }
2875}
2876
2877fn wave_stats_dump() {
2878 let ms = |n: u64| n as f64 / 1e6;
2879 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2880 for i in 0..WS_SLOTS {
2881 let jobs = WS_JOBS[i].load(Relaxed);
2882 if jobs == 0 {
2883 continue;
2884 }
2885 s += &format!(
2886 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2887 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2888 ms(WS_BUSY[i].load(Relaxed)),
2889 ms(WS_WAIT[i].load(Relaxed)),
2890 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2891 );
2892 }
2893 s += &format!(
2894 " | pipe={}/{}",
2895 PIPE_FRAMES.load(Relaxed),
2896 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2897 );
2898 s += &format!(
2899 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2900 ms(WS_PARSE.load(Relaxed)),
2901 ms(WS_BARRIER.load(Relaxed)),
2902 WS_BARRIERS.load(Relaxed),
2903 ms(WS_DRAIN.load(Relaxed)),
2904 WS_BLOCK_ABOVE.load(Relaxed),
2905 WS_BLOCK_LEFT.load(Relaxed),
2906 );
2907 eprintln!("{s}");
2908}
2909
2910#[allow(unsafe_code)]
2911fn wave_worker(st: &WaveState, idx: usize) {
2912 let fctx = FrameCtx::new();
2913 fctx.bit_depth.set(st.bit_depth);
2914 fctx.enable_edge_filter.set(st.enable_edge_filter);
2915 let stats = wave_stats();
2916 let slot = idx.min(WS_SLOTS - 1);
2917 loop {
2918 let t0 = std::time::Instant::now();
2919 let mut q = st.q.lock().unwrap();
2920 let (r, c, job) = loop {
2921 if let Some(job) = q.take_runnable(st.last_col, stats) {
2922 break job;
2923 }
2924 if q.closed && q.queued == 0 {
2925 return;
2926 }
2927 q = st.cv.wait(q).unwrap();
2928 };
2929 q.active += 1;
2930 drop(q);
2931 if stats {
2932 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2933 WS_JOBS[slot].fetch_add(1, Relaxed);
2934 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
2935 }
2936 let t1 = std::time::Instant::now();
2937 let ReconPlanes(y, u, v) = st.planes;
2938 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2939 // every superblock that could have written or be reading them is
2940 // complete by the wavefront rule above.
2941 let mut cur: [Vec<u16>; 3] = Default::default();
2942 let ReconJob { mut ops, mut coeffs, mut preds } = job;
2943 unsafe {
2944 for op in ops.drain(..) {
2945 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
2946 }
2947 }
2948 if stats {
2949 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2950 }
2951 coeffs.clear();
2952 preds.clear();
2953 let mut q = st.q.lock().unwrap();
2954 // lane-sballoc: hand the three buffers back for the next submit.
2955 if q.free.len() < q.free_cap {
2956 q.free.push((ops, coeffs, preds));
2957 }
2958 q.done[r] = c as isize;
2959 q.active -= 1;
2960 st.cv.notify_all();
2961 }
2962}
2963
2964/// Installs the wavefront for one tile and joins its workers on every exit
2965/// from the tile decoder, including the `?` ones -- the jobs hold raw
2966/// pointers into the tile's planes, so no worker may outlive them.
2967/// (lane-pool1: the workers come from this thread's persistent pool, so a
2968/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
2969/// with fresh scratch.)
2970pub(crate) struct WaveGuard<'a>(
2971 &'a crate::decode::FrameCtx,
2972 Option<crate::par::Batch<'static>>,
2973);
2974
2975#[allow(unsafe_code)]
2976impl<'a> WaveGuard<'a> {
2977 fn install(
2978 fctx: &'a crate::decode::FrameCtx,
2979 y: &mut PlaneBuf<'static>,
2980 u: &mut PlaneBuf<'static>,
2981 v: &mut PlaneBuf<'static>,
2982 rows: usize,
2983 cols: usize,
2984 ) -> Option<Self> {
2985 let threads = crate::par::recon_threads();
2986 if threads == 1 || rows == 0 || cols == 0 {
2987 return None;
2988 }
2989 let st = std::sync::Arc::new(WaveState {
2990 q: std::sync::Mutex::new(WaveQueue {
2991 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2992 queued: 0,
2993 done: vec![-1; rows],
2994 last_sub: vec![-1; rows],
2995 last_push: vec![-1; rows],
2996 active: 0,
2997 closed: false,
2998 free: Vec::new(),
2999 free_cap: threads + 2,
3000 }),
3001 cv: std::sync::Condvar::new(),
3002 // SAFETY: the planes are locals of the tile decoder and outlive
3003 // this guard, which joins every worker in `drop`.
3004 planes: ReconPlanes(
3005 std::ptr::from_mut(y),
3006 std::ptr::from_mut(u),
3007 std::ptr::from_mut(v),
3008 ),
3009 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3010 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3011 last_col: cols - 1,
3012 });
3013 let batch = crate::par::Batch::new("ec-av1-recon");
3014 for idx in 0..threads {
3015 let st = std::sync::Arc::clone(&st);
3016 batch.submit(move || wave_worker(&st, idx));
3017 }
3018 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3019 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
3020 Some(Self(fctx, Some(batch)))
3021 }
3022}
3023
3024impl Drop for WaveGuard<'_> {
3025 fn drop(&mut self) {
3026 let st = self.0.wave.with(|w| w.borrow_mut().take());
3027 if let Some(st) = st {
3028 st.q.lock().unwrap().closed = true;
3029 st.cv.notify_all();
3030 }
3031 let t0 = std::time::Instant::now();
3032 // Dropping the batch waits every worker out, as the joins did.
3033 drop(self.1.take());
3034 if wave_stats() {
3035 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3036 WS_TILES.fetch_add(1, Relaxed);
3037 wave_stats_dump();
3038 }
3039 }
3040}
3041
3042/// An empty buffer for the next superblock: the recycled one when it is at
3043/// least as big as the superblock just parsed, else a fresh sized one
3044/// (lane-sballoc; `v` is always empty).
3045fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3046 if v.capacity() < cap {
3047 v.reserve_exact(cap - v.len());
3048 }
3049 v
3050}
3051
3052/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3053/// when there is no wavefront (one reconstruction thread), in which case the
3054/// caller replays them itself.
3055fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3056 let st = fctx.wave.with(|w| w.borrow().clone());
3057 let Some(st) = st else { return false };
3058 // lane-blockmem: the op list is replaced sized for the next superblock,
3059 // exactly as the two arenas below are -- taking it left a zero-capacity
3060 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3061 // every superblock.
3062 // lane-sballoc: the replacement comes from the finished jobs' free list
3063 // when there is one (warm capacity, already faulted in); only the first
3064 // superblocks of a tile allocate.
3065 let mut q = st.q.lock().unwrap();
3066 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3067 let ops = fctx.recon_ops.with(|c| {
3068 let mut c = c.borrow_mut();
3069 let cap = c.len();
3070 std::mem::replace(&mut *c, reuse(sops, cap))
3071 });
3072 // The job owns its coefficients: the arena is replaced by an empty one
3073 // sized for the next superblock, so parse never regrows from nothing and
3074 // the worker frees this buffer once, instead of once per unit.
3075 let coeffs = fctx.coeff_arena.with(|c| {
3076 let mut c = c.borrow_mut();
3077 let cap = c.len();
3078 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3079 });
3080 let preds = fctx.pred_arena.with(|c| {
3081 let mut c = c.borrow_mut();
3082 let cap = c.len();
3083 std::mem::replace(&mut *c, reuse(spreds, cap))
3084 });
3085 {
3086 if (c as isize) > q.last_sub[r] {
3087 q.last_sub[r] = c as isize;
3088 }
3089 if !ops.is_empty() {
3090 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3091 q.queued += 1;
3092 q.last_push[r] = c as isize;
3093 }
3094 drop(q);
3095 st.cv.notify_all();
3096 }
3097 if wave_stats() {
3098 let now = std::time::Instant::now();
3099 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3100 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3101 }
3102 }
3103 true
3104}
3105
3106/// Waits until every submitted job is reconstructed, so the parser may read
3107/// the planes itself (the intrabc source fetch and the interintra intra
3108/// predictor -- see [`flush_recon`]).
3109fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3110 let st = fctx.wave.with(|w| w.borrow().clone());
3111 let Some(st) = st else { return };
3112 let stats = wave_stats();
3113 let t0 = std::time::Instant::now();
3114 let mut q = st.q.lock().unwrap();
3115 while q.queued > 0 || q.active > 0 {
3116 q = st.cv.wait(q).unwrap();
3117 }
3118 drop(q);
3119 if stats {
3120 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3121 WS_BARRIERS.fetch_add(1, Relaxed);
3122 }
3123}
3124
3125/// Performs an intra write at its push site when the tile registered its
3126/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3127/// caller must record it for the wavefront workers instead.
3128#[allow(unsafe_code)]
3129#[allow(clippy::too_many_arguments)]
3130fn inline_intra(
3131 plane: usize,
3132 x: usize,
3133 oy: usize,
3134 bw: usize,
3135 bh: usize,
3136 rect: bool,
3137 mode: usize,
3138 angle_delta: i32,
3139 reach: Reach,
3140 residual: &[i32],
3141 cfl: Option<(i32, CflSrc)>,
3142 filter_intra: Option<usize>,
3143 smooth_neighbor: bool,
3144 fctx: &crate::decode::FrameCtx,
3145) -> bool {
3146 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3147 return false;
3148 };
3149 let pred = take_palette_pred(fctx);
3150 // SAFETY: see [`ReconPlanes`].
3151 unsafe {
3152 exec_intra(
3153 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3154 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
3155 );
3156 }
3157 true
3158}
3159
3160/// [`inline_intra`] for a motion-compensated write.
3161#[allow(unsafe_code)]
3162#[allow(clippy::too_many_arguments)]
3163fn inline_mc(
3164 plane: usize,
3165 x: usize,
3166 oy: usize,
3167 stride: usize,
3168 w: usize,
3169 h: usize,
3170 prediction: &[u16],
3171 residual: &[i32],
3172 fctx: &crate::decode::FrameCtx,
3173) -> bool {
3174 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3175 return false;
3176 };
3177 // SAFETY: see [`ReconPlanes`].
3178 unsafe {
3179 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
3180 }
3181 true
3182}
3183
3184/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3185#[allow(clippy::too_many_arguments)]
3186fn push_intra(
3187 plane: usize,
3188 x: usize,
3189 y: usize,
3190 side: usize,
3191 mode: usize,
3192 angle_delta: i32,
3193 reach: Reach,
3194 residual: &[i32],
3195 cfl: Option<(i32, CflSrc)>,
3196 filter_intra: Option<usize>,
3197 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3198) {
3199 if inline_intra(
3200 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3201 smooth_neighbor, fctx,
3202 ) {
3203 return;
3204 }
3205 let pred = take_palette_pred(fctx);
3206 push_op(fctx, ReconOp::Intra {
3207 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3208 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3209 });
3210}
3211
3212/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3213#[allow(clippy::too_many_arguments)]
3214fn push_intra_rect(
3215 plane: usize,
3216 x: usize,
3217 y: usize,
3218 bw: usize,
3219 bh: usize,
3220 mode: usize,
3221 angle_delta: i32,
3222 reach: Reach,
3223 residual: &[i32],
3224 cfl: Option<(i32, CflSrc)>,
3225 filter_intra: Option<usize>,
3226 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3227) {
3228 if inline_intra(
3229 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3230 smooth_neighbor, fctx,
3231 ) {
3232 return;
3233 }
3234 let pred = take_palette_pred(fctx);
3235 push_op(fctx, ReconOp::Intra {
3236 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3237 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3238 });
3239}
3240
3241/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3242fn push_mc(
3243 plane: usize,
3244 x: usize,
3245 y: usize,
3246 side: usize,
3247 prediction: Pred<'_>,
3248 residual: &[i32], fctx: &crate::decode::FrameCtx,
3249) {
3250 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3251}
3252
3253/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3254#[allow(clippy::too_many_arguments)]
3255fn push_mc_rect(
3256 plane: usize,
3257 x: usize,
3258 y: usize,
3259 stride: usize,
3260 w: usize,
3261 h: usize,
3262 prediction: Pred<'_>,
3263 residual: &[i32], fctx: &crate::decode::FrameCtx,
3264) {
3265 let (src, stride) = match prediction.inline(stride) {
3266 Some(v) => v,
3267 None => {
3268 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3269 push_op(fctx, ReconOp::Mc {
3270 plane, x, y, stride: ss, w, h,
3271 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3272 residual: Residual::done(residual, fctx),
3273 });
3274 return;
3275 }
3276 };
3277 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3278 return;
3279 }
3280 push_op(fctx, ReconOp::Mc {
3281 plane, x, y, stride, w, h,
3282 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3283 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3284 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3285 residual: Residual::done(residual, fctx),
3286 });
3287}
3288
3289/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3290/// thread the transform runs here, exactly as before; on the wavefront it
3291/// travels with the op and runs on the worker (lane-wave3).
3292#[allow(clippy::too_many_arguments)]
3293fn push_intra_tx(
3294 plane: usize,
3295 x: usize,
3296 y: usize,
3297 bw: usize,
3298 bh: usize,
3299 rect: bool,
3300 mode: usize,
3301 angle_delta: i32,
3302 reach: Reach,
3303 tx: TxParams,
3304 grid: &[i32],
3305 cfl: Option<(i32, CflSrc)>,
3306 filter_intra: Option<usize>,
3307 smooth_neighbor: bool,
3308 fctx: &crate::decode::FrameCtx,
3309) {
3310 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3311 inline_intra(
3312 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3313 smooth_neighbor, fctx,
3314 );
3315 return;
3316 }
3317 let pred = take_palette_pred(fctx);
3318 push_op(fctx, ReconOp::Intra {
3319 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3320 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3321 });
3322}
3323
3324/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3325#[allow(clippy::too_many_arguments)]
3326fn push_mc_rect_tx(
3327 plane: usize,
3328 x: usize,
3329 y: usize,
3330 stride: usize,
3331 w: usize,
3332 h: usize,
3333 prediction: Pred<'_>,
3334 tx: TxParams,
3335 grid: &[i32],
3336 fctx: &crate::decode::FrameCtx,
3337) {
3338 // lane-wave4: a deferred prediction is not there to be windowed -- the
3339 // op carries its offset into the block's prediction instead, and the
3340 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3341 // both buffers at one stride).
3342 let (prediction, stride) = match prediction.inline(stride) {
3343 Some(v) => v,
3344 None => {
3345 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3346 let mut tx = tx;
3347 tx.stride = 0;
3348 push_op(fctx, ReconOp::Mc {
3349 plane, x, y, stride: w, w, h,
3350 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3351 residual: Residual::coeffs(tx, grid, fctx),
3352 });
3353 return;
3354 }
3355 };
3356 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3357 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3358 // stride, so a prediction handed over at the block's stride (a var-tx
3359 // unit's window, lane-wave4) has to be densified for a dense residual
3360 // -- which is exactly what the recorded path below does.
3361 let residual = tx.run(grid);
3362 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3363 let window;
3364 let prediction = if stride == res_stride {
3365 prediction
3366 } else {
3367 debug_assert_eq!(res_stride, w);
3368 let mut win = Vec::with_capacity(w * h);
3369 for row in 0..h {
3370 win.extend_from_slice(&prediction[row * stride..][..w]);
3371 }
3372 window = win;
3373 &window[..]
3374 };
3375 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3376 return;
3377 }
3378 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3379 // two buffers at `stride`, so the record carries that window densely
3380 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3381 // copied 64*64 samples on the PARSING thread before. The residual is then
3382 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3383 // in the same places at stride `w`.
3384 let off = fctx.pred_arena.with(|a| {
3385 let mut a = a.borrow_mut();
3386 let off = a.len();
3387 for row in 0..h {
3388 a.extend_from_slice(&prediction[row * stride..][..w]);
3389 }
3390 off as u32
3391 });
3392 let mut tx = tx;
3393 tx.stride = 0;
3394 push_op(fctx, ReconOp::Mc {
3395 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3396 residual: Residual::coeffs(tx, grid, fctx),
3397 });
3398}
3399
3400/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3401/// and empties the queue (lane-wave1 step (i)).
3402///
3403/// Called at the top of each superblock visit and at the end of each tile, so
3404/// a whole superblock's parsing runs with no plane access at all; the two
3405/// parse-time pixel READS that survive -- the intrabc source fetch and the
3406/// interintra intra predictor -- flush ahead of themselves instead, which
3407/// keeps them byte-exact and names exactly what step (ii) still has to move.
3408fn flush_recon(
3409 fctx: &crate::decode::FrameCtx,
3410 y: &mut PlaneBuf<'static>,
3411 u: &mut PlaneBuf<'static>,
3412 v: &mut PlaneBuf<'static>,
3413) {
3414 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3415 // writes in place, not just this superblock's queue.
3416 wave_barrier(fctx);
3417 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3418 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3419 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3420 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3421 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3422 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3423 let mut cur: [Vec<u16>; 3] = Default::default();
3424 for op in ops.drain(..) {
3425 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3426 }
3427 coeffs.clear();
3428 preds.clear();
3429 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3430 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3431 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3432}
3433
3434/// Performs one recorded write: the body [`flush_recon`] replays, and the
3435/// body [`push_op`] runs immediately when reconstruction is inline.
3436fn exec_op(
3437 op: ReconOp,
3438 y: &mut PlaneBuf<'static>,
3439 u: &mut PlaneBuf<'static>,
3440 v: &mut PlaneBuf<'static>,
3441 cur: &mut [Vec<u16>; 3],
3442 coeffs: &[i32],
3443 preds: &[u16],
3444 fctx: &crate::decode::FrameCtx,
3445) {
3446 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
3447 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
3448 // alone. It makes the encoder's own streams garbage, so it is a
3449 // MEASUREMENT rung only -- what it measures is how much of the encoder's
3450 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
3451 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
3452 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
3453 // stage and the parse plus the neighbour grids are the other 94%. That
3454 // is why handing the decoder the encoder's own reconstruction cannot
3455 // shrink the stage: only publishing the per-mi neighbour state the
3456 // filters read (and so never parsing at all) can.
3457 if crate::envflags::env_flag!("EC_AV1_NORECON") {
3458 return;
3459 }
3460 let mut scratch = Vec::new();
3461 match op {
3462 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3463 ReconOp::Intra {
3464 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3465 filter_intra, smooth_neighbor, pred,
3466 } => exec_intra(
3467 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3468 residual.resolve(coeffs, &mut scratch),
3469 cfl, filter_intra, smooth_neighbor, pred, fctx,
3470 ),
3471 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3472 let residual = residual.resolve(coeffs, &mut scratch);
3473 match prediction {
3474 PredSrc::Owned(off, len) => {
3475 let p = &preds[off as usize..][..len as usize];
3476 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3477 }
3478 PredSrc::Cur { plane: sp, off, src } => {
3479 let block = std::mem::take(&mut cur[sp]);
3480 if src == stride {
3481 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3482 } else {
3483 // A transform unit's residual is dense, so its window
3484 // of the block prediction is taken out dense too --
3485 // the copy the parsing thread used to make, made here.
3486 let mut window = Vec::with_capacity(w * h);
3487 for row in 0..h {
3488 window.extend_from_slice(&block[off + row * src..][..w]);
3489 }
3490 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3491 }
3492 cur[sp] = block;
3493 }
3494 }
3495 }
3496 }
3497}
3498
3499/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3500/// path ([`push_op`]'s registered planes) reaches it without ever building
3501/// the record -- which is what keeps one reconstruction thread at the cost of
3502/// the pre-lane-wave1 decoder.
3503#[allow(clippy::too_many_arguments)]
3504fn exec_intra(
3505 y: &mut PlaneBuf<'static>,
3506 u: &mut PlaneBuf<'static>,
3507 v: &mut PlaneBuf<'static>,
3508 plane: usize,
3509 x: usize,
3510 oy: usize,
3511 bw: usize,
3512 bh: usize,
3513 rect: bool,
3514 mode: usize,
3515 angle_delta: i32,
3516 reach: Reach,
3517 residual: &[i32],
3518 cfl: Option<(i32, CflSrc)>,
3519 filter_intra: Option<usize>,
3520 smooth_neighbor: bool,
3521 pred: Option<Vec<u16>>,
3522 fctx: &crate::decode::FrameCtx,
3523) {
3524 // The CfL AC signal is read HERE, off the luma that has already been
3525 // written for this block -- at parse time it would have been the previous
3526 // frame's samples.
3527 let ac = cfl.map(|(alpha, src)| {
3528 let sig = if src.rect {
3529 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3530 } else {
3531 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3532 };
3533 (alpha, sig)
3534 });
3535 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3536 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3537 if rect {
3538 target.reconstruct_rect(
3539 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3540 smooth_neighbor, pred, fctx,
3541 );
3542 } else {
3543 target.reconstruct(
3544 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3545 smooth_neighbor, pred, fctx,
3546 );
3547 }
3548}
3549
3550/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3551#[allow(clippy::too_many_arguments)]
3552fn exec_mc(
3553 y: &mut PlaneBuf<'static>,
3554 u: &mut PlaneBuf<'static>,
3555 v: &mut PlaneBuf<'static>,
3556 plane: usize,
3557 x: usize,
3558 oy: usize,
3559 stride: usize,
3560 w: usize,
3561 h: usize,
3562 prediction: &[u16],
3563 residual: &[i32],
3564 fctx: &crate::decode::FrameCtx,
3565) {
3566 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3567 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3568}
3569
3570thread_local! {
3571 /// The current frame's `mi` grid, kept only while a frame header set
3572 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3573 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3574 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3575 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3576 /// does not allow intrabc (so nothing is paid for it).
3577 ///
3578 /// corner-cut: only [`decode_block`] (the square path) records into it,
3579 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3580 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3581 /// be wrong there; upgrade = record from the rect/leaf paths too.
3582 /// The block vector [`read_intra_mode`] just decoded, handed to
3583 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3584 /// which the alternative -- a tenth tuple member through every caller --
3585 /// already avoids). Always `.take()`n by the block that reads it.
3586 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
3587 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3588}
3589 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3590 // an intrabc block's chroma reads can inherit it (see
3591 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3592 // through that one arming site.
3593 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3594 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3595 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3596 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3597 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3598 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3599 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3600 // -- getting it wrong desyncs the chroma coefficients, it is not a
3601 // reconstruction-only detail.
3602
3603/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3604/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3605/// needs no separate plumbing to reach the rect-strip mode reader.
3606fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3607 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3608}
3609
3610thread_local! {
3611 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3612 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3613 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3614 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3615}
3616
3617/// Current value of [`RECT_INTRABC_READS`].
3618pub(crate) fn rect_intrabc_reads() -> usize {
3619 RECT_INTRABC_READS.with(|c| c.get())
3620}
3621
3622/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3623#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3624pub(crate) fn reset_rect_intrabc_reads() {
3625 RECT_INTRABC_READS.with(|c| c.set(0));
3626}
3627
3628thread_local! {
3629 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3630 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3631 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3632}
3633
3634/// Current value of [`LEAF8_INTRABC_HITS`].
3635pub(crate) fn leaf8_intrabc_hits() -> usize {
3636 LEAF8_INTRABC_HITS.with(|c| c.get())
3637}
3638
3639/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3640#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3641pub(crate) fn reset_leaf8_intrabc_hits() {
3642 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3643}
3644
3645/// Current value of [`INTRABC_HITS`].
3646#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3647pub(crate) fn intrabc_hits() -> usize {
3648 INTRABC_HITS.with(|c| c.get())
3649}
3650
3651/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3652#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3653pub(crate) fn reset_intrabc_hits() {
3654 INTRABC_HITS.with(|c| c.set(0));
3655}
3656
3657thread_local! {
3658 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3659 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3660 /// that replaced the refusal "an intrabc block under TxMode::Select".
3661 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3662}
3663
3664/// Current value of [`INTRABC_VARTX_HITS`].
3665#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3666pub(crate) fn intrabc_vartx_hits() -> usize {
3667 INTRABC_VARTX_HITS.with(|c| c.get())
3668}
3669
3670/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3671#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3672pub(crate) fn reset_intrabc_vartx_hits() {
3673 INTRABC_VARTX_HITS.with(|c| c.set(0));
3674}
3675
3676/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3677/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3678/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3679/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3680fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
3681 fctx.intrabc_mi_grid.with(|g| {
3682 let mut g = g.borrow_mut();
3683 let Some((grid, _, _)) = g.as_mut() else {
3684 return;
3685 };
3686 let info = crate::mvstack::MiInfo {
3687 is_inter: dv.is_some(),
3688 ref_frame: 0,
3689 ref_frame1: NO_REF1,
3690 mv: mv16(dv.unwrap_or((0, 0))),
3691 mv1: (0, 0),
3692 is_new_mv: dv.is_some(),
3693 is_global_mv0: false,
3694 is_global_mv1: false,
3695 size: n4 as u8,
3696 size_h: n4 as u8,
3697 };
3698 for r in mi_r..mi_r + n4 {
3699 for c in mi_c..mi_c + n4 {
3700 grid.set(r, c, info);
3701 }
3702 }
3703 });
3704}
3705
3706// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3707// proves a real `skip_mode_present` stream actually reached a block that
3708// picked it, not just that the frame header bit was set.
3709thread_local! {
3710 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3711 const { std::cell::Cell::new(0) };
3712}
3713
3714/// Current value of [`SKIP_MODE_HITS`].
3715#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3716pub(crate) fn skip_mode_hits() -> usize {
3717 SKIP_MODE_HITS.with(|c| c.get())
3718}
3719
3720// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3721// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3722// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3723// reached [`obmc_blend`], not just the header bit.
3724thread_local! {
3725 static OBMC_HITS: std::cell::Cell<usize> =
3726 const { std::cell::Cell::new(0) };
3727}
3728
3729// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3730// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3731// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3732// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3733// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3734// decoder used to read with the wrong alphabet, so a gate that asserts this
3735// counter advanced proves the fixed path fired (class
3736// `gate-blind-to-feature`).
3737thread_local! {
3738 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3739}
3740
3741/// Current value of [`FIMV_ALPHABET_HITS`].
3742pub fn fimv_alphabet_hits() -> usize {
3743 FIMV_ALPHABET_HITS.with(|c| c.get())
3744}
3745
3746// lane-fimv r1: how many frame headers this decoder has decoded with
3747// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3748// prove the encoder really produced the header state under test rather than
3749// assume it.
3750thread_local! {
3751 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3752}
3753
3754/// Current value of [`FIMV_FRAME_HITS`].
3755pub fn fimv_frame_hits() -> usize {
3756 FIMV_FRAME_HITS.with(|c| c.get())
3757}
3758
3759/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3760/// `force_integer_mv` bit is set.
3761pub fn note_force_integer_mv_frame() {
3762 hit!(FIMV_FRAME_HITS);
3763}
3764
3765/// Current value of [`OBMC_HITS`].
3766#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3767pub(crate) fn obmc_hits() -> usize {
3768 OBMC_HITS.with(|c| c.get())
3769}
3770
3771// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3772// off the neighbour band -- the positive half of the proof for "an OBMC
3773// neighbour whose switchable interp filter was never recorded". A
3774// fixed-filter frame returns before this point (its neighbours legitimately
3775// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3776// `interp_filter` symbols were published by `record_inter_rect_mi`.
3777thread_local! {
3778 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3779}
3780
3781/// Current value of [`OBMC_FILTER_BAND_READS`].
3782#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3783pub(crate) fn obmc_filter_band_reads() -> usize {
3784 OBMC_FILTER_BAND_READS.with(|c| c.get())
3785}
3786
3787// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3788// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3789// reference would pass just as well and prove nothing, so the gate
3790// hard-asserts each combination this round lifts actually occurred:
3791// a compound block with a scaled tap, a warp block whose warp libaom
3792// suppresses because the reference is scaled, an OBMC block, an interintra
3793// block, and an 8x8 leaf.
3794thread_local! {
3795 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3796 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3797 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3798 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3799 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3800 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3801 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3802}
3803
3804/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
3805/// scaled and one unscaled tap.
3806#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3807pub(crate) fn mixed_scale_compound_hits() -> usize {
3808 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
3809}
3810
3811/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
3812/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
3813/// instead because their reference is scaled (libaom `motion_mode_allowed`,
3814/// `blockd.h:1484`).
3815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3816pub(crate) fn scaled_warp_suppressed_hits() -> usize {
3817 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
3818}
3819
3820/// Current value of [`SCALED_COMPOUND_HITS`].
3821#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3822pub(crate) fn scaled_compound_hits() -> usize {
3823 SCALED_COMPOUND_HITS.with(|c| c.get())
3824}
3825
3826/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
3827pub fn scaled_warp_fallback_hits() -> usize {
3828 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
3829}
3830
3831/// Current value of [`SCALED_OBMC_HITS`].
3832#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3833pub(crate) fn scaled_obmc_hits() -> usize {
3834 SCALED_OBMC_HITS.with(|c| c.get())
3835}
3836
3837/// Current value of [`SCALED_INTERINTRA_HITS`].
3838#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3839pub(crate) fn scaled_interintra_hits() -> usize {
3840 SCALED_INTERINTRA_HITS.with(|c| c.get())
3841}
3842
3843/// Current value of [`SCALED_BLOCK8_HITS`].
3844#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3845pub(crate) fn scaled_block8_hits() -> usize {
3846 SCALED_BLOCK8_HITS.with(|c| c.get())
3847}
3848
3849// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
3850// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
3851// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
3852// 8x8-leaf OBMC block apart from a 16x16+ one.
3853thread_local! {
3854 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3855}
3856
3857// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
3858// pair whose two directions differ (`enable_dual_filter` only -- with dual
3859// filter off both directions take the single symbol, so this can never fire).
3860// A gate asserting it proves the stream really carries dual-filter blocks.
3861thread_local! {
3862 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3863}
3864
3865// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
3866// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
3867// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
3868// no-filter sentinel that made a neighbouring OBMC block panic).
3869thread_local! {
3870 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3871}
3872
3873/// Current value of [`DUAL_FILTER_DIFF_HITS`].
3874#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3875pub(crate) fn dual_filter_diff_hits() -> usize {
3876 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
3877}
3878
3879/// Current value of [`COMPOUND8_FILTER_HITS`].
3880#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3881pub(crate) fn compound8_filter_hits() -> usize {
3882 COMPOUND8_FILTER_HITS.with(|c| c.get())
3883}
3884
3885// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
3886// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
3887// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
3888// -- the gate's proof that a fixture really exercises the alphabet this
3889// round changed, even though the block itself still refuses (warp
3890// estimation/filter not ported).
3891thread_local! {
3892 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
3893 const { std::cell::Cell::new(0) };
3894}
3895
3896/// Current value of [`WARP_SELECTED_HITS`].
3897#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3898pub(crate) fn warp_selected_hits() -> usize {
3899 WARP_SELECTED_HITS.with(|c| c.get())
3900}
3901
3902// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
3903// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
3904// into the compound intermediate) rather than translationally -- the
3905// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
3906// really reached [`crate::warp::warp_affine_compound`].
3907thread_local! {
3908 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
3909 const { std::cell::Cell::new(0) };
3910}
3911
3912/// Current value of [`COMPOUND_WARP_HITS`].
3913#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3914pub(crate) fn compound_warp_hits() -> usize {
3915 COMPOUND_WARP_HITS.with(|c| c.get())
3916}
3917
3918// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
3919// arm ([`decode_inter_block8`]) -- that arm predicted both taps
3920// translationally until r3, so a gate needs to tell a warped 8x8 compound
3921// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
3922thread_local! {
3923 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
3924 const { std::cell::Cell::new(0) };
3925}
3926
3927/// Current value of [`COMPOUND_WARP_HITS_8`].
3928#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3929pub(crate) fn compound_warp_hits_8() -> usize {
3930 COMPOUND_WARP_HITS_8.with(|c| c.get())
3931}
3932
3933// lane-gmaffine r1: how many blocks built their prediction from a
3934// SIX-parameter (`AFFINE`) global-motion model through
3935// `crate::warp::global_warp_params` -- the gate's proof that a stream really
3936// carried an AFFINE `global_motion_params` AND that a block was predicted
3937// with it, not merely that the header parsed one.
3938thread_local! {
3939 static AFFINE_GM_HITS: std::cell::Cell<usize> =
3940 const { std::cell::Cell::new(0) };
3941}
3942
3943/// Current value of [`AFFINE_GM_HITS`].
3944#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3945pub(crate) fn affine_gm_hits() -> usize {
3946 AFFINE_GM_HITS.with(|c| c.get())
3947}
3948
3949// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
3950// differently at the block's WIDTH than at libaom's
3951// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
3952// pick the wrong motion_mode alphabet.
3953thread_local! {
3954 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3955}
3956
3957/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
3958pub fn tr_reach_longer_side_hits() -> usize {
3959 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
3960}
3961
3962// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
3963// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
3964// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
3965// reads its interp-filter symbol. Counts the blocks where that guard flips
3966// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
3967// and a 4-px side, which we used to suppress the interp read on (a pre-mode
3968// entropy desync one symbol wide).
3969thread_local! {
3970 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3971}
3972
3973/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
3974pub fn gm_nontrans_small_side_hits() -> usize {
3975 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
3976}
3977
3978// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
3979// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
3980// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
3981// only once `find_projection` returned a usable model, unlike
3982// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
3983// proof that the leaf path itself fired, not the 16x16+ one.
3984thread_local! {
3985 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3986 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3987}
3988
3989/// Current value of [`GLOBALMV_HITS_8`].
3990#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3991pub(crate) fn globalmv_hits_8() -> usize {
3992 GLOBALMV_HITS_8.with(|c| c.get())
3993}
3994
3995/// Current value of [`WARP_HITS_8`].
3996#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3997pub(crate) fn warp_hits_8() -> usize {
3998 WARP_HITS_8.with(|c| c.get())
3999}
4000
4001// How many blocks decoded `interintra == 1` with the non-wedge blended
4002// prediction applied (lane-interintra r1) -- the gate's proof that a
4003// stream actually exercised interintra.
4004thread_local! {
4005 static INTERINTRA_HITS: std::cell::Cell<usize> =
4006 const { std::cell::Cell::new(0) };
4007}
4008
4009/// Current value of [`INTERINTRA_HITS`].
4010#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4011pub(crate) fn interintra_hits() -> usize {
4012 INTERINTRA_HITS.with(|c| c.get())
4013}
4014
4015// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
4016// -- the shape `interintra_blend` used to build a square `side x side` intra
4017// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
4018// pre-existing interintra gate passed with that bug, so the rect arm needs
4019// its own counter to stop being vacuous.
4020thread_local! {
4021 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4022}
4023
4024/// Current value of [`INTERINTRA_RECT_HITS`].
4025pub fn interintra_rect_hits() -> usize {
4026 INTERINTRA_RECT_HITS.with(|c| c.get())
4027}
4028
4029// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
4030// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
4031// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
4032// gate fixture actually exercises this alphabet, even though the block
4033// still refuses (the mask blend itself is unported).
4034thread_local! {
4035 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4036 const { std::cell::Cell::new(0) };
4037}
4038
4039/// Current value of [`MASKED_COMPOUND_HITS`].
4040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4041pub(crate) fn masked_compound_hits() -> usize {
4042 MASKED_COMPOUND_HITS.with(|c| c.get())
4043}
4044
4045// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
4046// masked-compound block whose true footprint is rectangular, i.e. the case
4047// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
4048// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
4049// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
4050thread_local! {
4051 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4052 const { std::cell::Cell::new(0) };
4053}
4054
4055/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
4056#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4057pub(crate) fn rect_masked_compound_hits() -> usize {
4058 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
4059}
4060
4061// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
4062// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
4063// actually exercised the wedge blend, not just the DIFFWTD half of
4064// `MASKED_COMPOUND_HITS`.
4065thread_local! {
4066 static WEDGE_HITS: std::cell::Cell<usize> =
4067 const { std::cell::Cell::new(0) };
4068}
4069
4070/// Current value of [`WEDGE_HITS`].
4071#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4072pub(crate) fn wedge_hits() -> usize {
4073 WEDGE_HITS.with(|c| c.get())
4074}
4075
4076// How many blocks decoded a real wedge-INTERINTRA block
4077// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
4078// a gate fixture exercised the wedge blend (fixed sign 0), not just the
4079// smooth arm counted by `INTERINTRA_HITS`.
4080thread_local! {
4081 static WII_HITS: std::cell::Cell<usize> =
4082 const { std::cell::Cell::new(0) };
4083}
4084
4085/// Current value of [`WII_HITS`].
4086#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4087pub(crate) fn wii_hits() -> usize {
4088 WII_HITS.with(|c| c.get())
4089}
4090
4091// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
4092// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
4093// wide <= 32 && high <= 32). The witness that a gate stream really carries a
4094// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
4095// frame carrying one.
4096thread_local! {
4097 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4098}
4099
4100/// Current value of [`NOCFL_UV_MODE_HITS`].
4101#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4102pub(crate) fn nocfl_uv_mode_hits() -> usize {
4103 NOCFL_UV_MODE_HITS.with(|c| c.get())
4104}
4105
4106/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
4107/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
4108pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
4109 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
4110
4111fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
4112 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
4113}
4114
4115// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
4116// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
4117// the rect wedge masks lifted this round actually fired, not just the square
4118// ones already counted by `WEDGE_HITS`/`WII_HITS`.
4119thread_local! {
4120 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4121 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4122}
4123
4124/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4125pub(crate) fn rect_wedge_hits() -> [usize; 6] {
4126 RECT_WEDGE_HITS.with(|c| c.get())
4127}
4128
4129/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4130pub(crate) fn rect_wii_hits() -> [usize; 6] {
4131 RECT_WII_HITS.with(|c| c.get())
4132}
4133
4134// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
4135// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
4136// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
4137// aomdec, neighbour list included).
4138thread_local! {
4139 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4140}
4141
4142/// Current value of [`OBMC_RECT_LEAF_HITS`].
4143pub(crate) fn obmc_rect_leaf_hits() -> usize {
4144 OBMC_RECT_LEAF_HITS.with(|c| c.get())
4145}
4146
4147// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
4148// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
4149// to be read from the pair's FIRST mi, which is a different block and, when
4150// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
4151// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
4152thread_local! {
4153 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4154}
4155
4156/// Current value of [`OBMC_PAIR_FILTER_HITS`].
4157pub(crate) fn obmc_pair_filter_hits() -> usize {
4158 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
4159}
4160
4161// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
4162// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
4163// own side, so a block overhanging the bottom/right still predicts the full
4164// neighbour strip (the destination write is what clips). We used to shrink the
4165// prediction to the visible part, which at 4 chroma rows/cols also swaps the
4166// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
4167thread_local! {
4168 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4169}
4170
4171/// Current value of [`OBMC_EDGE_SPAN_HITS`].
4172#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4173pub(crate) fn obmc_edge_span_hits() -> usize {
4174 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
4175}
4176
4177/// Current value of [`OBMC_HITS_8`].
4178#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4179pub(crate) fn obmc_hits_8() -> usize {
4180 OBMC_HITS_8.with(|c| c.get())
4181}
4182
4183// lane-rectgate r1: how many 32x32 quadrants actually decoded a
4184// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
4185// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
4186// `VERT_B` all still fall into the generic "a partition type this encoder
4187// never writes" refusal below) -- the gate's proof that a free-partition
4188// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
4189// coincidentally never selecting one.
4190thread_local! {
4191 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
4192 const { std::cell::Cell::new(0) };
4193}
4194
4195/// Current value of [`EXTENDED_PARTITION_HITS`].
4196#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4197pub(crate) fn extended_partition_hits() -> usize {
4198 EXTENDED_PARTITION_HITS.with(|c| c.get())
4199}
4200
4201// lane-partitions r1: how many 32x32 quadrants decoded a real
4202// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
4203// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
4204// gate's proof this round's arms actually fired.
4205thread_local! {
4206 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
4207 const { std::cell::Cell::new(0) };
4208}
4209
4210/// Current value of [`RECT_PARTITION_HITS`].
4211#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4212pub(crate) fn rect_partition_hits() -> usize {
4213 RECT_PARTITION_HITS.with(|c| c.get())
4214}
4215
4216// lane-inter8 r1: how many superblocks an inter tile coded as a single
4217// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4218// static content, previously a named refusal).
4219thread_local! {
4220 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4221 /// path decoded as one whole block (its gate's own witness).
4222 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4223 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4224 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4225 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4226}
4227
4228/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4229pub(crate) fn inter_sb128_horz_hits() -> usize {
4230 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4231}
4232
4233/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4234pub(crate) fn inter_sb128_vert_hits() -> usize {
4235 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4236}
4237
4238/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4239pub fn inter_sb128_none_hits() -> usize {
4240 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4241}
4242
4243thread_local! {
4244 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4245 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4246 /// units) -- the gate's witness that the lifted refusal's case fired.
4247 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4248}
4249
4250/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4251pub fn intra_128_in_inter_hits() -> usize {
4252 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4253}
4254
4255thread_local! {
4256 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4257 const { std::cell::Cell::new(0) };
4258}
4259
4260/// Current value of [`INTER_SB_NONE_HITS`].
4261#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4262pub(crate) fn inter_sb_none_hits() -> usize {
4263 INTER_SB_NONE_HITS.with(|c| c.get())
4264}
4265
4266// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4267// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4268// path has always run that loop, so only this counter proves the newly-lifted
4269// alphabet value fired.
4270thread_local! {
4271 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4272 const { std::cell::Cell::new(0) };
4273}
4274
4275/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4276#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4277pub(crate) fn inter_sub16_split_hits() -> usize {
4278 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4279}
4280
4281// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4282// while at least one reference picture was SCALED (superres) -- the counter
4283// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4284thread_local! {
4285 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4286 const { std::cell::Cell::new(0) };
4287}
4288
4289/// Current value of [`SCALED_LEAF8_HITS`].
4290pub fn scaled_leaf8_hits() -> usize {
4291 SCALED_LEAF8_HITS.with(|c| c.get())
4292}
4293
4294// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4295// rect pair) were predicted from a SCALED reference -- the counter behind the
4296// lifted "sub-8x8 inter block under a scaled reference" refusal.
4297thread_local! {
4298 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4299 const { std::cell::Cell::new(0) };
4300}
4301
4302/// Current value of [`SCALED_SUB8_HITS`].
4303pub fn scaled_sub8_hits() -> usize {
4304 SCALED_SUB8_HITS.with(|c| c.get())
4305}
4306
4307// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4308// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4309// rect coefficient reader itself fired, not just the strip-level partition
4310// symbol [`RECT_PARTITION_HITS`] already counts.
4311thread_local! {
4312 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4313 const { std::cell::Cell::new(0) };
4314}
4315
4316/// Current value of [`RECT_COEFF_HITS`].
4317#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4318pub(crate) fn rect_coeff_hits() -> usize {
4319 RECT_COEFF_HITS.with(|c| c.get())
4320}
4321
4322// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4323// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4324// charter's real-aomenc gate hard-asserts.
4325thread_local! {
4326 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4327 const { std::cell::Cell::new(0) };
4328}
4329
4330/// Current value of [`RECT_LEAF_COEFF_HITS`].
4331#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4332pub(crate) fn rect_leaf_coeff_hits() -> usize {
4333 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4334}
4335
4336// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4337// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4338// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4339// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4340// needs rectangular intra prediction" before this round.
4341thread_local! {
4342 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4343 const { std::cell::Cell::new([0; 3]) };
4344}
4345
4346/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4347/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4348#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4349pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4350 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4351}
4352
4353// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4354// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4355// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4356// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4357// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4358// a single counter cannot tell an axis swap from a working arm
4359// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4360thread_local! {
4361 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4362 const { std::cell::Cell::new([0; 2]) };
4363}
4364
4365/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4366/// (0 = 64x32, 1 = 32x64).
4367pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4368 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4369}
4370
4371// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4372// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4373// is never incremented) -- the gate's proof that the lifted path ran per depth.
4374thread_local! {
4375 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4376 const { std::cell::Cell::new([0; 3]) };
4377}
4378
4379// lane-t900 r21: rect intra strips inside an inter frame that read the
4380// screen-content palette syntax (`allow_screen_content_tools` set and the
4381// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4382// refusal used to guard, so this counter is what keeps its witness gate
4383// non-vacuous.
4384thread_local! {
4385 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4386}
4387
4388/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4389#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4390pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4391 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4392}
4393
4394/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4395#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4396pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4397 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4398}
4399
4400/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4401#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4402pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4403 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4404}
4405
4406// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
4407// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
4408// the blocks the key frame's deblock-grid approximation used to mis-read.
4409thread_local! {
4410 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
4411 const { std::cell::Cell::new(0) };
4412}
4413
4414/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
4415#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4416pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
4417 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
4418}
4419
4420// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4421// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4422// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4423// rect strip on the inter block path" before this round.
4424thread_local! {
4425 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4426 const { std::cell::Cell::new([0; 4]) };
4427}
4428
4429/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4430/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4431pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4432 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4433}
4434
4435// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4436// through one of the key-frame rect readers ([`decode_block_rect4`],
4437// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4438// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4439// already read by [`decode_inter_block`] and (b) the luma mode comes off
4440// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4441// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4442
4443// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4444// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4445// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4446// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4447thread_local! {
4448 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4449 const { std::cell::Cell::new(0) };
4450}
4451
4452/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4453#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4454pub(crate) fn mode_mi_override_hits() -> usize {
4455 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4456}
4457
4458// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4459// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4460// mode from the previous tile, where libaom's `up_available`/`left_available`
4461// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4462// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4463// per superblock row in `start_row`, so the luma fallback cannot leak the way
4464// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4465// the invariant that makes the coarse fallback safe.
4466thread_local! {
4467 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4468 const { std::cell::Cell::new(0) };
4469}
4470
4471/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4472#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4473pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4474 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4475}
4476
4477// lane-cfl r1: how many times a chroma intra-edge filter-type read
4478// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4479// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4480// r1 defect would have filtered a chroma edge with the wrong strength.
4481thread_local! {
4482 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4483 const { std::cell::Cell::new(0) };
4484}
4485
4486/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4487#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4488pub(crate) fn uv_mode_mi_override_hits() -> usize {
4489 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4490}
4491
4492// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4493// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4494// answered differently -- the sub-8x8 pair case where the pair's own first
4495// half had already overwritten the column slot the chroma-ref half reads.
4496thread_local! {
4497 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4498 const { std::cell::Cell::new(0) };
4499}
4500
4501/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4502pub fn uv_mode_grid_override_hits() -> usize {
4503 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4504}
4505
4506// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4507// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4508// from an earlier block in that pixel row/column while the mi-exact map --
4509// which an inter block only started writing this round -- correctly says the
4510// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4511// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4512thread_local! {
4513 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4514 const { std::cell::Cell::new(0) };
4515}
4516
4517/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4518#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4519pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4520 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4521}
4522
4523// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4524// suppressed at a TILE edge that is not a frame edge -- the above/left
4525// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4526// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4527// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4528// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4529// above would decide this tile's chroma edge filter strength.
4530thread_local! {
4531 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4532 const { std::cell::Cell::new(0) };
4533}
4534
4535/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4536#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4537pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4538 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4539}
4540
4541// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4542// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4543// shapes the r1 chroma defect showed up on.
4544thread_local! {
4545 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4546 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4547}
4548
4549/// Current value of [`CFL_BLOCK_HITS`].
4550#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4551pub(crate) fn cfl_block_hits() -> usize {
4552 CFL_BLOCK_HITS.with(|c| c.get())
4553}
4554
4555/// Current value of [`UV_ANGLE_DELTA_HITS`].
4556#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4557pub(crate) fn uv_angle_delta_hits() -> usize {
4558 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4559}
4560
4561// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4562// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4563// gate's proof this round's arms actually reached a real block, not just
4564// that `partition_w64` read one of those two symbol values.
4565thread_local! {
4566 static SB_RECT_HITS: std::cell::Cell<usize> =
4567 const { std::cell::Cell::new(0) };
4568}
4569
4570// Current value of [`SB_RECT_HITS`].
4571// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4572// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4573// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4574// non-SPLIT edge arm actually decoded (before this round the bit was read and
4575// thrown away, so that arm was unreachable).
4576thread_local! {
4577 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4578}
4579
4580/// Current value of [`EDGE_PART_HITS`].
4581#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4582pub(crate) fn edge_part_hits() -> [usize; 4] {
4583 EDGE_PART_HITS.with(|c| c.get())
4584}
4585
4586/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4587#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4588pub(crate) fn reset_edge_part_hits() {
4589 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4590}
4591
4592fn bump_edge_part(slot: usize) {
4593 hit_do! {
4594 EDGE_PART_HITS.with(|c| {
4595 let mut h = c.get();
4596 h[slot] += 1;
4597 c.set(h);
4598 });
4599 }
4600}
4601
4602#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4603pub(crate) fn sb_rect_hits() -> usize {
4604 SB_RECT_HITS.with(|c| c.get())
4605}
4606
4607// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4608// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4609// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4610// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4611// paths (intra and inter) feed the same counter.
4612//
4613// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4614// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4615// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4616// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4617// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4618// every SB of the last row), so the 32-level slots stay 0 on that content and
4619// only these prove the arm fired.
4620thread_local! {
4621 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4622 const { std::cell::Cell::new([0; 8]) };
4623}
4624
4625/// Current value of [`EDGE32_HITS`].
4626#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4627pub(crate) fn edge32_hits() -> [usize; 8] {
4628 EDGE32_HITS.with(|c| c.get())
4629}
4630
4631/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4632/// reads are `if`-conditions, so the counter has to ride the expression.
4633fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4634 bump_edge32(base + bit.min(1));
4635 bit
4636}
4637
4638fn bump_edge32(slot: usize) {
4639 hit_do! {
4640 EDGE32_HITS.with(|c| {
4641 let mut h = c.get();
4642 h[slot] += 1;
4643 c.set(h)
4644 });
4645 }
4646}
4647
4648// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4649// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4650// strip) fired. Real aomenc picks these at 64 even with
4651// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4652// the counter the gate hard-asserts.
4653thread_local! {
4654 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4655 const { std::cell::Cell::new([0; 4]) };
4656}
4657
4658/// Current value of [`SB_AB_HITS`], summed over the four arms.
4659#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4660pub(crate) fn sb_ab_hits() -> usize {
4661 SB_AB_HITS.with(|c| c.get().iter().sum())
4662}
4663
4664/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4665/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4666/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4667/// proof of all four.
4668#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4669pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4670 SB_AB_HITS.with(std::cell::Cell::get)
4671}
4672
4673// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4674// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4675// strips). Two counters, not one, because a gate that only proved "some 1:4
4676// strip fired" would pass on a stream that never coded the other axis, and
4677// every scan/context table this round added comes in a transposed pair.
4678thread_local! {
4679 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4680 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4681}
4682
4683/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4685pub(crate) fn sb_rect4_horz_hits() -> usize {
4686 SB_RECT4_HORZ_HITS.with(|c| c.get())
4687}
4688
4689/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4690#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4691pub(crate) fn sb_rect4_vert_hits() -> usize {
4692 SB_RECT4_VERT_HITS.with(|c| c.get())
4693}
4694
4695// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4696// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4697// strips), the arms the ReelB mid-film extract stops at.
4698thread_local! {
4699 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4700 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4701 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4702 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4703 /// `PARTITION_VERT_4`.
4704 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4705 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4706 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4707 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4708 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4709 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4710 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4711 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4712}
4713
4714// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4715// a gate that only counted strips would pass on an all-skip stream, which
4716// exercises none of the new scan/context tables.
4717thread_local! {
4718 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4719}
4720
4721// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4722// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4723// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4724// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4725// counts the same for a 16x8/8x16 strip below 16x16.
4726thread_local! {
4727 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4728 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4729 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4730}
4731
4732/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4733#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4734pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4735 (
4736 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4737 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4738 )
4739}
4740
4741/// Current value of `SUB16_SPLIT_HITS`.
4742#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4743pub(crate) fn sub16_split_hits() -> usize {
4744 SUB16_SPLIT_HITS.with(|c| c.get())
4745}
4746
4747// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4748// luma transform is SPLIT and which therefore leave through that fn's early
4749// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4750thread_local! {
4751 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4752}
4753
4754/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4755#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4756pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4757 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4758}
4759
4760/// Current value of `RECT4_COEFF_HITS`.
4761pub(crate) fn rect4_coeff_hits() -> usize {
4762 RECT4_COEFF_HITS.with(|c| c.get())
4763}
4764
4765// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4766// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4767// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4768// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4769// asserts the arms it proves separately so a run whose RD only picked one
4770// cannot pass as proof of the others.
4771thread_local! {
4772 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4773}
4774
4775/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4776/// inter frame).
4777pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4778 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4779}
4780
4781// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4782// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4783// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4784// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4785// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4786// arm separately so a run whose RD only picked one cannot pass as proof of
4787// four.
4788thread_local! {
4789 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4790}
4791
4792/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4793/// inter frame).
4794pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4795 AB16_INTER_HITS.with(std::cell::Cell::get)
4796}
4797
4798// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
4799// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
4800// counts the odd strips that close a 4:2:0 chroma pair
4801// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
4802// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
4803// the PREVIOUS strip's own mv/ref/filters -- libaom
4804// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
4805// through `is_sub8x8_inter` (same file, :54).
4806thread_local! {
4807 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4808 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4809 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4810 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4811}
4812
4813// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
4814// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
4815// pair's single 8x4 (4x8) chroma unit for BOTH strips.
4816thread_local! {
4817 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4818 const { std::cell::Cell::new([0; 3]) };
4819}
4820
4821/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
4822/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
4823pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
4824 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
4825 (v[0], v[1], v[2])
4826}
4827
4828/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
4829/// strips, chroma pairs closed, chroma pairs built from two different
4830/// strips' motion vectors)`.
4831pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
4832 (
4833 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
4834 INTER16_VERT4_HITS.with(std::cell::Cell::get),
4835 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
4836 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
4837 )
4838}
4839
4840/// One 16x4 / 4x16 inter strip's chroma situation, handed to
4841/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
4842/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
4843/// that all mean "an ordinary block, chroma of its own".
4844#[derive(Clone, Copy)]
4845pub(crate) struct InterStripChroma {
4846 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
4847 /// read and reconstruct NO chroma at all.
4848 has_chroma: bool,
4849 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
4850 horz: bool,
4851 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
4852 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
4853 /// i.e. the origin of the 8x4 (4x8) chroma transform.
4854 pair_mi: (usize, usize),
4855 /// The previous (even) strip's single-reference MC parameters, `None`
4856 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
4857 /// and the whole chroma block is predicted from THIS strip's mv.
4858 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
4859}
4860
4861 /// The single-reference MC parameters of the inter block that decoded
4862 /// last -- read by the next 1:4 strip to build its pair's chroma.
4863
4864fn bump_ab16_inter(arm: usize) {
4865 hit_do! {
4866 AB16_INTER_HITS.with(|c| {
4867 let mut v = c.get();
4868 v[arm] += 1;
4869 c.set(v);
4870 });
4871 }
4872}
4873
4874// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
4875// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
4876// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
4877thread_local! {
4878 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4879 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4880 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4881 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4882 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4883 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
4884 /// base mi differs from what the strip's own (odd) mi would have said --
4885 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
4886 /// key frame miss by 1. Zero here means a gate never exercised the fix.
4887 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4888 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
4889 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
4890 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4891}
4892
4893/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
4894/// that reconstructed as flat DC before lane-kf1200 r2).
4895pub fn skip_cfl_hits() -> usize {
4896 SKIP_CFL_HITS.with(|c| c.get())
4897}
4898
4899/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
4900/// from the pair's base mi than the strip's own mi would have given.
4901pub fn rect4_16_uv_pair_filt_hits() -> usize {
4902 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
4903}
4904
4905// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
4906// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
4907// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
4908// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
4909// intra-edge filter type must come from the chroma-reference position).
4910thread_local! {
4911 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4912 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4913}
4914
4915/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
4916pub fn reelc_chroma_counters() -> (usize, usize) {
4917 (
4918 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
4919 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
4920 )
4921}
4922
4923/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
4924/// strips, chroma-reference strips, strips with a coded residual, strips
4925/// whose luma transform is split)`.
4926pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
4927 (
4928 RECT4_16_HORZ_HITS.with(|c| c.get()),
4929 RECT4_16_VERT_HITS.with(|c| c.get()),
4930 RECT4_16_CHROMA_HITS.with(|c| c.get()),
4931 RECT4_16_COEFF_HITS.with(|c| c.get()),
4932 RECT4_16_SPLIT_HITS.with(|c| c.get()),
4933 )
4934}
4935
4936/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
4937pub(crate) fn rect4_32_horz_hits() -> usize {
4938 RECT4_32_HORZ_HITS.with(|c| c.get())
4939}
4940
4941/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
4942pub(crate) fn rect4_32_vert_hits() -> usize {
4943 RECT4_32_VERT_HITS.with(|c| c.get())
4944}
4945
4946/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
4947pub(crate) fn rect4_32_horz_inter_hits() -> usize {
4948 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
4949}
4950
4951/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
4952pub(crate) fn rect4_32_vert_inter_hits() -> usize {
4953 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
4954}
4955
4956/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
4957pub(crate) fn inter_sb_horz_hits() -> usize {
4958 INTER_SB_HORZ_HITS.with(|c| c.get())
4959}
4960
4961/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
4962pub(crate) fn inter_sb_vert_hits() -> usize {
4963 INTER_SB_VERT_HITS.with(|c| c.get())
4964}
4965
4966/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
4967pub(crate) fn inter_sb_horz4_hits() -> usize {
4968 INTER_SB_HORZ4_HITS.with(|c| c.get())
4969}
4970
4971/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
4972pub(crate) fn inter_sb_vert4_hits() -> usize {
4973 INTER_SB_VERT4_HITS.with(|c| c.get())
4974}
4975
4976// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
4977// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
4978// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
4979// just inert-compiled. Zero forever on a passing gate means that gate's
4980// stream never carries `delta_q_present=1` through a rect64 block.
4981thread_local! {
4982 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
4983 const { std::cell::Cell::new(0) };
4984}
4985
4986/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
4987#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4988pub(crate) fn rect64_qidx_drift_hits() -> usize {
4989 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
4990}
4991
4992// lane-partab r1: how many 32x32 quadrants decoded an AB partition
4993// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
4994// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
4995// free-partition gate's proof this round's arms actually fired.
4996thread_local! {
4997 static PARTAB_HITS: std::cell::Cell<usize> =
4998 const { std::cell::Cell::new(0) };
4999}
5000
5001/// Current value of [`PARTAB_HITS`].
5002#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5003pub(crate) fn partab_hits() -> usize {
5004 PARTAB_HITS.with(|c| c.get())
5005}
5006
5007// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
5008// one counter per arm rather than one shared total -- the gate hard-asserts
5009// each of these individually nonzero so a recipe that only ever fires
5010// HORZ_A can't silently stand in for the whole set.
5011thread_local! {
5012 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
5013 const { std::cell::Cell::new(0) };
5014 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
5015 const { std::cell::Cell::new(0) };
5016 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
5017 const { std::cell::Cell::new(0) };
5018 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
5019 const { std::cell::Cell::new(0) };
5020}
5021
5022/// Current value of [`INTRA_HORZ_A_HITS`].
5023#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5024pub(crate) fn intra_horz_a_hits() -> usize {
5025 INTRA_HORZ_A_HITS.with(|c| c.get())
5026}
5027/// Current value of [`INTRA_HORZ_B_HITS`].
5028#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5029pub(crate) fn intra_horz_b_hits() -> usize {
5030 INTRA_HORZ_B_HITS.with(|c| c.get())
5031}
5032/// Current value of [`INTRA_VERT_A_HITS`].
5033#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5034pub(crate) fn intra_vert_a_hits() -> usize {
5035 INTRA_VERT_A_HITS.with(|c| c.get())
5036}
5037/// Current value of [`INTRA_VERT_B_HITS`].
5038#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5039pub(crate) fn intra_vert_b_hits() -> usize {
5040 INTRA_VERT_B_HITS.with(|c| c.get())
5041}
5042
5043// How many [`read_inter_compound_mode`] reads actually happened
5044// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
5045// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
5046// mvstack build), not just that `comp_mode` fired. Still refused right
5047// after (no MV assignment or MC wired), so this only counts attempted
5048// reads.
5049thread_local! {
5050 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
5051 const { std::cell::Cell::new(0) };
5052}
5053
5054/// Current value of [`COMPOUND_MODE_HITS`].
5055#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5056pub(crate) fn compound_mode_hits() -> usize {
5057 COMPOUND_MODE_HITS.with(|c| c.get())
5058}
5059
5060/// How many query blocks folded in at least one temporal MV candidate
5061/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
5062/// temporal-MV gate's own firing counter (lane-av1tmvp).
5063///
5064/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
5065/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
5066/// this file (`decode_inter_block`) still passes `tpl: None` -- this
5067/// counter compiles and the projection math it counts is unit-tested
5068/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
5069/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
5070/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
5071/// against any real stream today. See the module doc on
5072/// `crate::motion_field` and this crate's ledger for the remaining wiring.
5073#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5074pub(crate) fn tmv_hits() -> usize {
5075 crate::mvstack::tmv_hits()
5076}
5077
5078/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
5079/// produced on this thread, the 10-bit inter gate's firing proof.
5080#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5081pub(crate) fn inter_pred_hits() -> usize {
5082 crate::mc::inter_pred_hits()
5083}
5084
5085/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
5086/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
5087/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
5088/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
5089/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
5090/// needs to turn a query block's own resolved `ref_frame` into
5091/// `TplArgs::cur_offset_0` (spec 7.9.3).
5092pub(crate) struct TplFrameArgs<'a> {
5093 pub field: &'a crate::motion_field::TplField,
5094 pub order_hint_bits: u32,
5095 pub order_hint: u32,
5096 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
5097 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
5098 /// frame's own `ref_frame_idx` names for each single reference.
5099 pub ref_order_hints: [u32; 7],
5100}
5101
5102/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
5103/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
5104/// decoded `grid`: every 4x4 unit an inter block covers reads the same
5105/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
5106/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
5107/// exact — every block this crate ever codes is at least 8x8, so no 8x8
5108/// cell straddles two different blocks' values.
5109#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
5110pub(crate) fn build_motion_field(
5111 grid: &MiGrid,
5112 mi_cols: usize,
5113 mi_rows: usize,
5114 order_hint: u32,
5115 order_hint_bits: u32,
5116 ref_order_hints: [u32; 7],
5117 fctx: &FrameCtx,
5118) -> crate::motion_field::MotionField {
5119 let mut field =
5120 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
5121 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
5122 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
5123 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
5124 // referencing one stores only its OTHER side's mv. With
5125 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
5126 // nothing is skipped.
5127 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
5128 // only on the reference frame, so it is 7 table lookups per frame instead
5129 // of two per inter unit.
5130 let other_side: [bool; 8] = std::array::from_fn(|rf| {
5131 let i = rf.wrapping_sub(LAST_FRAME as usize);
5132 order_hint_bits != 0
5133 && i < 7
5134 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
5135 || ref_order_hints[i] == order_hint)
5136 });
5137 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
5138 // capped at 12 bits per component; a longer one is not stored at all.
5139 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
5140 let (cols, rows, cells) = field.cells_mut();
5141 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
5142 // never touch each other (an 8x8 cell lives in one cell row, and mi row
5143 // `row` writes cell row `row / 2`).
5144 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
5145 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
5146 let out = &mut out[(row / 2 - r0) * cols..][..cols];
5147 for col in 0..mi_cols {
5148 let Some(info) = grid.get_frame(row, col) else {
5149 continue;
5150 };
5151 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
5152 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
5153 // so an intra block -- or an inter block whose every slot is on the
5154 // other side / over the limit -- wipes what an earlier block wrote
5155 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
5156 // share a cell).
5157 if !info.is_inter {
5158 out[col / 2] = None;
5159 continue;
5160 }
5161 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
5162 // qualifying one wins -- a compound block stores its second
5163 // reference's mv, never its first (unless the second is on the
5164 // other side or over the limit). Storing slot 0 unconditionally
5165 // put the wrong (mv, ref_frame_offset) pair in every compound
5166 // block's cell, which a later frame's temporal candidate then
5167 // projected with the wrong reference distance.
5168 let mut saved: Option<crate::motion_field::SavedMv> = None;
5169 for (rf, mv) in [
5170 (info.ref_frame, Some(mv32(info.mv))),
5171 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
5172 ] {
5173 let (Some(mv), true) = (mv, rf > 0) else {
5174 continue;
5175 };
5176 if other_side[rf as usize] {
5177 continue;
5178 }
5179 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
5180 continue;
5181 }
5182 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
5183 }
5184 out[col / 2] = saved;
5185 }
5186 }
5187 };
5188 // lane-mf: the whole-frame pass split over the filter pool in cell-row
5189 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
5190 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
5191 let bands = crate::par::bands(rows, crate::par::filter_threads());
5192 if bands.len() <= 1 {
5193 fill(0, rows, cells);
5194 } else {
5195 let shared = crate::par::Shared::new(cells);
5196 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
5197 // SAFETY: cell rows `r0..r1` are this band's alone.
5198 let cells = unsafe { shared.get() };
5199 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
5200 });
5201 }
5202 if crate::envflags::env_flag!("EC_TRACE_TPL") {
5203 eprintln!("EC_TPL_SAVED oh={order_hint}");
5204 for (r, row) in field.occupancy().iter().enumerate() {
5205 eprintln!("EC_TPL_SAVED r{r} {row}");
5206 }
5207 }
5208 field
5209}
5210
5211/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5212/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5213#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5214pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5215 let c = match ref_frame {
5216 LAST2_FRAME => &LAST2_HITS,
5217 LAST3_FRAME => &LAST3_HITS,
5218 GOLDEN_FRAME => &GOLDEN_HITS,
5219 BWDREF_FRAME => &BWDREF_HITS,
5220 ALTREF2_FRAME => &ALTREF2_HITS,
5221 ALTREF_FRAME => &ALTREF_HITS,
5222 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5223 };
5224 c.with(|v| v.get())
5225}
5226
5227 /// The sequence header's `enable_intra_edge_filter`, set once per
5228 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5229 /// own read of it, kept off the call stack (see that function's own doc
5230 /// comment for why) rather than threaded through every `read_plane`/
5231 /// `decode_block`/`decode_leaf8` call between here and there.
5232
5233/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5234///
5235/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5236/// never did -- so an inter frame's intra blocks read whatever value the last
5237/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5238/// harmless (its own key frame sets it first), but a caller that decodes an
5239/// inter frame directly, or a test harness running several streams on one
5240/// thread, inherits a foreign sequence's bit: decode stops being a pure
5241/// function of the bitstream. `decode_stream` now calls this once per stream
5242/// from the sequence header, which covers every frame including inter ones.
5243pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5244 fctx.enable_edge_filter.with(|f| f.set(value));
5245}
5246
5247/// Current value of [`ANGLE_DELTA_HITS`].
5248#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5249pub(crate) fn angle_delta_hits() -> usize {
5250 ANGLE_DELTA_HITS.with(|c| c.get())
5251}
5252
5253/// Current value of [`TX_CLASS1_HITS`].
5254#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5255pub(crate) fn tx_class1_hits() -> usize {
5256 TX_CLASS1_HITS.with(|c| c.get())
5257}
5258
5259// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5260// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5261// bottom) this thread's decode actually reconstructed -- the same
5262// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5263// genuinely exercised the sub-8x8 leaf path rather than every attempt
5264// coincidentally landing on `PARTITION_NONE`.
5265thread_local! {
5266 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5267 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5268 /// sub-blocks (lane-intersub8).
5269 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5270 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5271 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5272 /// `[1] = VERT` (two BLOCK_4X8).
5273 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5274 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5275 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5276 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5277 /// MIXED groups whose chroma reference is INTER while its sibling is
5278 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5279 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5280 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5281 /// so only this cell separates the split arm from the HORZ/VERT one).
5282 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5283}
5284
5285/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5286/// mixed groups, split 4x4 leaves)`.
5287pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5288 SUB8_INTRA_RECT_HITS.with(|c| {
5289 let h = c.get();
5290 (h[0], h[1], h[2], h[3], h[4])
5291 })
5292}
5293
5294/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5295pub fn sub8_inter_rect_hits() -> (usize, usize) {
5296 SUB8_INTER_RECT_HITS.with(|c| {
5297 let h = c.get();
5298 (h[0], h[1])
5299 })
5300}
5301
5302// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5303// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5304// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5305// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5306// (b) was 0 for every stream before this round -- the leaf path never touched
5307// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5308// filtered where libaom skips it. A gate asserts both are non-zero.
5309thread_local! {
5310 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5311 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5312 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5313 // crosses the cropped frame edge -- the only units for which "clamp at
5314 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5315 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5316 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5317 // whose width or height is not a multiple of 8 is the only shape that
5318 // produces one; the straddling-band gate arms assert it grew.
5319 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5320 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5321 // (see `Neighbours::skip_written`).
5322 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5323 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5324 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5325 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5326 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5327 // 8-tall strip pair where only one half is skip must still be FILTERED.
5328 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5329 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5330}
5331
5332/// Current value of `RECT_SKIP_BAND_HITS`.
5333pub fn rect_skip_band_hits() -> usize {
5334 RECT_SKIP_BAND_HITS.with(|c| c.get())
5335}
5336
5337/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5338pub fn cdef_mixed_skip_units() -> usize {
5339 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5340}
5341
5342/// Current value of `CDEF_SKIPPED_UNITS`.
5343#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5344pub(crate) fn cdef_skipped_units() -> usize {
5345 CDEF_SKIPPED_UNITS.with(|c| c.get())
5346}
5347
5348/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5349/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5350pub fn cdef_unwritten_skip_units() -> usize {
5351 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5352}
5353
5354/// Current value of `INTER8_SKIP_BAND_HITS`.
5355#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5356pub(crate) fn inter8_skip_band_hits() -> usize {
5357 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5358}
5359
5360/// Current value of `CDEF_STRADDLE_UNITS`.
5361#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5362pub(crate) fn cdef_straddle_units() -> usize {
5363 CDEF_STRADDLE_UNITS.with(|c| c.get())
5364}
5365
5366/// Current value of [`SUB8_SPLIT_HITS`].
5367#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5368pub(crate) fn sub8_split_hits() -> usize {
5369 SUB8_SPLIT_HITS.with(|c| c.get())
5370}
5371
5372/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5373pub fn sub8_inter_split_hits() -> usize {
5374 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5375}
5376
5377// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5378// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5379// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5380// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5381// first sub-block's type is never the one). Reading it off sub-block 0
5382// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5383// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5384// see this rule through this counter.
5385thread_local! {
5386 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5387}
5388
5389/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5390pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5391 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5392}
5393
5394fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5395 if coeffs && first_sub != chroma_ref {
5396 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5397 }
5398}
5399
5400// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5401// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5402// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5403// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5404// asserts on these two rather than a plain leaf count.
5405thread_local! {
5406 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5407 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5408 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5409 /// two 4x4 transform units, predicted one after the other. A separate
5410 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5411 /// the gate can prove THIS path fired.
5412 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5413 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5414 /// own width (above-right) or height (below-left) -- the samples
5415 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5416 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5417 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5418 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5419 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5420 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5421}
5422
5423/// Current value of [`RECT8_SPLIT_TX_HITS`].
5424#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5425pub(crate) fn rect8_split_tx_hits() -> usize {
5426 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5427}
5428
5429/// Current value of [`RECT_STRIP_PRED_HITS`].
5430#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5431pub(crate) fn rect_strip_pred_hits() -> usize {
5432 RECT_STRIP_PRED_HITS.with(|c| c.get())
5433}
5434
5435/// Current value of [`RECT_STRIP_REACH_HITS`].
5436#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5437pub(crate) fn rect_strip_reach_hits() -> usize {
5438 RECT_STRIP_REACH_HITS.with(|c| c.get())
5439}
5440
5441/// Current value of [`TX4X8_CODED_HITS`].
5442#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5443pub(crate) fn tx4x8_coded_hits() -> usize {
5444 TX4X8_CODED_HITS.with(|c| c.get())
5445}
5446
5447/// Current value of [`TX8X4_CODED_HITS`].
5448#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5449pub(crate) fn tx8x4_coded_hits() -> usize {
5450 TX8X4_CODED_HITS.with(|c| c.get())
5451}
5452
5453// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5454// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5455// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5456// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5457// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5458// (`eob_pt_{16,64,128,256}_chroma_class1`).
5459thread_local! {
5460 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5461 const { std::cell::Cell::new(0) };
5462}
5463
5464/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5465#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5466pub(crate) fn chroma_eob_class1_hits() -> usize {
5467 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5468}
5469
5470/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5471/// `tx_type` put this block's `eob_pt` on the class-1 row.
5472fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5473 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5474 hit!(CHROMA_EOB_CLASS1_HITS);
5475 }
5476}
5477
5478const SUB_MI: u32 = 4;
5479const MI: usize = 4;
5480const SB: usize = 64;
5481/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5482/// (tile start, superblock-row start).
5483///
5484/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5485/// `av1_get_partition_plane_context` reads its own zero-initialised
5486/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5487/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5488/// (64), which reads identically at every level up to 64x64 but sets the bit
5489/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5490/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5491/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5492const NO_NEIGHBOUR_SIDE: usize = 128;
5493const BLOCK: usize = 32;
5494const SUB: usize = 16;
5495const TX32: usize = 32;
5496const TX16: usize = 16;
5497const TX8: usize = 8;
5498const TX4: usize = 4;
5499const DC_PRED: usize = 0;
5500/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5501/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5502/// constant.
5503const V_PRED: usize = 1;
5504const H_PRED: usize = 2;
5505/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
5506/// `Fimode_To_Intradir`, libaom `blockd.h`).
5507const D157_PRED: usize = 6;
5508/// The last directional mode, `D67_PRED`.
5509const D67_PRED: usize = 8;
5510/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
5511/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
5512/// codes anything else, so this decoder never reads anything else either.
5513const ANGLE_DELTA_ZERO: usize = 3;
5514const NUM_BASE_LEVELS: i32 = 2;
5515const COEFF_BASE_RANGE: i32 = 12;
5516const BR_STEP: i32 = 3;
5517const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
5518
5519/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
5520/// whose probability mass a superblock or block half outside the frame
5521/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
5522/// duplicated here (that module is another lane's territory this round) and
5523/// kept in step with it by the byte-exact round-trip tests below rather than
5524/// by sharing code.
5525const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
5526const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
5527
5528fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
5529 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5530 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
5531 }
5532}
5533
5534fn element_prob(cdf: &[u16], element: usize) -> u16 {
5535 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5536}
5537
5538/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5539/// with: the mass of `elements` becomes the probability of the one partition
5540/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5541/// (the encoder's non-adapting counterpart to this read).
5542fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5543 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5544 [32768 - split, 32768, 0]
5545}
5546
5547fn unsupported(what: impl Into<String>) -> Error {
5548 Error::unsupported("AV1 tile", what.into())
5549}
5550
5551/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5552/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5553/// same rule.
5554pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5555 match base_q_idx {
5556 0..=20 => 0,
5557 21..=60 => 1,
5558 61..=120 => 2,
5559 _ => 3,
5560 }
5561}
5562
5563/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5564/// [`crate::tile`]'s writer generates its scan tables with.
5565fn default_scan(side: usize) -> &'static [u16] {
5566 // One table per transform side (4/8/16/32), built once: this used to be a
5567 // fresh heap allocation plus the whole anti-diagonal walk on every
5568 // transform block read.
5569 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5570 [
5571 default_scan_gen(4),
5572 default_scan_gen(8),
5573 default_scan_gen(16),
5574 default_scan_gen(32),
5575 ]
5576 });
5577 assert!(
5578 matches!(side, 4 | 8 | 16 | 32),
5579 "no default scan for a {side}-point transform"
5580 );
5581 &SCANS[side.trailing_zeros() as usize - 2]
5582}
5583
5584fn default_scan_gen(side: usize) -> Vec<u16> {
5585 let mut scan = Vec::with_capacity(side * side);
5586 for d in 0..(2 * side - 1) {
5587 let lo = d.saturating_sub(side - 1);
5588 let hi = d.min(side - 1);
5589 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5590 if d % 2 == 0 {
5591 scan.extend(diagonal.rev());
5592 } else {
5593 scan.extend(diagonal);
5594 }
5595 }
5596 scan
5597}
5598
5599/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5600/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5601/// in, instead of the default zigzag. libaom's own tables are keyed by a
5602/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5603/// physically column-major level buffer, but they decompose to the exact
5604/// same (row, col) walk as a flat row-major traversal of *our* row-major
5605/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5606/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5607/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5608/// transposed (column 0 down every row, then column 1, ...).
5609pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5610 class_scan_table_wh(side, side, class)
5611}
5612
5613/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5614/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5615/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5616/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5617/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5618/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5619fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5620 match class {
5621 TxClass::Vert => (0..(w * h) as u16).collect(),
5622 TxClass::Horiz => (0..w)
5623 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5624 .collect(),
5625 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5626 }
5627}
5628
5629fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5630 match scan_idx {
5631 0 => 0,
5632 i if i <= area / 8 => 1,
5633 i if i <= area / 4 => 2,
5634 _ => 3,
5635 }
5636}
5637
5638/// One cell of [`read_coeffs`]'s level buffer.
5639///
5640/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
5641/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
5642/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
5643/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
5644/// zero cells instead of needing the `row >= side || col >= side` edge test
5645/// this used to run five times per coefficient. Nothing writes a padding
5646/// cell, so the values are the same zeros the test returned.
5647#[inline]
5648fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5649 grid[row * stride + col] as i32
5650}
5651
5652/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5653/// `txb_common.h`): everything but the two lone-axis-identity types this
5654/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5655#[derive(Clone, Copy, PartialEq, Eq)]
5656pub(crate) enum TxClass {
5657 TwoD,
5658 Horiz,
5659 Vert,
5660}
5661
5662impl TxClass {
5663 pub(crate) fn of(tx_type: TxType) -> Self {
5664 match tx_type {
5665 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5666 // key on axis alone -- FLIPADST is still ADST for this purpose.
5667 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5668 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5669 _ => Self::TwoD,
5670 }
5671 }
5672}
5673
5674/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5675/// table (indexed by the position along the transform's *coded* axis --
5676/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5677/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5678/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5679pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
5680 match i {
5681 0 => 26,
5682 1 => 31,
5683 _ => 36,
5684 }
5685}
5686
5687fn base_ctx(
5688 grid: &[u8],
5689 stride: usize,
5690 row: usize,
5691 col: usize,
5692 class: TxClass,
5693 rect_shape: Option<(usize, usize)>,
5694) -> usize {
5695 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5696 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5697 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5698 // position through the full 1D neighbour sum and offset table. Skipping
5699 // that for every class desynced the last (DC) coefficient of a
5700 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5701 // 0, which then read one extra `BR` symbol at the max and forced a
5702 // spurious third Golomb call).
5703 if class == TxClass::TwoD && row == 0 && col == 0 {
5704 return 0;
5705 }
5706 let offsets: [(usize, usize); 5] = match class {
5707 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5708 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5709 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5710 };
5711 let mag: i32 = offsets
5712 .iter()
5713 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
5714 .sum();
5715 let ctx = ((mag + 1) >> 1).min(4) as usize;
5716 match class {
5717 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5718 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5719 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5720 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5721 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5722 // strip, which own a genuinely different table from the square one
5723 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5724 // square table vs the real ctx 13 the rect table gives).
5725 TxClass::TwoD => {
5726 // lane-rectsplit r4: apply libaom's GENERATING RULE
5727 // (`txb_common.h:199-209`) directly instead of indexing the
5728 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5729 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5730 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5731 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5732 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5733 // transcriptions are `[col][row]` and this read had them as
5734 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5735 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5736 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5737 // pins the rule against the tables over their whole 5x5 domain.
5738 if let Some((w, h)) = rect_shape {
5739 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5740 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
5741 }
5742 if w < h && row < 2 {
5743 return ctx + 11;
5744 }
5745 if w > h && col < 2 {
5746 return ctx + 16;
5747 }
5748 }
5749 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5750 }
5751 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5752 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5753 }
5754}
5755
5756/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
5757/// offsets into the padded level frame (lane-coefread): the tap pattern is a
5758/// function of the tx class alone, which is fixed for a whole transform unit,
5759/// so resolving it once per unit takes the class match and the `(dr, dc)`
5760/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
5761/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
5762/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
5763/// original `(dr, dc)` form.
5764fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
5765 match class {
5766 TxClass::TwoD => (
5767 [stride, 1, stride + 1, 2 * stride, 2],
5768 [stride, 1, stride + 1],
5769 ),
5770 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
5771 TxClass::Vert => (
5772 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
5773 [stride, 1, 2 * stride],
5774 ),
5775 }
5776}
5777
5778/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
5779/// neighbours) + 1) >> 1`, clamped to 4.
5780#[inline(always)]
5781fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
5782 let mut mag = 0u32;
5783 for &t in taps {
5784 mag += u32::from(grid[idx + t]).min(3);
5785 }
5786 (((mag + 1) >> 1) as usize).min(4)
5787}
5788
5789/// [`br_ctx`]'s neighbour sum, off flat taps.
5790#[inline(always)]
5791fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
5792 let mut mag = 0u32;
5793 for &t in taps {
5794 mag += u32::from(grid[idx + t]);
5795 }
5796 (((mag + 1) >> 1) as usize).min(6)
5797}
5798
5799/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
5800/// origin-offset tail the two coefficient readers state inline; kept as the
5801/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
5802/// flat one against.
5803#[cfg(test)]
5804fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
5805 let extra = match class {
5806 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
5807 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
5808 TxClass::Vert => neighbour(grid, stride, row + 2, col),
5809 };
5810 let mag = neighbour(grid, stride, row + 1, col)
5811 + neighbour(grid, stride, row, col + 1)
5812 + extra;
5813 let mag = (((mag + 1) >> 1).min(6)) as usize;
5814 if row == 0 && col == 0 {
5815 return mag;
5816 }
5817 let near_origin = match class {
5818 TxClass::TwoD => row < 2 && col < 2,
5819 TxClass::Horiz => col == 0,
5820 TxClass::Vert => row == 0,
5821 };
5822 if near_origin { mag + 7 } else { mag + 14 }
5823}
5824
5825/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
5826/// transposed from libaom's column-major buffer into this decoder's row-major
5827/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
5828/// against the real table). Not the square zigzag formula generalized to
5829/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
5830const SCAN_32X16: [u16; 512] = [
5831 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
5832 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
5833 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
5834 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
5835 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
5836 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
5837 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
5838 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
5839 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
5840 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
5841 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
5842 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
5843 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
5844 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
5845 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
5846 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
5847 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
5848 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
5849 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
5850 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
5851 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
5852 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
5853 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
5854 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
5855 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
5856 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
5857 509, 478, 447, 510, 479, 511,
5858];
5859
5860/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
5861/// [`SCAN_32X16`]'s doc comment).
5862const SCAN_16X32: [u16; 512] = [
5863 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,
5864 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
5865 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
5866 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
5867 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
5868 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
5869 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
5870 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
5871 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
5872 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
5873 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
5874 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
5875 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
5876 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
5877 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
5878 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
5879 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
5880 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
5881 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
5882 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
5883 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
5884 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
5885 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
5886 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
5887 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
5888 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
5889];
5890
5891/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
5892/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
5893/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
5894/// the same source).
5895const SCAN_4X8: [u16; 32] = [
5896 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,
5897 23, 26, 29, 27, 30, 31,
5898];
5899
5900/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
5901const SCAN_8X4: [u16; 32] = [
5902 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,
5903 29, 22, 15, 30, 23, 31,
5904];
5905
5906/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
5907/// [`SCAN_32X16`]'s doc comment).
5908const SCAN_16X8: [u16; 128] = [
5909 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,
5910 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
5911 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
5912 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
5913 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
5914 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
5915];
5916
5917/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
5918/// [`SCAN_32X16`]'s doc comment).
5919const SCAN_8X16: [u16; 128] = [
5920 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,
5921 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5922 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5923 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5924 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
5925 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
5926];
5927
5928/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
5929/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
5930/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
5931/// scans column-major (`p = col * height + row`), so a naive copy of
5932/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
5933/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
5934/// are byte-identical to this decoder's [`SCAN_8X16`].
5935const SCAN_32X8: [u16; 256] = [
5936 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
5937 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
5938 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
5939 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
5940 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
5941 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
5942 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
5943 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
5944 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
5945 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
5946 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
5947 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
5948 222, 191, 254, 223, 255,
5949];
5950/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
5951/// 16x64 `PARTITION_VERT_4` strip).
5952const SCAN_8X32: [u16; 256] = [
5953 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,
5954 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5955 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5956 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5957 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
5958 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
5959 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
5960 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
5961 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
5962 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
5963 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
5964 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
5965 239, 246, 253, 247, 254, 255,
5966];
5967/// `Default_Scan_16x4`, this decoder's own row-major transcription of
5968/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
5969/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
5970/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
5971/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
5972/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
5973/// were emitted -- a naive copy installs the transpose (class
5974/// reference-layout-not-spec).
5975const SCAN_16X4: [u16; 64] = [
5976 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,
5977 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
5978 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
5979];
5980/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
5981/// 8x32 `PARTITION_VERT_4` strip).
5982const SCAN_4X16: [u16; 64] = [
5983 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,
5984 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
5985 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
5986];
5987
5988/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
5989/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
5990/// padding already holds.
5991#[inline]
5992fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5993 grid[row * stride + col] as i32
5994}
5995
5996/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
5997/// the rect generalization is libaom's own comment in
5998/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
5999/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
6000/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
6001/// [`decode_block_rect`] codes (see that function's own doc comment).
6002fn base_ctx_rect(
6003 grid: &[u8],
6004 stride: usize,
6005 w: usize,
6006 h: usize,
6007 row: usize,
6008 col: usize,
6009 class: TxClass,
6010) -> usize {
6011 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
6012 // the 2D class short-circuits the DC position.
6013 if class == TxClass::TwoD && row == 0 && col == 0 {
6014 return 0;
6015 }
6016 let offsets: [(usize, usize); 5] = match class {
6017 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
6018 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
6019 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
6020 };
6021 let mag: i32 = offsets
6022 .iter()
6023 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
6024 .sum();
6025 let ctx = ((mag + 1) >> 1).min(4) as usize;
6026 match class {
6027 TxClass::TwoD => {
6028 if w < h && row < 2 {
6029 return ctx + 11;
6030 }
6031 if w > h && col < 2 {
6032 return ctx + 16;
6033 }
6034 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6035 }
6036 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
6037 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
6038 // position along one axis only).
6039 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6040 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6041 }
6042}
6043
6044/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
6045/// neighbour-offset math itself is shape-independent, only the boundary
6046/// clamp needs the real bound in each axis.
6047/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
6048/// its body was character-for-character [`br_ctx`]'s, which
6049/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
6050#[cfg(test)]
6051fn br_ctx_rect(
6052 grid: &[u8],
6053 stride: usize,
6054 row: usize,
6055 col: usize,
6056 class: TxClass,
6057) -> usize {
6058 let extra = match class {
6059 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
6060 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
6061 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
6062 };
6063 let mag = neighbour_rect(grid, stride, row + 1, col)
6064 + neighbour_rect(grid, stride, row, col + 1)
6065 + extra;
6066 let mag = (((mag + 1) >> 1).min(6)) as usize;
6067 if row == 0 && col == 0 {
6068 return mag;
6069 }
6070 let near_origin = match class {
6071 TxClass::TwoD => row < 2 && col < 2,
6072 TxClass::Horiz => col == 0,
6073 TxClass::Vert => row == 0,
6074 };
6075 if near_origin { mag + 7 } else { mag + 14 }
6076}
6077
6078fn dc_vote(dc: Option<bool>) -> i32 {
6079 match dc {
6080 None => 0,
6081 Some(true) => -1,
6082 Some(false) => 1,
6083 }
6084}
6085
6086fn dc_sign_ctx(vote: i32) -> usize {
6087 match vote.signum() {
6088 0 => 0,
6089 -1 => 1,
6090 _ => 2,
6091 }
6092}
6093
6094/// The `tx_type` a CDF symbol names, given the width of the row it was read
6095/// from.
6096///
6097/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
6098/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
6099/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
6100/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
6101/// members are a prefix of the five.
6102///
6103/// One function rather than a `match` at each reader, so
6104/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
6105/// tests the mapping the readers actually use.
6106pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
6107 match cdf_len {
6108 17 => TxType::from_symbol_all16(t),
6109 13 => TxType::from_symbol_set2_12(t),
6110 8 => TxType::from_symbol_set1(t),
6111 _ => TxType::from_symbol(t),
6112 }
6113}
6114
6115/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
6116/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
6117/// (class `table-and-reader-move-together` -- the writer picks its symbol
6118/// through the reader's own map, so the two cannot drift).
6119pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
6120 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
6121}
6122
6123/// The remainder of a level the base and base-range syntax could not reach
6124/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
6125/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
6126pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
6127 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
6128 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
6129 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
6130 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
6131 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
6132 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
6133 // stream_can_carry` enumerates that whole value domain.
6134 //
6135 // So this refusal never names a reader gap: it is always the SYMPTOM of an
6136 // earlier desync (class `refusal-hides-a-defect`), and every historical
6137 // instance was closed by fixing that desync -- lane-dgolomb's
6138 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
6139 // Raising the cap only trades a clean refusal for silent corruption:
6140 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
6141 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
6142 // from a refusal into a frame-0 LUMA MISMATCH.
6143 let mut length = 1u32;
6144 while dec.literal(1) == 0 {
6145 length += 1;
6146 if length > 20 {
6147 return Err(unsupported("a Golomb tail longer than this decoder reads"));
6148 }
6149 }
6150 let mut x = 1u32;
6151 for _ in 1..length {
6152 x = (x << 1) | dec.literal(1);
6153 }
6154 Ok(x - 1)
6155}
6156
6157/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
6158/// [`crate::tile`]'s `write_eob`.
6159fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
6160 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6161 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6162
6163 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6164 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
6165 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
6166 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
6167 // `eob_multi_ctx`). Missing that split desynced the very first
6168 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
6169 // against a real aomdec trace).
6170 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6171 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6172 (_, Some(class1)) => class1,
6173 };
6174 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6175 let (range, value) = dec.debug_state();
6176 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
6177 }
6178 let group = dec.symbol(eob_pt) + 1;
6179 if trace {
6180 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
6181 }
6182 let bits = OFFSET_BITS[group];
6183 let mut offset = 0u32;
6184 if bits > 0 {
6185 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
6186 if trace {
6187 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
6188 }
6189 offset = top << (bits - 1);
6190 if bits > 1 {
6191 offset |= dec.literal(bits - 1);
6192 }
6193 }
6194 GROUP_START[group] + offset as usize
6195}
6196
6197/// One transform block's levels, the inverse of [`crate::tile`]'s
6198/// `write_coeffs`, returned as a `side * side` grid in raster order, along
6199/// with the transform type that grid was coded under (`DCT_DCT` when the
6200/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
6201/// 64-point transforms, which never code anything else).
6202///
6203/// # Errors
6204/// Returns an error if the `tx_type` symbol decodes to a value outside its
6205/// CDF's own set (a corrupt or unsupported bitstream) — every value the
6206/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
6207/// produce dispatches to a real inverse transform.
6208/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
6209/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
6210/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
6211/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
6212/// the plane's own predicted mode instead. Every entry this table can
6213/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
6214/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
6215/// table ever names), so unlike the CDF-coded luma path there is no
6216/// ext-tx-set membership check to fall back from here.
6217pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
6218 use crate::intra::{
6219 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
6220 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
6221 };
6222 match mode {
6223 DC_PRED | D45_PRED => TxType::DctDct,
6224 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6225 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6226 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6227 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6228 }
6229}
6230
6231/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6232/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6233/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6234fn is_smooth_mode(mode: usize) -> bool {
6235 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6236}
6237
6238/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6239/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6240/// nine of them inside the base/sign loops pinned nine sets of values in the
6241/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6242/// traffic). Out of line, the loop keeps its values in registers and the
6243/// trace output is character-for-character what it was.
6244#[cold]
6245#[inline(never)]
6246fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6247 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6248}
6249
6250#[cold]
6251#[inline(never)]
6252fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6253 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6254}
6255
6256#[cold]
6257#[inline(never)]
6258fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6259 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6260}
6261
6262#[cold]
6263#[inline(never)]
6264fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6265 let (rng, _) = dec.debug_state();
6266 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6267}
6268
6269#[cold]
6270#[inline(never)]
6271fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6272 let (rng, _) = dec.debug_state();
6273 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6274}
6275
6276#[cold]
6277#[inline(never)]
6278fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6279 let (rng, _) = dec.debug_state();
6280 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6281}
6282
6283#[cold]
6284#[inline(never)]
6285fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6286 let (rng, _) = dec.debug_state();
6287 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6288}
6289
6290#[cold]
6291#[inline(never)]
6292fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6293 let (rng, _) = dec.debug_state();
6294 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6295}
6296
6297fn read_coeffs(
6298 dec: &mut SymbolDecoder,
6299 coding: &mut TxbTables,
6300 scan: &[u16],
6301 skip_ctx: usize,
6302 sign_ctx: usize,
6303 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6304 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6305 // nothing at all; `DctDct` for every luma call and every chroma call at
6306 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6307 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6308 default_tx_type: TxType,
6309 // `Some((w, h))` with `w != h` when this read is a superblock-level
6310 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6311 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6312 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6313 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6314 // caller's block genuinely is `side` x `side`.
6315 rect_shape: Option<(usize, usize)>,
6316) -> Result<(Grid, TxType)> {
6317 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6318 let side = coding.side;
6319 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6320 let (range, value) = dec.debug_state();
6321 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6322 }
6323 let dbg_txbskip = if coeff_trace_on() {
6324 coding.txb_skip[skip_ctx]
6325 } else {
6326 [0; 3]
6327 };
6328 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6329 if coeff_trace_on() {
6330 let (rng, _) = dec.debug_state();
6331 eprintln!(
6332 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6333 coding.side,
6334 all_zero as i32
6335 );
6336 }
6337 if crate::envflags::env_flag!("EC_AV1_TELL") {
6338 eprintln!(
6339 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6340 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6341 );
6342 }
6343 if trace {
6344 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6345 }
6346 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6347 let (range, value) = dec.debug_state();
6348 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6349 }
6350 if all_zero {
6351 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6352 // shared zero grid instead of allocating and zeroing its own.
6353 return Ok((Grid::Zero(side * side), TxType::DctDct));
6354 }
6355 let mut grid = vec![0i32; side * side];
6356 let mut tx_type = default_tx_type;
6357 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6358 // The CDF row's own width names its set (lane-cdffwd2: extended
6359 // past the original two-way intra split once wider `reduced_tx_set
6360 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6361 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6362 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6363 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6364 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6365 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6366 let len = tx_type_cdf.len();
6367 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6368 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6369 }
6370 let t = dec.symbol(tx_type_cdf);
6371 crate::census::tx_type(len, t);
6372 if coeff_trace_on() {
6373 let (rng, _) = dec.debug_state();
6374 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6375 }
6376 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6377 let (range, value) = dec.debug_state();
6378 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6379 }
6380 if trace {
6381 eprintln!("TRACE tx_type value={t} len={len}");
6382 }
6383 tx_type = tx_type_from_symbol(len, t)
6384 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6385 }
6386
6387 let class = TxClass::of(tx_type);
6388 if class != TxClass::TwoD {
6389 hit!(TX_CLASS1_HITS);
6390 hit!(RECT_CLASS1_HITS);
6391 }
6392 let eob = read_eob(dec, coding, class);
6393 if trace {
6394 eprintln!("TRACE eob value={eob}");
6395 }
6396 let ec_trace_coeff = coeff_trace_on();
6397 if ec_trace_coeff {
6398 let (rng, _) = dec.debug_state();
6399 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6400 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6401 }
6402 let class_scan;
6403 let scan: &[u16] = if class == TxClass::TwoD {
6404 scan
6405 } else {
6406 class_scan = class_scan_table(side, class);
6407 &class_scan
6408 };
6409 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6410 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6411 // shift and a mask say the same thing, and the level buffer fits a fixed
6412 // 32x32 frame of stack instead of a heap allocation per transform block.
6413 debug_assert!(side.is_power_of_two() && side <= 32);
6414 let sh = side.trailing_zeros();
6415 let col_mask = side - 1;
6416 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6417 // `stride = side + 4` columns and four spare rows, so the widest read
6418 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6419 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6420 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6421 let stride = side + 4;
6422 let mut levels_buf = [0u8; 36 * 36];
6423 let levels = &mut levels_buf[..stride * stride];
6424 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6425 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6426 // padded frame just to skip the zeros. The base pass already knows both,
6427 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6428 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6429 // pass walks that list in reverse (the base pass runs in reverse scan
6430 // order, so reversing it is forward scan order: the same coefficients, in
6431 // the same order, with the same `c` the trace prints).
6432 let mut nz_buf = [0u16; 1024];
6433 let mut nz_n = 0usize;
6434 let (base_taps, br_taps) = flat_taps(stride, class);
6435 for scan_idx in (0..eob).rev() {
6436 let pos = scan[scan_idx] as usize;
6437 let (row, col) = (pos >> sh, pos & col_mask);
6438 let idx = row * stride + col;
6439 let level = if scan_idx == eob - 1 {
6440 let ctx = eob_coeff_ctx(scan_idx, side * side);
6441 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6442 if trace {
6443 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6444 }
6445 v
6446 } else {
6447 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6448 if row == 0 && col == 0 {
6449 0
6450 } else {
6451 base_mag(levels, idx, &base_taps)
6452 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6453 }
6454 } else {
6455 base_ctx(levels, stride, row, col, class, rect_shape)
6456 };
6457 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6458 if ec_trace_coeff {
6459 // `pos` in libaom's column-major `coeff_idx` convention, so
6460 // the ladder lines up with instrumented `aomdec`.
6461 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6462 }
6463 if trace {
6464 trace_base(scan_idx, pos, row, col, ctx, v);
6465 }
6466 v
6467 };
6468 let level = if level > NUM_BASE_LEVELS {
6469 let ctx = {
6470 let mag = br_mag(levels, idx, &br_taps);
6471 if row == 0 && col == 0 {
6472 mag
6473 } else {
6474 let near_origin = match class {
6475 TxClass::TwoD => row < 2 && col < 2,
6476 TxClass::Horiz => col == 0,
6477 TxClass::Vert => row == 0,
6478 };
6479 if near_origin { mag + 7 } else { mag + 14 }
6480 }
6481 };
6482 let mut level = level;
6483 let mut sent = 0;
6484 loop {
6485 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6486 if ec_trace_coeff {
6487 // lane-leaf8tx r3: the `br` rung was missing from THIS
6488 // path's trace, so the cross-decoder range ladder was
6489 // blind to every base-range symbol and mis-reported the
6490 // first divergence (class [[gate-blind-to-feature]]).
6491 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6492 }
6493 if trace {
6494 trace_br(scan_idx, pos, row, col, ctx, k);
6495 }
6496 level += k;
6497 sent += BR_STEP;
6498 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6499 break;
6500 }
6501 }
6502 level
6503 } else {
6504 level
6505 };
6506 if ec_trace_coeff && scan_idx == eob - 1 {
6507 coeff_step_base_eob_level(dec, level);
6508 }
6509 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
6510 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
6511 // added in the sign pass below, straight into `grid`), so the context
6512 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
6513 // byte gather (lane-coefbuf).
6514 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6515 levels[idx] = level as u8;
6516 if level != 0 {
6517 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6518 nz_n += 1;
6519 }
6520 }
6521 if ec_trace_coeff {
6522 let (rng, _) = dec.debug_state();
6523 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6524 }
6525
6526 for &packed in nz_buf[..nz_n].iter().rev() {
6527 let c = (packed >> 4) as usize;
6528 let pos = scan[c] as usize;
6529 let level = (packed & 15) as i32;
6530 let negative = if pos == 0 {
6531 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
6532 if trace {
6533 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
6534 }
6535 v
6536 } else {
6537 dec.literal(1) == 1
6538 };
6539 if ec_trace_coeff {
6540 coeff_step_sign(dec, c, negative);
6541 }
6542 let level = if level > MAX_BR_LEVEL {
6543 let g = read_golomb(dec)?;
6544 if trace {
6545 eprintln!("TRACE golomb pos={pos} value={g}");
6546 }
6547 level + g as i32
6548 } else {
6549 level
6550 };
6551 if ec_trace_coeff {
6552 coeff_step_post_golomb(dec, c, level);
6553 }
6554 grid[pos] = if negative { -level } else { level };
6555 }
6556 Ok((Grid::Own(grid), tx_type))
6557}
6558
6559/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
6560/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
6561/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
6562/// can ever produce, since every `tx_type` this decoder's rect sets can read
6563/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
6564/// rather than guess-decode if a non-2D class ever shows up here, since
6565/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
6566/// form for those.
6567
6568fn read_coeffs_rect(
6569 dec: &mut SymbolDecoder,
6570 coding: &mut TxbTables,
6571 scan: &[u16],
6572 w: usize,
6573 h: usize,
6574 skip_ctx: usize,
6575 sign_ctx: usize,
6576 default_tx_type: TxType,
6577) -> Result<(Grid, TxType)> {
6578 let rect_trace = coeff_trace_on();
6579 let entry_rng = dec.debug_state().0;
6580 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6581 if rect_trace {
6582 eprintln!(
6583 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
6584 all_zero as i32,
6585 dec.debug_state().0
6586 );
6587 }
6588 if all_zero {
6589 return Ok((Grid::Zero(w * h), TxType::DctDct));
6590 }
6591 let mut grid = vec![0i32; w * h];
6592 hit!(RECT_COEFF_TU_HITS);
6593 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
6594 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
6595 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
6596 // context offsets -- both of which now have rect forms
6597 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
6598 // The rect sets that carry no symbol at all still pass `None` here.
6599 let mut tx_type = default_tx_type;
6600 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6601 let len = tx_type_cdf.len();
6602 let t = dec.symbol(tx_type_cdf);
6603 crate::census::tx_type(len, t);
6604 tx_type = tx_type_from_symbol(len, t)
6605 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6606 if rect_trace {
6607 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
6608 }
6609 }
6610 let class = TxClass::of(tx_type);
6611 if class != TxClass::TwoD {
6612 hit!(TX_CLASS1_HITS);
6613 }
6614 let eob = read_eob(dec, coding, class);
6615 if rect_trace {
6616 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
6617 }
6618 let class_scan;
6619 let scan: &[u16] = if class == TxClass::TwoD {
6620 scan
6621 } else {
6622 class_scan = class_scan_table_wh(w, h, class);
6623 &class_scan
6624 };
6625 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
6626 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
6627 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
6628 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
6629 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
6630 // mask rather than a hardware divide.
6631 let stride = w + 4;
6632 let n = stride * (h + 4);
6633 debug_assert!(w.is_power_of_two() && n <= 36 * 36);
6634 let (mut b96, mut b256, mut b768);
6635 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
6636 let levels: &mut [u8] = if n <= 96 {
6637 b96 = [0u8; 96];
6638 &mut b96[..n]
6639 } else if n <= 256 {
6640 b256 = [0u8; 256];
6641 &mut b256[..n]
6642 } else {
6643 b768 = [0u8; 768];
6644 &mut b768[..n]
6645 };
6646 let wsh = w.trailing_zeros();
6647 let wmask = w - 1;
6648 // lane-coefread: the non-zero list [`read_coeffs`] documents.
6649 let mut nz_buf = [0u16; 1024];
6650 let mut nz_n = 0usize;
6651 let (base_taps, br_taps) = flat_taps(stride, class);
6652 let (wlt, wgt) = (w < h, w > h);
6653 for scan_idx in (0..eob).rev() {
6654 let pos = scan[scan_idx] as usize;
6655 let (row, col) = (pos >> wsh, pos & wmask);
6656 let idx = row * stride + col;
6657 // libaom's column-major `coeff_idx`, for ladder comparison.
6658 let _apos = col * h + row;
6659 let level = if scan_idx == eob - 1 {
6660 let ctx = eob_coeff_ctx(scan_idx, w * h);
6661 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6662 if rect_trace {
6663 eprintln!(
6664 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6665 dec.debug_state().0
6666 );
6667 }
6668 v
6669 } else {
6670 let ctx = if class == TxClass::TwoD {
6671 if row == 0 && col == 0 {
6672 0
6673 } else {
6674 let m = base_mag(levels, idx, &base_taps);
6675 if wlt && row < 2 {
6676 m + 11
6677 } else if wgt && col < 2 {
6678 m + 16
6679 } else {
6680 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6681 }
6682 }
6683 } else {
6684 base_ctx_rect(levels, stride, w, h, row, col, class)
6685 };
6686 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6687 if rect_trace {
6688 eprintln!(
6689 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6690 dec.debug_state().0
6691 );
6692 }
6693 v
6694 };
6695 let level = if level > NUM_BASE_LEVELS {
6696 let ctx = {
6697 let mag = br_mag(levels, idx, &br_taps);
6698 if row == 0 && col == 0 {
6699 mag
6700 } else {
6701 let near_origin = match class {
6702 TxClass::TwoD => row < 2 && col < 2,
6703 TxClass::Horiz => col == 0,
6704 TxClass::Vert => row == 0,
6705 };
6706 if near_origin { mag + 7 } else { mag + 14 }
6707 }
6708 };
6709 let mut level = level;
6710 let mut sent = 0;
6711 loop {
6712 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6713 if rect_trace {
6714 eprintln!(
6715 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
6716 dec.debug_state().0
6717 );
6718 }
6719 level += k;
6720 sent += BR_STEP;
6721 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6722 break;
6723 }
6724 }
6725 level
6726 } else {
6727 level
6728 };
6729 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6730 levels[idx] = level as u8;
6731 if level != 0 {
6732 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6733 nz_n += 1;
6734 }
6735 if rect_trace {
6736 let (rng, _) = dec.debug_state();
6737 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
6738 }
6739 }
6740 if rect_trace {
6741 let (rng, _) = dec.debug_state();
6742 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6743 }
6744 for &packed in nz_buf[..nz_n].iter().rev() {
6745 let pos = scan[(packed >> 4) as usize] as usize;
6746 let level = (packed & 15) as i32;
6747 let negative = if pos == 0 {
6748 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
6749 } else {
6750 dec.literal(1) == 1
6751 };
6752 if rect_trace {
6753 let (rng, _) = dec.debug_state();
6754 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
6755 }
6756 let level = if level > MAX_BR_LEVEL {
6757 let g = read_golomb(dec)?;
6758 level + g as i32
6759 } else {
6760 level
6761 };
6762 grid[pos] = if negative { -level } else { level };
6763 }
6764 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
6765 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
6766 // grids differ is a reader defect, one whose grids agree is a transform
6767 // defect.
6768 if crate::envflags::env_flag!("EC_DQCOEFF") {
6769 let nz: Vec<String> = grid
6770 .iter()
6771 .enumerate()
6772 .filter(|&(_, &v)| v != 0)
6773 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
6774 .collect();
6775 eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(","));
6776 }
6777 Ok((Grid::Own(grid), tx_type))
6778}
6779
6780/// What one coded block leaves behind for the blocks that read it as a
6781/// neighbour: whether it coded anything at all, and the sign of its DC —
6782/// [`crate::tile`]'s own private `Neighbour`.
6783#[derive(Clone, Copy, Default)]
6784struct Neighbour {
6785 /// The transform unit's cumulative coefficient level (spec `cul_level`,
6786 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
6787 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
6788 /// boolean (`level != 0`) is enough for every context this decoder read
6789 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
6790 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
6791 /// needs the actual magnitude tier of its above/left neighbours, not
6792 /// just whether they coded anything.
6793 level: u8,
6794 dc: Option<bool>,
6795}
6796
6797/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
6798/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
6799/// grid is dropped, never a panic. One `memset` per grid row instead of a
6800/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
6801/// is contiguous, so this writes exactly the cells the cell loop did,
6802/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
6803/// next row.
6804#[inline]
6805fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
6806 let end = (start + n).min(dst.len());
6807 if start < end {
6808 dst[start..end].fill(v);
6809 }
6810}
6811
6812fn neighbour_state(grid: &[i32]) -> Neighbour {
6813 // lane-coefgrid: the shared zero grid sums to zero by construction; this
6814 // sum has no early exit, so the 60% of units that code nothing used to
6815 // walk their whole grid here.
6816 if is_zero_grid(grid) {
6817 return Neighbour::default();
6818 }
6819 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
6820 Neighbour {
6821 level: cul.min(7) as u8,
6822 dc: (grid[0] != 0).then_some(grid[0] < 0),
6823 }
6824}
6825
6826/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6827/// transform unit smaller than the block it sits in): `top`/`left` are the
6828/// above/left neighbours' magnitude tiers, each already clamped to 4.
6829pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6830 [1, 2, 2, 2, 3],
6831 [2, 4, 4, 4, 5],
6832 [2, 4, 4, 4, 5],
6833 [2, 4, 4, 4, 5],
6834 [3, 5, 5, 5, 6],
6835];
6836
6837/// The `skip` flag, its written-instrument bit, and the covering coded
6838/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
6839/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
6840/// nothing else, so a block's row is one fill instead of four, and the
6841/// deblocker's `pu_edge` reads origin and dims off one cache line.
6842#[derive(Clone, Copy)]
6843struct BlkCell {
6844 skip: bool,
6845 written: bool,
6846 org: [u16; 2],
6847 dim: [u8; 2],
6848}
6849
6850/// The neighbour state a block's contexts are read from — a duplicate of
6851/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
6852/// territory this round), kept at the same two granularities the real writer
6853/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
6854/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
6855/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
6856/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
6857/// chroma transform straddling the true, odd-sized frame edge see its
6858/// neighbour's state clamped at its own subsampled edge rather than luma's.
6859#[derive(Clone)]
6860struct Neighbours {
6861 above: Vec<[Neighbour; 3]>,
6862 left: Vec<[Neighbour; 3]>,
6863 above_mode: Vec<usize>,
6864 left_mode: Vec<usize>,
6865 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
6866 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
6867 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
6868 /// luma one -- the same block can (and often does) code a different
6869 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
6870 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
6871 /// within-block neighbour finer than this grid) is luma-only -- a known,
6872 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
6873 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
6874 above_uv_mode: Vec<usize>,
6875 left_uv_mode: Vec<usize>,
6876 above_side: Vec<usize>,
6877 left_side: Vec<usize>,
6878 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
6879 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
6880 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
6881 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
6882 /// array cannot tell the second leaf's partition symbol that the first
6883 /// one was coded at 8x8.
6884 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
6885 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
6886 above_side_mi: Vec<u8>,
6887 left_side_mi: Vec<u8>,
6888 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
6889 /// / row, with the mi position it was written at
6890 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
6891 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
6892 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
6893 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
6894 /// leaf whose neighbour is another split group needs that group's leaf 3
6895 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
6896 /// and read only by [`decode_leaf_split4`]; the position guard makes it
6897 /// fall back to the coarse slot whenever the real neighbour was a block
6898 /// of 8x8 or larger (whose one mode is correct for every row it spans).
6899 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
6900 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
6901 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
6902 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
6903 /// frame is 65536 px = 16384 mi).
6904 sub8_mode_col: Vec<(u16, u8)>,
6905 sub8_mode_row: Vec<(u16, u8)>,
6906 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
6907 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
6908 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
6909 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
6910 /// the leaf above writes the same row slot the block to the left owns.
6911 uv_mode_col: Vec<(u16, u8)>,
6912 uv_mode_row: Vec<(u16, u8)>,
6913 /// Every mi cell's own `uv_mode`, the mi grid libaom's
6914 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
6915 /// blockd.h). lane-t900 r12: the one-slot-per-column
6916 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
6917 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
6918 /// overwrote the row the pair's chroma-ref half then wanted to read --
6919 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
6920 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
6921 uv_mode_grid: Vec<u8>,
6922 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
6923 /// every other band here).
6924 uv_grid_cols: usize,
6925 /// Whether the block above/left of this column/row was coded `skip` --
6926 /// an inter frame's own `skip` context (spec `SkipContext`), which the
6927 /// key-frame writer never tracks (its skip context is always zero); a
6928 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
6929 /// `left_skip`.
6930 above_skip: Vec<bool>,
6931 left_skip: Vec<bool>,
6932 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
6933 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
6934 /// pixels last written over each unit by `set_txfm_ctxs`/
6935 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
6936 /// symbol reads its context from (lane-txselect, spec 5.11.17).
6937 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
6938 /// array is exactly libaom's per-superblock-row reset, since each mi row
6939 /// is only ever visited inside one superblock row.
6940 above_txfm: Vec<u8>,
6941 left_txfm: Vec<u8>,
6942 /// Whether the block above/left of this column/row coded `skip_mode`
6943 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
6944 /// lane-av1comp round 14.
6945 above_skip_mode: Vec<bool>,
6946 left_skip_mode: Vec<bool>,
6947 /// Whether the block above/left was coded inter -- the `is_inter`
6948 /// context (spec `av1_get_intra_inter_context`), a duplicate of
6949 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
6950 above_inter: Vec<bool>,
6951 left_inter: Vec<bool>,
6952 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
6953 /// alphabet) the block above/left of this column/row coded, or `-1` for
6954 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
6955 /// functions (`mvstack::ref_ctx` family) need the real reference, not
6956 /// just "was it inter" (lane-av1refs: every inter block used to be
6957 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
6958 /// enough).
6959 above_ref: Vec<i8>,
6960 left_ref: Vec<i8>,
6961 /// The block above/left's *second* reference frame when it was coded
6962 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
6963 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
6964 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
6965 /// `i8`, once a compound `read_ref_frames` lands.
6966 /// lane-publish2 audit: the "always `None` today" note this doc used to
6967 /// carry is long stale -- compound blocks do occur, and
6968 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
6969 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
6970 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
6971 /// [`crate::mvstack::NeighbourRef`] construction (class
6972 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
6973 above_ref1: Vec<Option<i8>>,
6974 left_ref1: Vec<Option<i8>>,
6975 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
6976 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
6977 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
6978 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
6979 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
6980 above_comp_group_idx: Vec<u8>,
6981 left_comp_group_idx: Vec<u8>,
6982 above_compound_idx: Vec<u8>,
6983 left_compound_idx: Vec<u8>,
6984 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
6985 /// `3` = "no info": an intra neighbour or the frame's own border) of the
6986 /// block above/left of this column/row -- spec
6987 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
6988 above_filter: Vec<[u8; 2]>,
6989 left_filter: Vec<[u8; 2]>,
6990 mi_cols: usize,
6991 mi_rows: usize,
6992 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
6993 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
6994 /// 7.15) never filters an 8x8 luma block whose covering coded block read
6995 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
6996 /// grain [`Self::record_mi`] already writes at), read back at 8x8
6997 /// granularity by [`apply_cdef`] since `skip` is constant across every
6998 /// mi cell one coded block covers.
6999 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
7000 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
7001 /// the `skip` bit at this mi cell during this frame. A fresh
7002 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
7003 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
7004 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
7005 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
7006 /// unobservable from the pixels alone. Counted by
7007 /// [`cdef_unwritten_skip_units`].
7008 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
7009 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
7010 /// which re-enables the loop filter at a prediction boundary between two
7011 /// skipped inter blocks (lane-mergefix r4). Written by
7012 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
7013 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
7014 /// that cell -- the other half of `pu_edge`: libaom tests the edge
7015 /// coordinate against the block's size in the FILTERED plane's own
7016 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
7017 blk_grid: Vec<BlkCell>,
7018 skip_grid_cols_mi: usize,
7019 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
7020 /// never splits a coded block's transform below its own size (round 2:
7021 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
7022 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
7023 /// edge-length lookup (`apply_deblock`).
7024 tx_grid: Vec<u8>,
7025 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
7026 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
7027 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
7028 tx_h_grid: Vec<u8>,
7029 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
7030 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
7031 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
7032 /// does NOT follow luma's `tx_depth` split, so deriving it as
7033 /// `tx_grid / 2` invented chroma transform edges the deblocker then
7034 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
7035 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
7036 /// every caller routes through.
7037 uv_tx_grid: Vec<u8>,
7038 uv_tx_h_grid: Vec<u8>,
7039 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
7040 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
7041 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
7042 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
7043 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
7044 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
7045 /// reference onto `LAST_FRAME`'s own delta).
7046 ref_grid: Vec<i8>,
7047 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
7048 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
7049 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
7050 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
7051 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
7052 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
7053 /// to know which mode produced the value.
7054 delta_lf_grid: Vec<[i8; 4]>,
7055 /// The block above/left's own palette-Y size (0 = not a palette block)
7056 /// and its base colours -- `av1_get_palette_mode_ctx`/
7057 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
7058 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
7059 above_palette_size: Vec<u8>,
7060 left_palette_size: Vec<u8>,
7061 above_palette_colors: Vec<[u16; 8]>,
7062 left_palette_colors: Vec<[u16; 8]>,
7063 /// As the four fields above, for the neighbour's own chroma (U-channel
7064 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
7065 /// palette size/colours (lane-palette2 r1).
7066 above_palette_uv_size: Vec<u8>,
7067 left_palette_uv_size: Vec<u8>,
7068 above_palette_uv_colors: Vec<[u16; 8]>,
7069 left_palette_uv_colors: Vec<[u16; 8]>,
7070 /// This tile's own top-left corner, in 4x4 mode-info units (spec
7071 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
7072 /// neighbour" check compares against this instead of literal `0`, since a
7073 /// block at the tile's own top/left edge has no usable neighbour even
7074 /// though a decoded block sits there in the picture (spec `decode_tile`'s
7075 /// per-tile `clear_above_context`/`left_available`/`up_available`).
7076 /// `0` for a single-tile frame, matching every existing caller exactly.
7077 tile_row0_mi: usize,
7078 tile_col0_mi: usize,
7079}
7080
7081#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7082impl Neighbours {
7083 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
7084 /// true (unpadded) size in 4x4 mode-info units.
7085 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
7086 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
7087 // neighbour state over the whole 64-row extent, past the frame's last
7088 // mi row (mi_rows 198, block rows 192..208). libaom's own context
7089 // buffers are superblock-aligned for exactly that reason
7090 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
7091 // side arrays to a superblock multiple and leave those cells unread --
7092 // every availability check uses the true `mi_rows`/`mi_cols` below.
7093 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
7094 let (cols, rows) = (
7095 cols.next_multiple_of(sb_sub),
7096 rows.next_multiple_of(sb_sub),
7097 );
7098 Self {
7099 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
7100 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
7101 above_mode: vec![DC_PRED; cols],
7102 left_mode: vec![DC_PRED; rows],
7103 above_uv_mode: vec![DC_PRED; cols],
7104 left_uv_mode: vec![DC_PRED; rows],
7105 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
7106 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
7107 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
7108 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
7109 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7110 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7111 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7112 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7113 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
7114 uv_grid_cols: cols * (SUB / MI),
7115 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
7116 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
7117 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
7118 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
7119 // 16x16 block beside it, which a SUB-grid slot cannot name
7120 // (class context-read-from-one-cell).
7121 above_skip: vec![false; cols * (SUB / MI)],
7122 left_skip: vec![false; rows * (SUB / MI)],
7123 above_skip_mode: vec![false; cols * (SUB / MI)],
7124 left_skip_mode: vec![false; rows * (SUB / MI)],
7125 above_inter: vec![false; cols * (SUB / MI)],
7126 left_inter: vec![false; rows * (SUB / MI)],
7127 above_ref: vec![-1; cols * (SUB / MI)],
7128 left_ref: vec![-1; rows * (SUB / MI)],
7129 above_ref1: vec![None; cols * (SUB / MI)],
7130 left_ref1: vec![None; rows * (SUB / MI)],
7131 above_comp_group_idx: vec![0; cols * (SUB / MI)],
7132 left_comp_group_idx: vec![0; rows * (SUB / MI)],
7133 above_compound_idx: vec![0; cols * (SUB / MI)],
7134 left_compound_idx: vec![0; rows * (SUB / MI)],
7135 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
7136 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
7137 mi_cols,
7138 mi_rows,
7139 blk_grid: vec![
7140 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
7141 cols * (SUB / MI) * rows * (SUB / MI)
7142 ],
7143 skip_grid_cols_mi: cols * (SUB / MI),
7144 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7145 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7146 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7147 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7148 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
7149 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
7150 above_palette_size: vec![0; cols * (SUB / MI)],
7151 left_palette_size: vec![0; rows * (SUB / MI)],
7152 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7153 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7154 above_palette_uv_size: vec![0; cols * (SUB / MI)],
7155 left_palette_uv_size: vec![0; rows * (SUB / MI)],
7156 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7157 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7158 tile_row0_mi: 0,
7159 tile_col0_mi: 0,
7160 }
7161 }
7162
7163 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
7164 /// tile's own column span (`col1_mi` exclusive), plus recording
7165 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
7166 /// availability check below. Left context resets every superblock row
7167 /// regardless of tile ([`Self::start_row`], already called once per SB
7168 /// row by every caller) so it needs no tile-specific reset here.
7169 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
7170 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
7171 // are tile-relative, same as every other neighbour lookup here.
7172 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
7173 self.tile_row0_mi = row0_mi;
7174 self.tile_col0_mi = col0_mi;
7175 let end = col1_mi.min(self.above.len());
7176 for i in col0_mi.min(end)..end {
7177 self.above[i] = Default::default();
7178 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
7179 }
7180 let (sc0, sc1) = (
7181 col0_mi / (SUB / MI),
7182 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
7183 );
7184 for i in sc0.min(sc1)..sc1 {
7185 self.above_mode[i] = DC_PRED;
7186 self.above_side[i] = NO_NEIGHBOUR_SIDE;
7187 }
7188 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
7189 // the tile's own mi column span directly.
7190 let mend = col1_mi.min(self.above_skip.len());
7191 for i in col0_mi.min(mend)..mend {
7192 self.above_skip[i] = false;
7193 self.above_skip_mode[i] = false;
7194 self.above_inter[i] = false;
7195 self.above_ref[i] = -1;
7196 self.above_ref1[i] = None;
7197 self.above_comp_group_idx[i] = 0;
7198 self.above_compound_idx[i] = 0;
7199 self.above_filter[i] = [3u8; 2];
7200 }
7201 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
7202 // stale `(row, mode)` from the tile to the LEFT names an mi row this
7203 // tile's first block would read as its own above neighbour.
7204 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
7205 for i in col0_mi.min(mcol_end)..mcol_end {
7206 self.sub8_mode_col[i] = (u16::MAX, 0);
7207 self.uv_mode_col[i] = (u16::MAX, 0);
7208 }
7209 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
7210 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
7211 // not zero) -- without it a second tile column reads the first one's
7212 // resolved transform sizes as its own above context.
7213 let tend = col1_mi.min(self.above_txfm.len());
7214 for i in col0_mi.min(tend)..tend {
7215 self.above_txfm[i] = TXFM_CTX_INIT;
7216 }
7217 }
7218
7219 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
7220 /// for a non-palette block, clearing any stale neighbour state) into every
7221 /// [`SUB`]-grid cell it covers on both the above and left edges --
7222 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
7223 /// call sites are all square blocks).
7224 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7225 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
7226 }
7227
7228 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
7229 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
7230 /// [`Self::record`]): a true rect strip's above/left neighbour spans
7231 /// differ.
7232 fn record_palette_y_rect(
7233 &mut self,
7234 mi: (usize, usize),
7235 w: usize,
7236 h: usize,
7237 size: usize,
7238 colors: [u16; 8],
7239 ) {
7240 let (r, c) = mi;
7241 if crate::envflags::env_flag!("EC_PALPUB") {
7242 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7243 }
7244 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7245 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7246 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7247 // old SUB grid let a 16x8 strip pair share one slot, so the second
7248 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7249 // cache came out one entry short (class [[context-read-from-one-cell]]).
7250 for cell in 0..(w / MI).max(1) {
7251 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7252 *e = size as u8;
7253 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7254 // neighbour's colours only where its palette size > 0, so a
7255 // non-palette block need not stamp 16 bytes of zeroes here.
7256 if size > 0 {
7257 self.above_palette_colors[c + cell] = colors;
7258 }
7259 }
7260 }
7261 for cell in 0..(h / MI).max(1) {
7262 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7263 *e = size as u8;
7264 if size > 0 {
7265 self.left_palette_colors[r + cell] = colors;
7266 }
7267 }
7268 }
7269 }
7270
7271 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7272 /// neighbours that are themselves a palette-Y block, plus
7273 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7274 /// cache (pred_common.c:73).
7275 ///
7276 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7277 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7278 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7279 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7280 /// the ctx too made every superblock in the frame's second SB row read
7281 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7282 /// palette block decoded as "no palette" and the tile desynced from
7283 /// there (class [[cdf-row-held-constant]]).
7284 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7285 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7286 }
7287
7288 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7289 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7290 /// drops the above neighbour on a 64-px superblock boundary
7291 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7292 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7293 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7294 /// every strip in an SB's top cell row, which libaom does not do.
7295 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7296 let (r, c) = mi;
7297 let above_ok = r % 16 != 0;
7298 // `xd->above_mbmi` exists for every row but the tile's own first.
7299 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7300 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7301 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7302 } else {
7303 (0, [0u16; 8])
7304 };
7305 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7306 // is NULL whenever the block sits at its TILE's own left column
7307 // (`left_available`), not the frame's -- without this guard a second
7308 // tile column reads the previous tile's palette colours into its cache
7309 // and its `palette_y_mode` ctx.
7310 let left_ok = c > self.tile_col0_mi;
7311 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7312 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7313 } else {
7314 (0, [0u16; 8])
7315 };
7316 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7317 let mut cache = Vec::with_capacity(16);
7318 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7319 if cache.last() != Some(&v) {
7320 cache.push(v);
7321 }
7322 };
7323 let (mut ai, mut li) = (0usize, 0usize);
7324 while ai < above_n && li < left_n {
7325 let (va, vl) = (above_colors[ai], left_colors[li]);
7326 if vl < va {
7327 push_dedup(&mut cache, vl);
7328 li += 1;
7329 } else {
7330 push_dedup(&mut cache, va);
7331 ai += 1;
7332 if vl == va {
7333 li += 1;
7334 }
7335 }
7336 }
7337 while ai < above_n {
7338 push_dedup(&mut cache, above_colors[ai]);
7339 ai += 1;
7340 }
7341 while li < left_n {
7342 push_dedup(&mut cache, left_colors[li]);
7343 li += 1;
7344 }
7345 (ctx, cache)
7346 }
7347
7348 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7349 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7350 /// same way (lane-palette2 r1).
7351 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7352 self.record_palette_uv_rect(
7353 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7354 side,
7355 side,
7356 size,
7357 colors,
7358 );
7359 }
7360
7361 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7362 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7363 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7364 /// luma resolution regardless of which plane the recorded state is for).
7365 fn record_palette_uv_rect(
7366 &mut self,
7367 mi: (usize, usize),
7368 w: usize,
7369 h: usize,
7370 size: usize,
7371 colors: [u16; 8],
7372 ) {
7373 let (r, c) = mi;
7374 // mi granularity, see [`Self::record_palette_y_rect`].
7375 for cell in 0..(w / MI).max(1) {
7376 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7377 *e = size as u8;
7378 if size > 0 {
7379 self.above_palette_uv_colors[c + cell] = colors;
7380 }
7381 }
7382 }
7383 for cell in 0..(h / MI).max(1) {
7384 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7385 *e = size as u8;
7386 if size > 0 {
7387 self.left_palette_uv_colors[r + cell] = colors;
7388 }
7389 }
7390 }
7391 }
7392
7393 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7394 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7395 /// no neighbour lookup at all (it is this block's own just-decided Y
7396 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7397 /// so only the cache is wanted here.
7398 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7399 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7400 }
7401
7402 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7403 /// [`Self::palette_ctx_and_cache_mi`].
7404 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7405 let (r, c) = mi;
7406 let above_ok = r % 16 != 0;
7407 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7408 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7409 } else {
7410 (0, [0u16; 8])
7411 };
7412 // Same tile-relative left availability as the luma cache above.
7413 let left_ok = c > self.tile_col0_mi;
7414 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7415 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7416 } else {
7417 (0, [0u16; 8])
7418 };
7419 let mut cache = Vec::with_capacity(16);
7420 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7421 if cache.last() != Some(&v) {
7422 cache.push(v);
7423 }
7424 };
7425 let (mut ai, mut li) = (0usize, 0usize);
7426 while ai < above_n && li < left_n {
7427 let (va, vl) = (above_colors[ai], left_colors[li]);
7428 if vl < va {
7429 push_dedup(&mut cache, vl);
7430 li += 1;
7431 } else {
7432 push_dedup(&mut cache, va);
7433 ai += 1;
7434 if vl == va {
7435 li += 1;
7436 }
7437 }
7438 }
7439 while ai < above_n {
7440 push_dedup(&mut cache, above_colors[ai]);
7441 ai += 1;
7442 }
7443 while li < left_n {
7444 push_dedup(&mut cache, left_colors[li]);
7445 li += 1;
7446 }
7447 cache
7448 }
7449
7450 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7451 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7452 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7453 /// units as [`Self::fill_skip_grid`].
7454 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7455 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7456 }
7457
7458 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7459 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7460 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7461 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
7462 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
7463 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
7464 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
7465 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
7466 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
7467 /// block's published transform extent to its own size is exactly that
7468 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
7469 /// that needs it is the 128 root, whose chroma extent (64) is the one
7470 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
7471 /// never suppressed (libaom's `is_inter_block` term), so this is called
7472 /// only from the skipped-inter branch.
7473 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
7474 let (mi_r, mi_c) = at_mi;
7475 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
7476 for rr in 0..h_mi {
7477 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7478 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
7479 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
7480 }
7481 }
7482
7483 fn fill_lf_grid_rect(
7484 &mut self,
7485 at_mi: (usize, usize),
7486 w_mi: usize,
7487 h_mi: usize,
7488 tx_px: u8,
7489 tx_h_px: u8,
7490 ref_frame: i8, fctx: &crate::decode::FrameCtx,
7491 ) {
7492 let (mi_r, mi_c) = at_mi;
7493 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
7494 // half its luma one (min 4 px, the smallest transform), capped at
7495 // TX_32X32 -- independent of this block's luma `tx_depth`.
7496 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
7497 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
7498 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7499 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}");
7500 }
7501 crate::census::tx(tx_px, tx_h_px);
7502 let cur = fctx.current_delta_lf.with(|c| c.get());
7503 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
7504 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
7505 } else {
7506 [cur[0].clamp(-63, 63) as i8; 4]
7507 };
7508 for rr in 0..h_mi {
7509 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7510 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7511 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7512 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
7513 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
7514 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
7515 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
7516 }
7517 }
7518
7519 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
7520 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
7521 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
7522 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
7523 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
7524 /// dims from the LEAF span and so invented chroma transform edges the
7525 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
7526 /// are already correct from the block's own fill over the same span.
7527 fn fill_lf_grid_leaf_luma(
7528 &mut self,
7529 at_mi: (usize, usize),
7530 w_mi: usize,
7531 h_mi: usize,
7532 tx_px: u8,
7533 tx_h_px: u8,
7534 ) {
7535 let (mi_r, mi_c) = at_mi;
7536 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7537 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}");
7538 }
7539 for rr in 0..h_mi {
7540 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7541 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7542 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7543 }
7544 }
7545
7546 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
7547 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
7548 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
7549 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
7550 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
7551 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
7552 }
7553
7554 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
7555 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
7556 let (mi_r, mi_c) = at_mi;
7557 if skip && w_mi != h_mi {
7558 hit!(RECT_SKIP_BAND_HITS);
7559 }
7560 // lane-census: an INTRA frame's blocks never reach the inter
7561 // publisher, and this one is what every coded block writes.
7562 crate::census::block_intra_frame(w_mi, h_mi, skip);
7563 for rr in 0..h_mi {
7564 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7565 fill_span(
7566 &mut self.blk_grid,
7567 start,
7568 w_mi,
7569 BlkCell {
7570 skip,
7571 written: true,
7572 org: [mi_r as u16, mi_c as u16],
7573 dim: [w_mi as u8, h_mi as u8],
7574 },
7575 );
7576 }
7577 }
7578
7579 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
7580 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
7581 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
7582 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
7583 /// straddle the region with a mix of skip/non-skip blocks).
7584 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
7585 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
7586 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
7587 /// filtered edge's two sides are each exactly one coded block wide.
7588 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
7589 self.blk_grid
7590 .get(mi_r * self.skip_grid_cols_mi + mi_c)
7591 .is_some_and(|c| c.skip)
7592 }
7593
7594 /// The `skip_txfm` context of a block whose top-left mi cell is
7595 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
7596 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
7597 /// with an absent neighbour contributing 0. The mi grid is per tile, so
7598 /// row/column 0 is a tile edge and has no neighbour on that axis.
7599 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
7600 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
7601 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
7602 }
7603
7604 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
7605 (0..2).all(|rr| {
7606 (0..2).all(|cc| {
7607 self.blk_grid
7608 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
7609 .is_some_and(|c| c.skip)
7610 })
7611 })
7612 }
7613
7614 fn start_row(&mut self) {
7615 self.left.iter_mut().for_each(|l| *l = Default::default());
7616 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
7617 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
7618 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
7619 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
7620 self.left_skip.iter_mut().for_each(|s| *s = false);
7621 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
7622 self.left_inter.iter_mut().for_each(|i| *i = false);
7623 self.left_ref.iter_mut().for_each(|r| *r = -1);
7624 self.left_ref1.iter_mut().for_each(|r| *r = None);
7625 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
7626 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
7627 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
7628 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
7629 // context (a tile/SB-row boundary has no left neighbour).
7630 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7631 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7632 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
7633 // are per-mi maps like every other one here, so they reset with the
7634 // row too -- the left guard above is what actually stops a cross-tile
7635 // read, this keeps a stale colour out of the arrays at all.
7636 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
7637 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7638 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
7639 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7640 // lane-mergefix r2: `av1_zero_left_context` memsets
7641 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
7642 // every superblock row of every tile -- the var-tx left context does
7643 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
7644 // previous tile column's last block otherwise).
7645 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
7646 }
7647
7648 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
7649 /// block that reads it as a neighbour -- [`crate::tile`]'s
7650 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
7651 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
7652 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
7653 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
7654 /// the real value, not just `is_inter`).
7655 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7656 fn record_inter(
7657 &mut self,
7658 at: (usize, usize),
7659 side: usize,
7660 skip: bool,
7661 is_inter: bool,
7662 ref_frame: i8,
7663 filter: [u8; 2],
7664 skip_mode: bool,
7665 ) {
7666 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
7667 }
7668
7669 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
7670 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
7671 /// r1: a true rectangular strip's above-context span (its own width) and
7672 /// left-context span (its own height) differ, unlike every caller before
7673 /// this round (class neighbour-votes-all-its-fields).
7674 #[allow(clippy::too_many_arguments)]
7675 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7676 fn record_inter_rect(
7677 &mut self,
7678 at: (usize, usize),
7679 w_sub: usize,
7680 h_sub: usize,
7681 skip: bool,
7682 is_inter: bool,
7683 ref_frame: i8,
7684 filter: [u8; 2],
7685 skip_mode: bool,
7686 ) {
7687 let (r, c) = at;
7688 self.record_inter_rect_mi(
7689 (r * (SUB / MI), c * (SUB / MI)),
7690 w_sub / MI,
7691 h_sub / MI,
7692 skip,
7693 is_inter,
7694 ref_frame,
7695 filter,
7696 skip_mode,
7697 );
7698 }
7699
7700 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
7701 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
7702 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
7703 /// routes through the wrapper above.
7704 #[allow(clippy::too_many_arguments)]
7705 fn record_inter_rect_mi(
7706 &mut self,
7707 at_mi: (usize, usize),
7708 w_mi: usize,
7709 h_mi: usize,
7710 skip: bool,
7711 is_inter: bool,
7712 ref_frame: i8,
7713 filter: [u8; 2],
7714 skip_mode: bool,
7715 ) {
7716 let (r, c) = at_mi;
7717 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
7718 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
7719 // writes for a whole block class): an INTER block left the luma mode
7720 // map untouched, so a later intra block's `get_intra_edge_filter_type`
7721 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
7722 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
7723 // block in that pixel row -- the directional edge filter then ran at
7724 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
7725 // which for an inter block is an INTER mode (>= NEARESTMV) and is
7726 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
7727 // already stamped it).
7728 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
7729 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
7730 // uv map must read DC_PRED over an inter block's cells too.
7731 if is_inter {
7732 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7733 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7734 }
7735 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
7736 self.above_skip[c..c + w_mi].fill(skip);
7737 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
7738 self.above_inter[c..c + w_mi].fill(is_inter);
7739 self.above_ref[c..c + w_mi].fill(ref_frame);
7740 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
7741 // this with the block's real second reference for a compound block,
7742 // called right after this one (lane-publish2 audit).
7743 self.above_ref1[c..c + w_mi].fill(None);
7744 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
7745 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
7746 // as `3`/`1` even though this block has no second reference.
7747 // `record_compound_ctx` overwrites this with the real bit for an
7748 // actual compound block's cells, called right after this one.
7749 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
7750 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
7751 self.above_filter[c..c + w_mi].fill(filter);
7752 self.left_skip[r..r + h_mi].fill(skip);
7753 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
7754 self.left_inter[r..r + h_mi].fill(is_inter);
7755 self.left_ref[r..r + h_mi].fill(ref_frame);
7756 self.left_ref1[r..r + h_mi].fill(None);
7757 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
7758 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
7759 self.left_filter[r..r + h_mi].fill(filter);
7760 }
7761
7762 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
7763 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
7764 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
7765 /// `get_comp_index_context`) -- called right after `record_inter` for
7766 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
7767 /// stamps `above_ref1`/`left_ref1` with the block's real second
7768 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
7769 /// this is the one caller that actually knows it) -- so the next block's
7770 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
7771 /// neighbour instead of `record_inter`'s single-ref default.
7772 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7773 fn record_compound_ctx(
7774 &mut self,
7775 at: (usize, usize),
7776 side: usize,
7777 ref1: i8,
7778 comp_group_idx: u8,
7779 compound_idx: u8,
7780 ) {
7781 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
7782 }
7783
7784 /// [`Self::record_compound_ctx`] with independent above/left extents,
7785 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
7786 #[allow(clippy::too_many_arguments)]
7787 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7788 fn record_compound_ctx_rect(
7789 &mut self,
7790 at: (usize, usize),
7791 w_sub: usize,
7792 h_sub: usize,
7793 ref1: i8,
7794 comp_group_idx: u8,
7795 compound_idx: u8,
7796 ) {
7797 let (r, c) = at;
7798 self.record_compound_ctx_rect_mi(
7799 (r * (SUB / MI), c * (SUB / MI)),
7800 w_sub / MI,
7801 h_sub / MI,
7802 ref1,
7803 comp_group_idx,
7804 compound_idx,
7805 );
7806 }
7807
7808 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
7809 /// [`Self::record_inter_rect_mi`]).
7810 fn record_compound_ctx_rect_mi(
7811 &mut self,
7812 at_mi: (usize, usize),
7813 w_mi: usize,
7814 h_mi: usize,
7815 ref1: i8,
7816 comp_group_idx: u8,
7817 compound_idx: u8,
7818 ) {
7819 let (r, c) = at_mi;
7820 crate::census::compound();
7821 for cell in 0..w_mi {
7822 self.above_ref1[c + cell] = Some(ref1);
7823 self.above_comp_group_idx[c + cell] = comp_group_idx;
7824 self.above_compound_idx[c + cell] = compound_idx;
7825 }
7826 for cell in 0..h_mi {
7827 self.left_ref1[r + cell] = Some(ref1);
7828 self.left_comp_group_idx[r + cell] = comp_group_idx;
7829 self.left_compound_idx[r + cell] = compound_idx;
7830 }
7831 }
7832
7833 /// The context of a block's partition symbol: delegates to the mi-precise
7834 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
7835 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
7836 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
7837 /// only touches the finer mi arrays -- leaves them stale for the *next*
7838 /// sibling's own partition symbol.
7839 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
7840 let (r, c) = at;
7841 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
7842 }
7843
7844 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
7845 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
7846 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
7847 /// than the enclosing 16x16 slot's stale, shared state.
7848 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
7849 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
7850 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
7851 }
7852
7853 /// The gathered coded/DC-sign state of the blocks above and to the left
7854 /// of a block `side` samples across, per plane.
7855 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7856 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
7857 }
7858
7859 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
7860 /// units, for the same reason [`Self::record_mi`] does.
7861 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7862 let side_mi = side / MI;
7863 // One pass over the cells accumulating all three planes, not one pass
7864 // per plane: the three planes of a cell live in the same
7865 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
7866 // cache lines three times (lane-publish).
7867 let mut out = [(false, false, 0i32); 3];
7868 for cell in 0..side_mi {
7869 let above = &self.above[mi_c + cell];
7870 let left = &self.left[mi_r + cell];
7871 for (plane, o) in out.iter_mut().enumerate() {
7872 o.0 |= above[plane].level != 0;
7873 o.1 |= left[plane].level != 0;
7874 o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc);
7875 }
7876 }
7877 out
7878 }
7879
7880 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
7881 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
7882 /// extent pattern for a true rectangular strip's own coefficient context.
7883 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7884 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
7885 }
7886
7887 /// [`Self::around_rect`] taking the block's position directly in 4x4
7888 /// mode-info units, mirroring [`Self::around_mi`].
7889 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7890 let (w_mi, h_mi) = (w / MI, h / MI);
7891 // [`Self::around_mi`]'s single pass, with the two extents split.
7892 let mut out = [(false, false, 0i32); 3];
7893 for cell in 0..w_mi {
7894 let above = &self.above[mi_c + cell];
7895 for (plane, o) in out.iter_mut().enumerate() {
7896 o.0 |= above[plane].level != 0;
7897 o.2 += dc_vote(above[plane].dc);
7898 }
7899 }
7900 for cell in 0..h_mi {
7901 let left = &self.left[mi_r + cell];
7902 for (plane, o) in out.iter_mut().enumerate() {
7903 o.1 |= left[plane].level != 0;
7904 o.2 += dc_vote(left[plane].dc);
7905 }
7906 }
7907 if crate::envflags::env_flag!("EC_DCDUMP") {
7908 for (plane, o) in out.iter().enumerate() {
7909 let vote = o.2;
7910 let ab: Vec<String> = (0..w_mi)
7911 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
7912 .collect();
7913 let lf: Vec<String> = (0..h_mi)
7914 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
7915 .collect();
7916 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
7917 }
7918 }
7919 out
7920 }
7921
7922 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
7923 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
7924 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
7925 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
7926 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
7927 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
7928 /// is always 0, spec's `plane_bsize == tx_size` branch).
7929 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
7930 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
7931 }
7932
7933 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
7934 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
7935 /// context over `tx_size_wide` and the left one over `tx_size_high`.
7936 fn luma_skip_ctx_rect(
7937 &self,
7938 (mi_r, mi_c): (usize, usize),
7939 w_mi: usize,
7940 h_mi: usize,
7941 ) -> usize {
7942 let side_mi = w_mi;
7943 let mut top = 0u8;
7944 let mut left = 0u8;
7945 for cell in 0..w_mi {
7946 top |= self.above[mi_c + cell][0].level;
7947 }
7948 for cell in 0..h_mi {
7949 left |= self.left[mi_r + cell][0].level;
7950 }
7951 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
7952 if crate::envflags::env_flag!("EC_ECDUMP") {
7953 let ab: Vec<String> =
7954 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
7955 let lf: Vec<String> =
7956 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
7957 eprintln!(
7958 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
7959 ab.join(","), lf.join(",")
7960 );
7961 }
7962 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7963 eprintln!(
7964 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
7965 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
7966 );
7967 }
7968 ctx
7969 }
7970
7971 /// Writes one coded block into every cell it covers, on both grids: the
7972 /// mode/side arrays up to `side`'s own width, and the coefficient-context
7973 /// arrays up to the true frame edge — the units past it are left at their
7974 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
7975 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
7976 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
7977 /// not from this block's own side).
7978 fn record(
7979 &mut self,
7980 at: (usize, usize),
7981 side: usize,
7982 mode: usize,
7983 uv_mode: usize,
7984 grids: &[&[i32]; 3],
7985 ) {
7986 self.record_rect(at, side, side, mode, uv_mode, grids);
7987 }
7988
7989 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
7990 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
7991 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
7992 /// spec's per-edge partition-context rule, so a true rectangular block
7993 /// naturally wants two different values here rather than one.
7994 /// Writes this block's luma `mode` into the mi-granular
7995 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
7996 /// position a *later* neighbour would read it from: the block's LAST mi
7997 /// row for every column it spans (what the block below reads via
7998 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
7999 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
8000 /// read these back, and only when the recorded position is exactly their
8001 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
8002 fn record_mode_mi(
8003 &mut self,
8004 mi_r: usize,
8005 mi_c: usize,
8006 mi_w: usize,
8007 mi_h: usize,
8008 mode: usize,
8009 ) {
8010 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
8011 let mode = mode as u8;
8012 for cell in 0..mi_w {
8013 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
8014 *slot = (last_r, mode);
8015 }
8016 }
8017 for cell in 0..mi_h {
8018 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
8019 *slot = (last_c, mode);
8020 }
8021 }
8022 }
8023
8024 /// The mi-exact above/left neighbour luma mode for a block whose top-left
8025 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
8026 /// mi position (then the coarse [`SUB`]-grid slot is right by
8027 /// construction). See [`Self::record_mode_mi`].
8028 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8029 match self.sub8_mode_col.get(mi_c) {
8030 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
8031 _ => None,
8032 }
8033 }
8034
8035 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8036 match self.sub8_mode_row.get(mi_r) {
8037 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
8038 _ => None,
8039 }
8040 }
8041
8042 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
8043 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
8044 fn record_uv_mode_mi(
8045 &mut self,
8046 mi_r: usize,
8047 mi_c: usize,
8048 mi_w: usize,
8049 mi_h: usize,
8050 uv_mode: usize,
8051 ) {
8052 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
8053 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
8054 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
8055 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
8056 // covers, so the chroma neighbour read below is a plain grid read.
8057 let stride = self.uv_grid_cols;
8058 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
8059 for row in mi_r..=last_r {
8060 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
8061 }
8062 }
8063
8064 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
8065 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
8066 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
8067 /// block has recorded the exact neighbouring mi.
8068 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
8069 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
8070 // REFERENCE block, not off the mi that carries the chroma syntax.
8071 // `set_mi_row_col` (`blockd.h`) takes
8072 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
8073 // only then `chroma_above_mbmi = base_mi[-stride]` /
8074 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
8075 // the ODD mi, so without the snap we looked one mi row/column too far
8076 // down/right -- the mi-exact slot never matched and the coarse
8077 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
8078 // 8x4 at (688, 100) = mi (51, 344): libaom's
8079 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
8080 // `UV_SMOOTH_PRED`), ours was 0, which flips
8081 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
8082 // false for type 1, TRUE for type 0) and upsampled an edge libaom
8083 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
8084 // predicting from it (class `context-read-from-one-cell`).
8085 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
8086 }
8087
8088 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
8089 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
8090 /// counter wants this: it measures how often the snap CHANGES the answer,
8091 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
8092 /// decode path uses the snapping form.
8093 fn smooth_uv_neighbour_unsnapped(
8094 &self,
8095 mi_r: usize,
8096 mi_c: usize,
8097 r: usize,
8098 c: usize,
8099 ) -> bool {
8100 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
8101 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
8102 // array that `start_tile` does not clear, so a block on a tile's first
8103 // mi row used to read the uv_mode of the block above it in the tile
8104 // ABOVE and filter its chroma edge at that neighbour's strength
8105 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
8106 // at chroma (120, 32), the top-right tile's first block).
8107 let have_above = mi_r > self.tile_row0_mi;
8108 let have_left = mi_c > self.tile_col0_mi;
8109 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
8110 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
8111 {
8112 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
8113 }
8114 // The mi grid is libaom's own read; the two maps below stay as the
8115 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
8116 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
8117 (col < self.uv_grid_cols)
8118 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
8119 .flatten()
8120 .filter(|&m| m != u8::MAX)
8121 .map(usize::from)
8122 };
8123 let above = match self.uv_mode_col.get(mi_c) {
8124 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
8125 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
8126 _ if have_above => self.above_uv_mode[c],
8127 _ => DC_PRED,
8128 };
8129 let left = match self.uv_mode_row.get(mi_r) {
8130 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
8131 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
8132 _ if have_left => self.left_uv_mode[r],
8133 _ => DC_PRED,
8134 };
8135 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
8136 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
8137 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
8138 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
8139 }) {
8140 hit!(UV_MODE_GRID_OVERRIDE_HITS);
8141 }
8142 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
8143 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
8144 // have been filtered at the wrong strength by the coarse map alone.
8145 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
8146 hit!(UV_MODE_MI_OVERRIDE_HITS);
8147 }
8148 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
8149 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
8150 {
8151 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8152 }
8153 is_smooth_mode(above) || is_smooth_mode(left)
8154 }
8155
8156 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
8157 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
8158 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
8159 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
8160 /// holding an OLDER, larger block's mode -- it only ever recorded into the
8161 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
8162 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
8163 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
8164 /// a different CDF for the same mode value).
8165 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
8166 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
8167 /// only when `up_available` and `left_mbmi` only when `left_available`;
8168 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
8169 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
8170 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
8171 /// strip's mode as its "left neighbour" (measured on the band fixture at
8172 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
8173 fn modes_above_left_mi(
8174 &self,
8175 mi_r: usize,
8176 mi_c: usize,
8177 fallback: (usize, usize),
8178 ) -> (usize, usize) {
8179 let above = if mi_r > self.tile_row0_mi {
8180 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
8181 } else {
8182 DC_PRED
8183 };
8184 let left = if mi_c > self.tile_col0_mi {
8185 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
8186 } else {
8187 DC_PRED
8188 };
8189 (above, left)
8190 }
8191
8192 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
8193 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
8194 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
8195 /// per superblock row and never per tile, so the first block column of
8196 /// tile 2..N read the previous tile's mode as its left neighbour, and the
8197 /// above band survives across a tile ROW boundary the same way lane-mtfix's
8198 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
8199 /// `up_available`/`left_available` and uses DC_PRED otherwise
8200 /// ([`Self::modes_above_left_mi`]).
8201 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
8202 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8203 let (above, left) =
8204 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
8205 if above != self.above_mode[c] || left != self.left_mode[r] {
8206 hit!(MODE_MI_OVERRIDE_HITS);
8207 }
8208 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
8209 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
8210 {
8211 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8212 }
8213 // A neighbour the coarse band offered where the tile edge makes it
8214 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
8215 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
8216 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
8217 {
8218 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
8219 }
8220 (above, left)
8221 }
8222
8223 fn record_rect(
8224 &mut self,
8225 at: (usize, usize),
8226 w: usize,
8227 h: usize,
8228 mode: usize,
8229 uv_mode: usize,
8230 grids: &[&[i32]; 3],
8231 ) {
8232 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
8233 }
8234
8235 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
8236 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
8237 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
8238 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
8239 /// the [`SUB`]-unit path does).
8240 fn record_rect_mi(
8241 &mut self,
8242 at_mi: (usize, usize),
8243 w: usize,
8244 h: usize,
8245 mode: usize,
8246 uv_mode: usize,
8247 grids: &[&[i32]; 3],
8248 ) {
8249 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8250 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8251 // last 16-px column/row stamps only the cells that exist (libaom's
8252 // arrays are padded past the frame and those cells are never read).
8253 for cell in 0..w / SUB {
8254 if c + cell >= self.above_mode.len() {
8255 break;
8256 }
8257 self.above_mode[c + cell] = mode;
8258 self.above_uv_mode[c + cell] = uv_mode;
8259 self.above_side[c + cell] = w;
8260 }
8261 for cell in 0..h / SUB {
8262 if r + cell >= self.left_mode.len() {
8263 break;
8264 }
8265 self.left_mode[r + cell] = mode;
8266 self.left_uv_mode[r + cell] = uv_mode;
8267 self.left_side[r + cell] = h;
8268 }
8269 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8270 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8271 self.record_mi_rect(at_mi, w, h, grids);
8272 }
8273
8274 /// The coefficient-context half of [`Self::record`], taking the block's
8275 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8276 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8277 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8278 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8279 self.record_mi_rect(at_mi, side, side, grids);
8280 }
8281
8282 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8283 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8284 fn record_mi_rect(
8285 &mut self,
8286 at_mi: (usize, usize),
8287 w: usize,
8288 h: usize,
8289 grids: &[&[i32]; 3],
8290 ) {
8291 let (mi_r, mi_c) = at_mi;
8292 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8293 let (w_mi, h_mi) = (w / MI, h / MI);
8294 if crate::envflags::env_flag!("EC_ECPUB") {
8295 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8296 }
8297 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8298 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8299 // A chroma 4x4 unit straddling the true luma edge is still whole in
8300 // chroma's own halved grid, so libaom rounds the luma bound up to the
8301 // plane's own 4x4 unit before clamping a subsampled plane
8302 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8303 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8304 let bound_h = [
8305 self.mi_rows,
8306 round_up_even(self.mi_rows),
8307 round_up_even(self.mi_rows),
8308 ];
8309 let bound_w = [
8310 self.mi_cols,
8311 round_up_even(self.mi_cols),
8312 round_up_even(self.mi_cols),
8313 ];
8314 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8315 // past the padded side arrays (mi_rows 198, block rows 192..208);
8316 // libaom's own arrays are superblock-sized, so those cells simply
8317 // have no reader -- [`fill_span`] drops them, as the `break` did.
8318 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8319 // predicate is three contiguous runs: all planes, chroma only, none
8320 // (lane-mi).
8321 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8322 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8323 let uv_only = [Neighbour::default(), states[1], states[2]];
8324 fill_span(&mut self.left, mi_r, luma_h, states);
8325 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8326 fill_span(
8327 &mut self.left,
8328 mi_r + chroma_h,
8329 h_mi - chroma_h,
8330 [Neighbour::default(); 3],
8331 );
8332 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8333 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8334 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8335 fill_span(&mut self.above, mi_c, luma_w, states);
8336 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8337 fill_span(
8338 &mut self.above,
8339 mi_c + chroma_w,
8340 w_mi - chroma_w,
8341 [Neighbour::default(); 3],
8342 );
8343 }
8344
8345 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8346 /// inside a coded block whose luma transform is smaller than its own
8347 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8348 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8349 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8350 /// [`Self::record_split_luma`] still writes once for the whole block.
8351 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8352 /// the caller's own [`Self::record_split_luma`] call sets those once,
8353 /// at the block's own true side, not this TU's.
8354 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8355 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8356 }
8357
8358 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8359 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8360 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8361 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8362 /// coefficient-context arrays are indexed by luma mi, the convention
8363 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8364 /// clamp included.
8365 fn record_mi_chroma(
8366 &mut self,
8367 (mi_r, mi_c): (usize, usize),
8368 w_px: usize,
8369 h_px: usize,
8370 plane: usize,
8371 grid: &[i32],
8372 ) {
8373 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8374 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8375 let state = neighbour_state(grid);
8376 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8377 self.left[mi_r + cell][plane] = state;
8378 }
8379 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
8380 self.above[mi_c + cell][plane] = state;
8381 }
8382 }
8383
8384 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
8385 /// r1): the above context spans the unit's width, the left context its
8386 /// height, which for a square unit is the same loop it always was.
8387 fn record_mi_luma_rect(
8388 &mut self,
8389 (mi_r, mi_c): (usize, usize),
8390 w_px: usize,
8391 h_px: usize,
8392 grid: &[i32],
8393 ) {
8394 let state = neighbour_state(grid);
8395 if crate::envflags::env_flag!("EC_ECPUB") {
8396 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
8397 }
8398 for cell in 0..h_px / MI {
8399 if mi_r + cell < self.mi_rows {
8400 self.left[mi_r + cell][0] = state;
8401 }
8402 }
8403 for cell in 0..w_px / MI {
8404 if mi_c + cell < self.mi_cols {
8405 self.above[mi_c + cell][0] = state;
8406 }
8407 }
8408 }
8409
8410 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
8411 /// block whose luma was decoded as several transform units through
8412 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
8413 /// whole-block luma write -- everything [`Self::record`] does except
8414 /// plane 0, which is already correct per-TU by the time this runs.
8415 fn record_split_luma(
8416 &mut self,
8417 at: (usize, usize),
8418 side: usize,
8419 mode: usize,
8420 uv_mode: usize,
8421 chroma_grids: [&[i32]; 2],
8422 ) {
8423 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
8424 }
8425
8426 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
8427 /// extents in pixels (lane-rectsplit r1), the same relationship
8428 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
8429 /// luma transform split into several square units needs exactly this
8430 /// bookkeeping, at its own true rectangular extents.
8431 fn record_split_luma_rect(
8432 &mut self,
8433 at: (usize, usize),
8434 w: usize,
8435 h: usize,
8436 mode: usize,
8437 uv_mode: usize,
8438 chroma_grids: [&[i32]; 2],
8439 ) {
8440 let (r, c) = at;
8441 self.record_split_luma_rect_mi(
8442 (r * (SUB / MI), c * (SUB / MI)),
8443 w,
8444 h,
8445 mode,
8446 uv_mode,
8447 chroma_grids,
8448 );
8449 }
8450
8451 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
8452 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
8453 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
8454 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
8455 /// convention [`decode_block_rect4`] already established for 1:4 strips.
8456 fn record_split_luma_rect_mi(
8457 &mut self,
8458 at_mi: (usize, usize),
8459 w: usize,
8460 h: usize,
8461 mode: usize,
8462 uv_mode: usize,
8463 chroma_grids: [&[i32]; 2],
8464 ) {
8465 let (mi_r, mi_c) = at_mi;
8466 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8467 for cell in 0..w.div_ceil(SUB) {
8468 if c + cell >= self.above_mode.len() {
8469 break;
8470 }
8471 self.above_mode[c + cell] = mode;
8472 self.above_uv_mode[c + cell] = uv_mode;
8473 self.above_side[c + cell] = w;
8474 }
8475 for cell in 0..h.div_ceil(SUB) {
8476 if r + cell >= self.left_mode.len() {
8477 break;
8478 }
8479 self.left_mode[r + cell] = mode;
8480 self.left_uv_mode[r + cell] = uv_mode;
8481 self.left_side[r + cell] = h;
8482 }
8483
8484 let (w_mi, h_mi) = (w / MI, h / MI);
8485 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
8486 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
8487 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8488 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8489 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8490 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8491 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
8492 let plane = plane_idx + 1;
8493 let state = neighbour_state(grid);
8494 for cell in 0..h_mi {
8495 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
8496 self.left[mi_r + cell][plane] = state;
8497 }
8498 }
8499 for cell in 0..w_mi {
8500 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
8501 self.above[mi_c + cell][plane] = state;
8502 }
8503 }
8504 }
8505 }
8506}
8507
8508/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
8509/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
8510/// exactly — including its skip context, which the real key-frame writer
8511/// always writes at a fixed context of zero (it never tracks a neighbour-based
8512/// one for intra blocks; that is the inter-frame writer's rule instead).
8513/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
8514/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
8515/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
8516/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
8517/// plain DC chroma.
8518/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
8519/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
8520/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
8521/// instead (the defect commit 1a89ed9 fixed at the square sites).
8522pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
8523 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
8524 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
8525}
8526
8527/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
8528/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
8529/// bound (spec `filter_intra_mode_info` never reads a symbol there).
8530pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
8531 match side {
8532 4 => Some(0),
8533 8 => Some(1),
8534 16 => Some(2),
8535 32 => Some(3),
8536 _ => None,
8537 }
8538}
8539
8540/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
8541/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
8542/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
8543/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
8544fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8545 match (bw, bh) {
8546 (32, 16) => Some(4),
8547 (16, 32) => Some(5),
8548 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
8549 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
8550 // here dropped that symbol on every DC_PRED strip of that size and
8551 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
8552 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
8553 (16, 8) => Some(6),
8554 (8, 16) => Some(7),
8555 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
8556 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
8557 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
8558 (4, 8) => Some(8),
8559 (8, 4) => Some(9),
8560 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
8561 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
8562 // `use_filter_intra` symbol on those strips although aomenc writes
8563 // one for every DC_PRED block of that shape with
8564 // `--enable-filter-intra=1` (its default), silently desyncing the
8565 // tile (class symbol-consumption-gap).
8566 (32, 8) => Some(10),
8567 (8, 32) => Some(11),
8568 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
8569 // strips), rows 17/16 of `default_filter_intra_cdfs`.
8570 (16, 4) => Some(12),
8571 (4, 16) => Some(13),
8572 _ if bw == bh => filter_intra_size_class(bw),
8573 _ => None,
8574 }
8575}
8576
8577/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
8578/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
8579/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8580/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8581/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8582pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8583 palette_bsize_ctx_wh(side, side)
8584}
8585
8586/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
8587/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
8588/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
8589/// for ANY bsize, not just the square ones a hand-picked table happened to
8590/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
8591/// row breaks the moment its indexing field moves off the diagonal, and a
8592/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
8593/// block dimension is a power of two, so `bw*bh` always is too and
8594/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
8595/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
8596fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
8597 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
8598 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
8599 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
8600 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
8601 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
8602 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
8603 if bw > 64 || bh > 64 || bw * bh < 64 {
8604 return None;
8605 }
8606 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
8607}
8608
8609/// A just-decoded palette-Y block's own size, base colours (only the first
8610/// `size` entries are real), and per-pixel colour-index map (`side*side`,
8611/// row-major, each entry `< size`).
8612struct PaletteY {
8613 size: usize,
8614 colors: [u16; 8],
8615 map: Vec<u8>,
8616}
8617
8618/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
8619/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
8620/// shared between U and V, both co-located after 4:2:0 subsampling) plus
8621/// each plane's own base colours.
8622struct PaletteUv {
8623 size: usize,
8624 u_colors: [u16; 8],
8625 v_colors: [u16; 8],
8626 map: Vec<u8>,
8627}
8628
8629/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
8630/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8631/// `get_unsigned_bits`, which is the same formula): smallest `n` with
8632/// `2^n >= x`, `0` for `x <= 1`.
8633pub(crate) fn ceil_log2(x: u32) -> u32 {
8634 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8635}
8636
8637/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
8638/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
8639fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
8640 let l = ceil_log2(n as u32);
8641 let m = (1usize << l) - n;
8642 let v = dec.literal(l - 1) as usize;
8643 if v < m {
8644 v
8645 } else {
8646 (v << 1) - m + dec.literal(1) as usize
8647 }
8648}
8649
8650/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
8651/// colours (already-known, from the above/left neighbours) with the
8652/// ascending `transmitted` ones (delta-coded off the wire) back into one
8653/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
8654/// value picks the cached copy first, matching the C `<=`.
8655fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
8656 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
8657 let (mut ci, mut ti) = (0, 0);
8658 while ci < cached.len() && ti < transmitted.len() {
8659 if cached[ci] <= transmitted[ti] {
8660 out.push(cached[ci]);
8661 ci += 1;
8662 } else {
8663 out.push(transmitted[ti]);
8664 ti += 1;
8665 }
8666 }
8667 out.extend_from_slice(&cached[ci..]);
8668 out.extend_from_slice(&transmitted[ti..]);
8669 out
8670}
8671
8672/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
8673/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
8674/// each delta's width, the `range` bound and the clamp) is sized by
8675/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
8676/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
8677/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
8678/// the msac range, so a cross-decoder range ladder stays bit-identical
8679/// through the whole miscount -- only the decoded VALUE differs (class
8680/// `compare-range-not-tell`'s blind spot). (this
8681/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
8682/// (one flag bit each, in cache order), then delta-codes the remainder
8683/// (first value raw, each following delta `>= 1` off a shrinking bit width),
8684/// and merges the two ascending lists back together.
8685fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
8686 let mut cached = Vec::with_capacity(n);
8687 for &c in cache {
8688 if cached.len() >= n {
8689 break;
8690 }
8691 if dec.literal(1) == 1 {
8692 cached.push(c);
8693 }
8694 }
8695 let bd = u32::from(bit_depth(fctx));
8696 let max_val = (1i32 << bd) - 1;
8697 let mut colors = [0u16; 8];
8698 let n_cached = cached.len();
8699 if n_cached < n {
8700 let mut transmitted = Vec::with_capacity(n - n_cached);
8701 let first = dec.literal(bd) as u16;
8702 transmitted.push(first);
8703 if n_cached + 1 < n {
8704 let min_bits = bd - 3;
8705 let mut bits = min_bits + dec.literal(2);
8706 let mut range = (1i32 << bd) - i32::from(first) - 1;
8707 for _ in (n_cached + 1)..n {
8708 let delta = dec.literal(bits) as i32 + 1;
8709 let prev = *transmitted.last().unwrap();
8710 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
8711 range -= i32::from(val) - i32::from(prev);
8712 bits = bits.min(ceil_log2(range.max(0) as u32));
8713 transmitted.push(val);
8714 }
8715 }
8716 let merged = merge_colors(&transmitted, &cached);
8717 colors[..n].copy_from_slice(&merged);
8718 } else {
8719 colors[..n].copy_from_slice(&cached[..n]);
8720 }
8721 colors
8722}
8723
8724/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
8725/// `bit_depth` (see [`read_palette_colors_y`]): U reads
8726/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
8727/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
8728/// unbiased by `+1` -- both differences from Y's own reader, matching the C
8729/// side by side). V never uses a cache: a leading bit picks either `n` raw
8730/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
8731/// rather than clamp.
8732fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
8733 let mut cached = Vec::with_capacity(n);
8734 for &c in cache {
8735 if cached.len() >= n {
8736 break;
8737 }
8738 if dec.literal(1) == 1 {
8739 cached.push(c);
8740 }
8741 }
8742 let bd = u32::from(bit_depth(fctx));
8743 let max_val = 1i32 << bd;
8744 let mut u_colors = [0u16; 8];
8745 let n_cached = cached.len();
8746 if n_cached < n {
8747 let mut transmitted = Vec::with_capacity(n - n_cached);
8748 let first = dec.literal(bd) as u16;
8749 transmitted.push(first);
8750 if n_cached + 1 < n {
8751 let min_bits = bd - 3;
8752 let mut bits = min_bits + dec.literal(2);
8753 let mut range = max_val - i32::from(first);
8754 for _ in (n_cached + 1)..n {
8755 let delta = dec.literal(bits) as i32;
8756 let prev = *transmitted.last().unwrap();
8757 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
8758 range -= i32::from(val) - i32::from(prev);
8759 bits = bits.min(ceil_log2(range.max(0) as u32));
8760 transmitted.push(val);
8761 }
8762 }
8763 let merged = merge_colors(&transmitted, &cached);
8764 u_colors[..n].copy_from_slice(&merged);
8765 } else {
8766 u_colors[..n].copy_from_slice(&cached[..n]);
8767 }
8768 let mut v_colors = [0u16; 8];
8769 if dec.literal(1) == 1 {
8770 let min_bits_v = bd - 4;
8771 let bits = min_bits_v + dec.literal(2);
8772 v_colors[0] = dec.literal(bd) as u16;
8773 for i in 1..n {
8774 let mut delta = dec.literal(bits) as i32;
8775 if delta != 0 && dec.literal(1) == 1 {
8776 delta = -delta;
8777 }
8778 let mut val = i32::from(v_colors[i - 1]) + delta;
8779 if val < 0 {
8780 val += max_val;
8781 }
8782 if val >= max_val {
8783 val -= max_val;
8784 }
8785 v_colors[i] = val as u16;
8786 }
8787 } else {
8788 for i in 0..n {
8789 v_colors[i] = dec.literal(bd) as u16;
8790 }
8791 }
8792 (u_colors, v_colors)
8793}
8794
8795/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
8796/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
8797/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
8798const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
8799
8800/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
8801/// map's own per-pixel context and colour-order permutation, from the
8802/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
8803/// selection sort). `map`'s stride is `side` (this decoder never crops a
8804/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
8805/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
8806/// actual colour index to store.
8807pub(crate) fn palette_color_index_context(
8808 map: &[u8],
8809 side: usize,
8810 row: usize,
8811 col: usize,
8812 n: usize,
8813) -> (usize, [u8; 8]) {
8814 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
8815 let up_left = if col >= 1 && row >= 1 {
8816 Some(map[(row - 1) * side + col - 1])
8817 } else {
8818 None
8819 };
8820 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
8821 let mut scores = [0i32; 8];
8822 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
8823 if let Some(v) = neighbour {
8824 scores[v as usize] += weight;
8825 }
8826 }
8827 let mut color_order = [0u8; 8];
8828 for i in 0..8 {
8829 color_order[i] = i as u8;
8830 }
8831 for i in 0..3 {
8832 let mut max = scores[i];
8833 let mut max_idx = i;
8834 for j in (i + 1)..n {
8835 if scores[j] > max {
8836 max = scores[j];
8837 max_idx = j;
8838 }
8839 }
8840 if max_idx != i {
8841 let max_score = scores[max_idx];
8842 let max_color = color_order[max_idx];
8843 for k in (i + 1..=max_idx).rev() {
8844 scores[k] = scores[k - 1];
8845 color_order[k] = color_order[k - 1];
8846 }
8847 scores[i] = max_score;
8848 color_order[i] = max_color;
8849 }
8850 }
8851 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
8852 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
8853 (ctx as usize, color_order)
8854}
8855
8856/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
8857/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
8858/// cut by the frame's bottom or right mi edge codes its colour-index map only
8859/// over this part and replicates it outward -- reading the full `bw x bh` grid
8860/// consumed symbols libaom never wrote and desynced the rest of the tile
8861/// (lane-svtinter; class map-read-past-frame-edge).
8862fn palette_onscreen(
8863 mi_r: usize,
8864 mi_c: usize,
8865 bw: usize,
8866 bh: usize,
8867 fctx: &crate::decode::FrameCtx,
8868) -> (usize, usize) {
8869 // lane-palw: the ENCODER's own in-process reconstruct runs on a
8870 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
8871 // frame encoders publish the header's mi dims onto it themselves
8872 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
8873 // clamp and `tile::write_color_index_map`'s now agree there too.
8874 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
8875 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
8876}
8877
8878/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
8879/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
8880/// compute the same on-screen extent or the decoder reads a different number
8881/// of symbols than the encoder wrote.
8882pub(crate) fn palette_onscreen_dims(
8883 mi_r: usize,
8884 mi_c: usize,
8885 bw: usize,
8886 bh: usize,
8887 (mi_rows, mi_cols): (usize, usize),
8888) -> (usize, usize) {
8889 (
8890 bw.min(mi_cols.saturating_sub(mi_c) * MI),
8891 bh.min(mi_rows.saturating_sub(mi_r) * MI),
8892 )
8893}
8894
8895/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
8896/// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block
8897/// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together
8898/// or a cut 8-wide block reads its chroma map at the wrong width.
8899pub(crate) fn palette_onscreen_uv(
8900 luma: (usize, usize),
8901 on: (usize, usize),
8902 chroma: (usize, usize),
8903) -> (usize, usize) {
8904 (
8905 (on.0 >> 1) + (chroma.0 - (luma.0 >> 1)),
8906 (on.1 >> 1) + (chroma.1 - (luma.1 >> 1)),
8907 )
8908}
8909
8910/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
8911/// map's wavefront decode over a `side x side` grid, read over the on-screen
8912/// `on_side x on_side` corner (see [`palette_onscreen`]).
8913fn decode_color_index_map(
8914 dec: &mut SymbolDecoder,
8915 cdfs: &mut Cdfs,
8916 n: usize,
8917 side: usize,
8918 on: (usize, usize),
8919 uv: bool,
8920) -> Vec<u8> {
8921 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
8922}
8923
8924/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
8925/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
8926/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
8927/// independently rather than one shared `side` -- the square call above is
8928/// just `bw == bh`.
8929fn decode_color_index_map_wh(
8930 dec: &mut SymbolDecoder,
8931 cdfs: &mut Cdfs,
8932 n: usize,
8933 bw: usize,
8934 bh: usize,
8935 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
8936 on: (usize, usize),
8937 uv: bool,
8938) -> Vec<u8> {
8939 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8940 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
8941 if on_bw < bw || on_bh < bh {
8942 hit!(PALETTE_ONSCREEN_CUT_HITS);
8943 }
8944 let mut map = vec![0u8; bw * bh];
8945 if trace {
8946 let (rng, _) = dec.debug_state();
8947 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
8948 }
8949 map[0] = read_uniform(dec, n) as u8;
8950 if trace {
8951 let (rng, _) = dec.debug_state();
8952 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
8953 }
8954 for i in 1..(on_bw + on_bh - 1) {
8955 let j_hi = i.min(on_bw - 1);
8956 let j_lo = i.saturating_sub(on_bh - 1);
8957 for j in (j_lo..=j_hi).rev() {
8958 let row = i - j;
8959 let col = j;
8960 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
8961 if trace {
8962 let (rng, _) = dec.debug_state();
8963 let row_cdf = if uv {
8964 &cdfs.palette_uv_color_index[n - 2][ctx]
8965 } else {
8966 &cdfs.palette_y_color_index[n - 2][ctx]
8967 };
8968 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
8969 }
8970 let symbol = if uv {
8971 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
8972 } else {
8973 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
8974 };
8975 map[row * bw + col] = color_order[symbol];
8976 if trace {
8977 let (rng, _) = dec.debug_state();
8978 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
8979 }
8980 }
8981 }
8982 palette_replicate(&mut map, bw, bh, on);
8983 map
8984}
8985
8986/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
8987/// last on-screen column then the last on-screen row are replicated over the
8988/// off-screen remainder, so the prediction still covers the whole block. The
8989/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
8990/// so the pixels it prices and reconstructs are the ones the on-screen
8991/// symbols it writes really decode to.
8992pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
8993 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
8994 for row in 0..on_bh {
8995 let last = map[row * bw + on_bw - 1];
8996 map[row * bw + on_bw..row * bw + bw].fill(last);
8997 }
8998 for row in on_bh..bh {
8999 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
9000 }
9001}
9002
9003/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
9004/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
9005/// size class comes from [`filter_intra_size_class_rect`] instead of the
9006/// square-only [`filter_intra_size_class`], and the palette read (when
9007/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
9008/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
9009/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
9010/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
9011#[allow(clippy::too_many_arguments)]
9012fn read_intra_mode_rect(
9013 dec: &mut SymbolDecoder,
9014 cdfs: &mut Cdfs,
9015 above_mode: usize,
9016 left_mode: usize,
9017 cfl: bool,
9018 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
9019 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
9020 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
9021 // chroma is coded once, on the closing strip). Every other caller is a
9022 // block big enough to own its chroma and passes `true`.
9023 has_chroma: bool,
9024 bw: usize,
9025 bh: usize,
9026 enable_filter_intra: bool,
9027 skip_ctx: usize,
9028 allow_screen_content_tools: bool,
9029 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
9030 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
9031 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
9032 palette: Option<(usize, &[u16])>,
9033 palette_uv_cache: &[u16],
9034 mi_r: usize,
9035 mi_c: usize, fctx: &crate::decode::FrameCtx,
9036) -> Result<(
9037 bool,
9038 usize,
9039 i32,
9040 usize,
9041 i32,
9042 Option<(i32, i32)>,
9043 Option<usize>,
9044 Option<PaletteY>,
9045 Option<PaletteUv>,
9046)> {
9047 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
9048 if ec_istep {
9049 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
9050 // (decodemv.c:818), printed at the same point: before the first
9051 // mode-info symbol of the block, so a cross-decoder range ladder can
9052 // be keyed on the BLOCK, not just on the symbol sequence.
9053 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);
9054 }
9055 macro_rules! istep {
9056 ($name:literal, $val:expr) => {
9057 if ec_istep {
9058 let (rng, _) = dec.debug_state();
9059 eprintln!(
9060 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
9061 $name, $val
9062 );
9063 }
9064 };
9065 }
9066 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
9067 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
9068 // the one point every rect caller routes through, so no call site can
9069 // offer the 14-symbol CFL alphabet on a 64-axis block (class
9070 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
9071 let cfl = if cfl && bw.max(bh) > 32 {
9072 hit!(NOCFL_UV_MODE_HITS);
9073 false
9074 } else {
9075 cfl
9076 };
9077 // lane-intra14 r1: on the INTER block path everything up to and including
9078 // `is_inter` was already read by [`decode_inter_block`], so this reader
9079 // starts at the mode syntax with the `skip` that caller read.
9080 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
9081 let skip = if let Some((_, skip)) = inter {
9082 skip
9083 } else {
9084 // Same `intra_segment_id` placement as the square reader above.
9085 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
9086 if seg_id_pre_skip(fctx) {
9087 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
9088 }
9089 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9090 istep!("skip", skip as i32);
9091 if !seg_id_pre_skip(fctx) {
9092 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
9093 }
9094 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
9095 istep!("cdef", 0);
9096 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
9097 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
9098 // `false`.
9099 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9100 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9101 istep!("dq", 0);
9102 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
9103 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
9104 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
9105 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
9106 // rect strips read it exactly like square leaves ([`read_intra_mode`],
9107 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
9108 // decoder at the FIRST symbol of the first rect block of every
9109 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
9110 // block at this shape is out of scope, so the flag is consumed and
9111 // refused by name when it fires.
9112 if allow_intrabc_frame(fctx) {
9113 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9114 hit!(RECT_INTRABC_READS);
9115 istep!("intrabc", use_intrabc as i32);
9116 if use_intrabc {
9117 hit!(INTRABC_HITS);
9118 return Err(unsupported(
9119 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
9120 ));
9121 }
9122 }
9123 skip
9124 };
9125 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
9126 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
9127 // off `kf_y_mode_cdf[above][left]`).
9128 let mode = if let Some((size_group, _)) = inter {
9129 dec.symbol(&mut cdfs.y_mode[size_group])
9130 } else {
9131 let above_ctx = INTRA_MODE_CTX[above_mode];
9132 let left_ctx = INTRA_MODE_CTX[left_mode];
9133 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
9134 };
9135 istep!("mode", mode as i32);
9136 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
9137 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
9138 } else {
9139 0
9140 };
9141 istep!("angle_y", angle_delta_y);
9142 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
9143 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
9144 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
9145 // here, from the block's own size, is the single point every caller routes
9146 // through -- a caller passing `true` for a >32 strip used to pick the
9147 // 14-symbol CFL CDF, same value but a different range (class
9148 // wrong-alphabet-same-value).
9149 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
9150 let uv_mode = if !has_chroma {
9151 DC_PRED
9152 } else if cfl {
9153 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9154 } else {
9155 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9156 };
9157 istep!("uv_mode", uv_mode as i32);
9158 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
9159 Some(read_cfl_alphas(dec, cdfs))
9160 } else {
9161 None
9162 };
9163 if has_chroma && (9..=12).contains(&uv_mode) {
9164 hit!(SMOOTH_UV_HITS);
9165 }
9166 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
9167 hit!(DIRECTIONAL_UV_HITS);
9168 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9169 } else {
9170 0
9171 };
9172 istep!("angle_uv", angle_delta_uv);
9173 if angle_delta_uv != 0 {
9174 hit!(UV_ANGLE_DELTA_HITS);
9175 }
9176 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
9177 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
9178 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
9179 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
9180 // colours only here, the colour-index maps deferred past `filter_intra`
9181 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
9182 // runs from the caller, after the whole mode-info read).
9183 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9184 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9185 if allow_screen_content_tools
9186 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
9187 {
9188 // r6: this is the exact site the removed blanket refusal used to
9189 // guard -- reached for EVERY rect strip in a screen-content frame,
9190 // independent of whether the block ends up using a palette.
9191 hit!(RECT_SCREEN_CONTENT_HITS);
9192 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
9193 let use_palette_y =
9194 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
9195 if use_palette_y {
9196 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9197 let colors = read_palette_colors_y(dec, n, cache, fctx);
9198 palette_y_pending = Some((n, colors));
9199 }
9200 let palette_uv_mode_ctx = usize::from(use_palette_y);
9201 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
9202 if has_chroma
9203 && uv_mode == DC_PRED
9204 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
9205 {
9206 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9207 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
9208 palette_uv_pending = Some((n, u_colors, v_colors));
9209 }
9210 }
9211 let mut filter_intra = None;
9212 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9213 let (rng, _) = dec.debug_state();
9214 eprintln!(
9215 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
9216 class={:?} rng={rng}",
9217 enable_filter_intra as i32,
9218 filter_intra_size_class_rect(bw, bh)
9219 );
9220 }
9221 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
9222 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
9223 if mode == DC_PRED
9224 && enable_filter_intra
9225 && palette_y_pending.is_none()
9226 && let Some(class) = filter_intra_size_class_rect(bw, bh)
9227 {
9228 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
9229 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9230 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
9231 }
9232 istep!("use_filter_intra", use_filter_intra as i32);
9233 if use_filter_intra {
9234 hit!(FILTER_INTRA_HITS);
9235 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9236 istep!("filter_intra_mode", fi_mode as i32);
9237 filter_intra = Some(fi_mode);
9238 }
9239 }
9240 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
9241 // same order as [`read_intra_mode`]'s own square path.
9242 let palette_y = palette_y_pending.map(|(n, colors)| {
9243 let map =
9244 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
9245 hit!(PALETTE_HITS);
9246 hit!(PALETTE_RECT_HITS);
9247 PaletteY { size: n, colors, map }
9248 });
9249 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9250 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
9251 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
9252 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
9253 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
9254 // chroma palette and desynced the tile from there.
9255 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
9256 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch));
9257 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
9258 hit!(PALETTE_UV_HITS);
9259 PaletteUv { size: n, u_colors, v_colors, map }
9260 });
9261 Ok((
9262 skip,
9263 mode,
9264 angle_delta_y,
9265 uv_mode,
9266 angle_delta_uv,
9267 alpha,
9268 filter_intra,
9269 palette_y,
9270 palette_uv,
9271 ))
9272}
9273
9274/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
9275/// at the strip's REAL mi position. `av1_get_palette_cache` reads
9276/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
9277/// block, so each strip owns its own rows and columns and no aliasing rule
9278/// is needed (lane-kf900 r6).
9279#[allow(clippy::too_many_arguments)]
9280fn record_strip_palette(
9281 n: &mut Neighbours,
9282 mi: (usize, usize),
9283 bw: usize,
9284 bh: usize,
9285 y_size: usize,
9286 y_colors: [u16; 8],
9287 uv_size: usize,
9288 uv_colors: [u16; 8],
9289) {
9290 let (r, c) = mi;
9291 // lane-t900 r23 rung: every publication of a block's palette state into
9292 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
9293 // path left a stale `left_palette_size` behind when
9294 // `av1_get_palette_mode_ctx` disagrees with libaom's.
9295 if crate::envflags::env_flag!("EC_PALPUB") {
9296 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
9297 }
9298 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
9299 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
9300 // existed because the 16px [`SUB`] cell held one slot for all the strips
9301 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
9302 // real neighbour leaf 1 reads.
9303 {
9304 for cell in 0..(bw / MI).max(1) {
9305 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
9306 *e = y_size as u8;
9307 n.above_palette_uv_size[c + cell] = uv_size as u8;
9308 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
9309 // colours of a size-0 neighbour are never read.
9310 if y_size > 0 {
9311 n.above_palette_colors[c + cell] = y_colors;
9312 }
9313 if uv_size > 0 {
9314 n.above_palette_uv_colors[c + cell] = uv_colors;
9315 }
9316 }
9317 }
9318 }
9319 {
9320 for cell in 0..(bh / MI).max(1) {
9321 if n.left_palette_size.get(r + cell).is_none() {
9322 break;
9323 }
9324 n.left_palette_size[r + cell] = y_size as u8;
9325 n.left_palette_uv_size[r + cell] = uv_size as u8;
9326 if y_size > 0 {
9327 n.left_palette_colors[r + cell] = y_colors;
9328 }
9329 if uv_size > 0 {
9330 n.left_palette_uv_colors[r + cell] = uv_colors;
9331 }
9332 }
9333 }
9334}
9335
9336/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
9337/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
9338/// above against this block's own *width* and the neighbour to the left
9339/// against its own *height* -- for a square block those are the same value,
9340/// which is why the square-only version can get away with one `own_side`.
9341fn tx_size_context_rect(
9342 n: &Neighbours,
9343 (mi_r, mi_c): (usize, usize),
9344 own_w: usize,
9345 own_h: usize,
9346) -> usize {
9347 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
9348 // not the block's own side: no transform is wider or taller than 64, so a
9349 // block with a 128 side resolves against 64 (the square path already caps
9350 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
9351 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
9352 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
9353 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
9354 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
9355 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9356 eprintln!(
9357 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
9358 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
9359 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
9360 usize::from(above) + usize::from(left)
9361 );
9362 }
9363 usize::from(above) + usize::from(left)
9364}
9365
9366/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9367fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9368 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9369}
9370
9371/// Everything a rect strip already read out of the stream before its luma
9372/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9373/// (nine values that would otherwise be nine more parameters).
9374struct RectStripModes {
9375 skip: bool,
9376 mode: usize,
9377 angle_delta_y: i32,
9378 uv_predict_mode: usize,
9379 angle_delta_uv: i32,
9380 alpha: Option<(i32, i32)>,
9381 filter_intra: Option<usize>,
9382 smooth_neighbor: bool,
9383 smooth_neighbor_uv: bool,
9384 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9385 /// mapped through the colour table), sliced per transform unit below --
9386 /// palette prediction reads no edge pixels, so a unit's slice of the
9387 /// whole-block map IS its prediction. Without this a palette strip whose
9388 /// transform splits predicted DC and came out flat grey while the entropy
9389 /// stream stayed in sync (the coefficients are read either way).
9390 palette_y: Option<Vec<u16>>,
9391 /// As `palette_y`, for the un-split chroma transform (U, V).
9392 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9393}
9394
9395/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9396/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9397/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9398/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9399/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9400/// TX_32X16`) and only the second reaches a square -- the reason
9401/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9402/// already square) mis-tiled 1:4 strips.
9403fn depth_to_tx_wh(
9404 bw: usize,
9405 bh: usize,
9406 depth: usize,
9407 fctx: &crate::decode::FrameCtx,
9408) -> (usize, usize) {
9409 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
9410 // `read_tx_size`: the lossless early return comes before
9411 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
9412 if lossless(fctx) {
9413 return (4, 4);
9414 }
9415 let (mut w, mut h) = (bw.min(64), bh.min(64));
9416 for _ in 0..depth {
9417 match w.cmp(&h) {
9418 std::cmp::Ordering::Greater => w /= 2,
9419 std::cmp::Ordering::Less => h /= 2,
9420 std::cmp::Ordering::Equal => {
9421 w /= 2;
9422 h /= 2;
9423 }
9424 }
9425 }
9426 (w, h)
9427}
9428
9429/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9430/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9431/// rect path here refused by name until now ("per-unit rect prediction is not
9432/// ported").
9433///
9434/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9435/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9436/// strip the very first step already lands on a SQUARE transform
9437/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9438/// every further step halves a square) -- so each unit is square and reads
9439/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9440/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9441/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9442/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9443/// split by luma's depth.
9444///
9445/// Each unit predicts off whatever the earlier units of this same block
9446/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9447/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9448/// what predicting the whole strip in one shot got wrong.
9449#[allow(clippy::too_many_arguments)]
9450fn decode_rect_split(
9451 dec: &mut SymbolDecoder,
9452 cdfs: &mut Cdfs,
9453 neighbours: &mut Neighbours,
9454 at_mi: (usize, usize),
9455 bw: usize,
9456 bh: usize,
9457 // The transform unit's own width and height in pixels. Square for every
9458 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9459 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9460 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9461 tx_w: usize,
9462 tx_h: usize,
9463 m: &RectStripModes,
9464 y: &mut PlaneBuf<'static>,
9465 u: &mut PlaneBuf<'static>,
9466 v: &mut PlaneBuf<'static>,
9467 base_q_idx: u8,
9468 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9469) -> Result<()> {
9470 let (mi_r, mi_c) = at_mi;
9471 let (px, py) = (mi_c * MI, mi_r * MI);
9472 let (cpx, cpy) = (px / 2, py / 2);
9473 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9474 // The chroma transform is picked before any symbol is read, so an
9475 // unsupported chroma shape refuses before this strip desyncs the tile.
9476 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9477 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9478 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9479 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9480 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9481 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9482 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9483 // squares a rect transform down to a CDF set by
9484 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9485 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9486 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9487 // paths already prove for these same shapes.
9488 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9489 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9490 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9491 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9492 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9493 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9494 _ => None,
9495 };
9496 if !m.skip {
9497 if let Some(i) = match (chroma_w, chroma_h) {
9498 (32, 8) => Some(0),
9499 (8, 32) => Some(1),
9500 (8, 4) => Some(2),
9501 (4, 8) => Some(3),
9502 _ => None,
9503 } {
9504 hit_do! {
9505 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9506 let mut hits = c.get();
9507 hits[i] += 1;
9508 c.set(hits);
9509 });
9510 }
9511 }
9512 if chroma.is_none() {
9513 // Diagnostic for the next caller that lands here (class
9514 // refusal-names-a-correlate: the message names the tool, not the
9515 // shape); the refusal below keeps its inventory-pinned wording.
9516 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9517 }
9518 }
9519 // lane-rectsplit r2 (verifier finding): with both callers wired
9520 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9521 // 64x32/32x64) every shape that reaches here has a table above, so this
9522 // arm is UNREACHABLE today. It stays as the shape guard for the next
9523 // caller -- a new strip size would otherwise hit the `expect` below and
9524 // panic instead of refusing by name -- and so stays in
9525 // `refusal_inventory::REFUSALS`.
9526 if !m.skip && chroma.is_none() {
9527 return Err(unsupported(
9528 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9529 ));
9530 }
9531 hit!(RECT_SPLIT_TX_HITS);
9532 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9533 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9534 }
9535 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9536 // A square unit reads through the ordinary square [`read_plane`]; a rect
9537 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9538 // the very tables the unsplit 16x8/32x16 paths use.
9539 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9540 (w, h) if w == h => None,
9541 (16, 8) | (8, 16) => Some((
9542 if reduced_tx_set {
9543 TxbSet::LumaRect16x8
9544 } else {
9545 TxbSet::LumaRect16x8Set1
9546 },
9547 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9548 )),
9549 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9550 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9551 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9552 // strip, read through the `luma_64corner` arm below instead of a rect
9553 // table -- a 64-length axis codes only its low 32 coefficients
9554 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9555 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9556 // depth-0 arm already reads on the key-frame path.
9557 //
9558 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9559 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9560 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9561 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9562 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9563 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9564 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9565 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9566 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9567 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9568 (64, 32) | (32, 64) => None,
9569 _ => {
9570 return Err(unsupported(format!(
9571 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9572 coefficient tables for that shape here)"
9573 )))
9574 }
9575 };
9576 // The `None` above that is NOT the square arm.
9577 let luma_64corner = tx_w != tx_h;
9578 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9579 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9580 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9581 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9582 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9583 // per-unit rect walk stay wired above/below; the round that finds that
9584 // defect deletes this refusal and nothing else.
9585 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9586 let luma_scan = default_scan(tx_w.min(tx_h));
9587 let zero_tu = vec![0i32; tx_w * tx_h];
9588 // The strip's OWN edge availability, the fallback for a transform unit
9589 // whose top-right/bottom-left pixels fall outside the strip.
9590 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9591 for tu_row in 0..bh / tx_h {
9592 for tu_col in 0..bw / tx_w {
9593 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9594 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9595 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9596 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9597 // libaom clips `av1_foreach_transformed_block_in_plane` to
9598 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9599 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9600 // TOP-LEFT sample falls outside the frame is never coded. We read
9601 // coefficients for those phantom units and desynced the stream at
9602 // the very next symbol.
9603 if tu_px >= y.true_width || tu_py >= y.true_height {
9604 continue;
9605 }
9606 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9607 // transform unit INSIDE a block, which is a different rule from
9608 // the standalone-block table [`Reach::of`] applies -- and the
9609 // reason a depth-2 superblock strip came out one sample off
9610 // before this: `Reach::of(tx, ..)` answered as if the unit were
9611 // its own block at that superblock position.
9612 // * top-right: if the unit's right neighbour is still inside the
9613 // strip the pixels are already reconstructed (`col_off +
9614 // tx_wide < plane_bw`); otherwise only the strip's own top row
9615 // of units can reach past it, through the block-level answer.
9616 // * bottom-left: a unit that is not in the strip's left column
9617 // has none (`col_off > 0` returns 0); inside the strip
9618 // (`row_off + tx_high < plane_bh`) they are the left
9619 // neighbour's, already reconstructed; the last row falls back
9620 // to the block-level answer.
9621 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9622 // The unit's own window on the block's palette prediction.
9623 if let Some(buf) = &m.palette_y {
9624 let tu_buf: Vec<u16> = (0..tx_h)
9625 .flat_map(|i| {
9626 let base = (row_off + i) * bw + col_off;
9627 buf[base..base + tx_w].iter().copied()
9628 })
9629 .collect();
9630 set_palette_pred(tu_buf, fctx);
9631 }
9632 if m.skip {
9633 push_intra_rect(0,
9634 tu_px,
9635 tu_py,
9636 tx_w,
9637 tx_h,
9638 m.mode,
9639 m.angle_delta_y,
9640 tu_reach,
9641 &zero_tu,
9642 None,
9643 m.filter_intra,
9644 m.smooth_neighbor, fctx,
9645 );
9646 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9647 } else if luma_64corner && luma_rect.is_none() {
9648 // The un-split 64-level luma transform: `read_coeffs` on the
9649 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9650 // and the real rect shape passed through for
9651 // `av1_nz_map_ctx_offset` -- byte for byte
9652 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9653 // 64-level strip gate already proves. `tx_type` is not coded
9654 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9655 // the square-up size is TX_64X64), and this unit covers its
9656 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9657 if crate::envflags::env_flag!("EC_RECT64TU") {
9658 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9659 }
9660 hit_do! {
9661 RECT64_CORNER_TU_HITS.with(|c| {
9662 let mut v = c.get();
9663 v[usize::from(tx_h > tx_w)] += 1;
9664 c.set(v);
9665 });
9666 }
9667 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9668 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
9669 let (corner, tu_tx_type) = read_coeffs(
9670 dec,
9671 &mut coding,
9672 default_scan(TX32),
9673 0,
9674 dc_sign_ctx(tu_around.2),
9675 TxType::DctDct,
9676 Some((tx_w, tx_h)),
9677 )?;
9678 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
9679 let mut tu_grid = vec![0i32; tx_w * tx_h];
9680 for row in 0..ch {
9681 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
9682 }
9683 let residual = dequant_and_inverse_typed_wh(
9684 &tu_grid,
9685 tx_w,
9686 tx_h,
9687 crate::decode::bit_depth(fctx),
9688 block_q_idx(fctx),
9689 plane_q_delta(0, fctx).0,
9690 plane_q_delta(0, fctx).1,
9691 tu_tx_type,
9692 );
9693 push_intra_rect(0,
9694 tu_px,
9695 tu_py,
9696 tx_w,
9697 tx_h,
9698 m.mode,
9699 m.angle_delta_y,
9700 tu_reach,
9701 &residual,
9702 None,
9703 m.filter_intra,
9704 m.smooth_neighbor, fctx,
9705 );
9706 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9707 } else if let Some((rect_set, rect_scan)) = luma_rect {
9708 // The rect-unit twin of the square arm below: same contexts,
9709 // same order, through the rect coefficient reader. The
9710 // `tx_type` CDF row of a filter-intra block is
9711 // `fimode_to_intradir[filter_intra_mode]`, never the block's
9712 // own (always DC_PRED) mode -- [`read_plane`] applies that
9713 // for the square arm, so this one must too.
9714 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9715 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
9716 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
9717 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
9718 // neighbour-magnitude table is for a unit SMALLER than its
9719 // block. [`decode_block_rect`]'s own unsplit read passes a
9720 // literal 0 for the same reason; this arm applied the table
9721 // unconditionally and desynced every depth-0 rect strip that
9722 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
9723 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
9724 0
9725 } else {
9726 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
9727 };
9728 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
9729 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9730 dec,
9731 &mut coding,
9732 rect_scan,
9733 tx_w,
9734 tx_h,
9735 tu_skip_ctx,
9736 dc_sign_ctx(tu_around.2),
9737 TxType::DctDct,
9738 )?;
9739 let residual = dequant_and_inverse_typed_wh(
9740 &tu_grid,
9741 tx_w,
9742 tx_h,
9743 crate::decode::bit_depth(fctx),
9744 block_q_idx(fctx),
9745 plane_q_delta(0, fctx).0,
9746 plane_q_delta(0, fctx).1,
9747 tu_tx_type,
9748 );
9749 push_intra_rect(0,
9750 tu_px,
9751 tu_py,
9752 tx_w,
9753 tx_h,
9754 m.mode,
9755 m.angle_delta_y,
9756 tu_reach,
9757 &residual,
9758 None,
9759 m.filter_intra,
9760 m.smooth_neighbor, fctx,
9761 );
9762 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9763 } else {
9764 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9765 // This unit is smaller than the block it sits in, so
9766 // `txb_skip_ctx` is the neighbour-magnitude table, not the
9767 // lone-TU 0 (spec `get_txb_ctx_general`).
9768 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9769 let tu_grid = read_plane(
9770 dec,
9771 cdfs,
9772 luma_set,
9773 &luma_scan,
9774 0,
9775 tu_around,
9776 m.mode,
9777 m.mode,
9778 m.angle_delta_y,
9779 tu_reach,
9780 y,
9781 tu_px,
9782 tu_py,
9783 tx_w,
9784 tx_w,
9785 base_q_idx,
9786 None,
9787 m.filter_intra,
9788 Some(tu_skip_ctx),
9789 m.smooth_neighbor, fctx,
9790 )?;
9791 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9792 }
9793 }
9794 }
9795 // CHROMA: one un-split rect transform for the whole strip.
9796 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
9797 // units -- each stamps its own neighbour context as it is read, and the
9798 // whole-block `record_split_luma_rect_mi` below would overwrite all of
9799 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
9800 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
9801 // collected here and replayed after that record.
9802 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new();
9803 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9804 let reach = block_reach;
9805 let (u_grid, v_grid) = if m.skip {
9806 let zero = Grid::Zero(chroma_w * chroma_h);
9807 if let Some((ub, _)) = &m.palette_uv {
9808 set_palette_pred(ub.clone(), fctx);
9809 }
9810 push_intra_rect(1,
9811 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9812 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
9813 );
9814 if let Some((_, vb)) = &m.palette_uv {
9815 set_palette_pred(vb.clone(), fctx);
9816 }
9817 push_intra_rect(2,
9818 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9819 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
9820 );
9821 (zero.clone(), zero)
9822 } else if lossless(fctx) {
9823 // lane-lossless: the strip's chroma plane block is coded as 4x4
9824 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
9825 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
9826 // (`decode_token_recon_block`'s mu-chunk loop, measured against
9827 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
9828 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
9829 // offset (our `+3` row base) whenever the plane block is bigger than
9830 // the transform.
9831 let scan4 = default_scan(4);
9832 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
9833 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
9834 let mut last = [Grid::Zero(16), Grid::Zero(16)];
9835 for plane_idx in 1..=2 {
9836 for cu_row in 0..ch_n {
9837 for cu_col in 0..cw_n {
9838 let luma_span = 8;
9839 let cu_mi = (
9840 mi_r + cu_row * (luma_span / MI),
9841 mi_c + cu_col * (luma_span / MI),
9842 );
9843 let cu_around = neighbours.around_mi(cu_mi, luma_span);
9844 let cu_reach = tu_reach(
9845 bw, bh,
9846 cu_col * luma_span, cu_row * luma_span, luma_span,
9847 block_reach, px, py, y.width, y.height, fctx,
9848 );
9849 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
9850 if let Some((ub, vb)) = &m.palette_uv {
9851 let pbuf = if plane_idx == 1 { ub } else { vb };
9852 set_palette_pred(
9853 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
9854 fctx,
9855 );
9856 }
9857 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9858 let grid = read_plane(
9859 dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
9860 cu_around[plane_idx], m.mode, m.uv_predict_mode,
9861 m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
9862 base_q_idx,
9863 m.alpha.zip(ac).map(|((au, av), ac)| {
9864 (if plane_idx == 1 { au } else { av }, ac)
9865 }),
9866 None, offset, m.smooth_neighbor_uv, fctx,
9867 )?;
9868 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid);
9869 ll_chroma_units.push((cu_mi, plane_idx, grid.clone()));
9870 last[plane_idx - 1] = grid;
9871 }
9872 }
9873 }
9874 let [ug, vg] = last;
9875 (ug, vg)
9876 } else {
9877 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
9878 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
9879 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
9880 // so only the 16x8/8x16 pair takes the mode-indexed default.
9881 let default_tx = if chroma_w.max(chroma_h) >= 32 {
9882 TxType::DctDct
9883 } else {
9884 default_intra_tx_type(m.uv_predict_mode as u8)
9885 };
9886 let around = neighbours.around_mi_rect(at_mi, bw, bh);
9887 let mut grids: Vec<Grid> = Vec::with_capacity(2);
9888 for plane_idx in 1..=2 {
9889 let skip_ctx =
9890 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
9891 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
9892 let (levels, tx_type) = read_coeffs_rect(
9893 dec,
9894 &mut coding,
9895 chroma_scan,
9896 chroma_w,
9897 chroma_h,
9898 skip_ctx,
9899 dc_sign_ctx(around[plane_idx].2),
9900 default_tx,
9901 )?;
9902 // The same delta_q proof the unsplit rect64 path records
9903 // (lane-rectsplit r4: lifting the split-transform refusal moved
9904 // superblock strips onto this path, so only counting there would
9905 // leave the delta_q gate's counter silent for them).
9906 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
9907 hit!(RECT64_QIDX_DRIFT_HITS);
9908 }
9909 let residual = dequant_and_inverse_typed_wh(
9910 &levels,
9911 chroma_w,
9912 chroma_h,
9913 crate::decode::bit_depth(fctx),
9914 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
9915 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
9916 // reading `current_q_idx` here dropped the segment feature
9917 // that every other dequant site applies (class
9918 // `parsed-then-discarded`).
9919 block_q_idx(fctx),
9920 plane_q_delta(plane_idx, fctx).0,
9921 plane_q_delta(plane_idx, fctx).1,
9922 tx_type,
9923 );
9924 let cfl = m
9925 .alpha
9926 .zip(ac)
9927 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
9928 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9929 if let Some((ub, vb)) = &m.palette_uv {
9930 let buf = if plane_idx == 1 { ub } else { vb };
9931 set_palette_pred(buf.clone(), fctx);
9932 }
9933 push_intra_rect(plane_idx,
9934 cpx,
9935 cpy,
9936 chroma_w,
9937 chroma_h,
9938 m.uv_predict_mode,
9939 m.angle_delta_uv,
9940 reach,
9941 &residual,
9942 cfl,
9943 None,
9944 m.smooth_neighbor_uv, fctx,
9945 );
9946 grids.push(levels);
9947 }
9948 let mut it = grids.into_iter();
9949 (it.next().unwrap(), it.next().unwrap())
9950 };
9951 neighbours.record_split_luma_rect_mi(
9952 at_mi,
9953 bw,
9954 bh,
9955 m.mode,
9956 m.uv_predict_mode,
9957 [&u_grid, &v_grid],
9958 );
9959 for (cu_mi, plane, unit) in &ll_chroma_units {
9960 neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit);
9961 }
9962 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
9963 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
9964 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9965 let (rng, _) = dec.debug_state();
9966 eprintln!(
9967 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
9968 tx={tx_w}x{tx_h} rng={rng}"
9969 );
9970 }
9971 Ok(())
9972}
9973
9974/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
9975/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
9976/// because it predicts squares only. Every pixel here goes through the rect
9977/// machinery the key-frame paths already prove: [`decode_rect_split`], which
9978/// at `depth == 0` is the unsplit strip as a single transform unit and
9979/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9980///
9981/// What is genuinely different from [`decode_block_rect`] is the mode
9982/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9983/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9984/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9985/// intra-in-inter arm's own reads at the rect footprint, including its
9986/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9987/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9988/// square and this arm) and a nonzero luma angle delta refused by name.
9989///
9990/// The strip's own neighbour records (luma per transform unit, chroma, skip
9991/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9992/// inter-side bands and the mi map.
9993#[allow(clippy::too_many_arguments)]
9994/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9995/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9996/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9997/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9998/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9999/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
10000/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
10001/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
10002/// table here rather than a shift of `bw.min(bh)`.
10003fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
10004 Some(match (bw.min(bh), bw.max(bh)) {
10005 (8, 16) => (1usize, 1usize),
10006 (16, 32) => (2, 2),
10007 (32, 64) => (3, 3),
10008 (8, 32) => (1, 2),
10009 (16, 64) => (2, 3),
10010 _ => return None,
10011 })
10012}
10013
10014/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
10015/// block path"): the shapes that can reach that arm, enumerated against the
10016/// MEASURED domain of the inter block path
10017/// ([`INTER_BLOCK_SHAPES`], the census the gate
10018/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
10019/// fills from three real streams).
10020///
10021/// [`decode_intra_rect_in_inter`] is called from one site, under
10022/// `write_w != side || write_h != side`, and only after two earlier arms have
10023/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
10024/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
10025/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
10026/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
10027/// and each of those has a row, so the refusal names a shape no measured
10028/// stream can present.
10029#[test]
10030fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
10031 let mut checked = 0;
10032 for &(side, w, h) in &INTER_BLOCK_SHAPES {
10033 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
10034 continue;
10035 }
10036 assert!(
10037 intra_in_inter_size_row(w, h).is_some(),
10038 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
10039 the \"no size-group/tx-category row\" refusal"
10040 );
10041 checked += 1;
10042 }
10043 assert_eq!(
10044 checked, 10,
10045 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
10046 lookup, not the 10 this claim was measured over"
10047 );
10048}
10049
10050/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
10051/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
10052/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
10053/// matched before the square arm's `log2` shortcut).
10054///
10055/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
10056/// row here"; the enumeration below is what proves no conformant block can
10057/// reach it.
10058pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
10059 Some(match (write_w, write_h) {
10060 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
10061 // below maps 128 to row 4 (BLOCK_16X32).
10062 (64, 128) => 14,
10063 (128, 64) => 15,
10064 (128, 128) => 16,
10065 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
10066 (16, 32) => 4,
10067 (32, 16) => 5,
10068 (32, 64) => 6,
10069 (64, 32) => 7,
10070 (8, 32) => 8,
10071 (32, 8) => 9,
10072 (16, 64) => 10,
10073 (64, 16) => 11,
10074 // lane-inter4 r3: the 16x16-level rect inter leaves.
10075 (8, 16) => 12,
10076 (16, 8) => 13,
10077 _ => return None,
10078 })
10079}
10080
10081/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
10082/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
10083/// `block_size_wide`/`block_size_high`).
10084#[cfg(test)]
10085const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
10086 (4, 4),
10087 (4, 8),
10088 (8, 4),
10089 (8, 8),
10090 (8, 16),
10091 (16, 8),
10092 (16, 16),
10093 (16, 32),
10094 (32, 16),
10095 (32, 32),
10096 (32, 64),
10097 (64, 32),
10098 (64, 64),
10099 (64, 128),
10100 (128, 64),
10101 (128, 128),
10102 (4, 16),
10103 (16, 4),
10104 (8, 32),
10105 (32, 8),
10106 (16, 64),
10107 (64, 16),
10108];
10109
10110/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
10111/// shape with no CDF row here" names a shape no conformant stream can present.
10112///
10113/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
10114/// whose `write_w.min(write_h) >= 8` clause is libaom's
10115/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
10116/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
10117/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
10118/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
10119/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
10120/// clause rejects before the lookup.
10121#[test]
10122fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
10123 let mut rows = std::collections::BTreeSet::new();
10124 let mut excluded = 0;
10125 for (w, h) in BLOCK_SIZES_ALL_WH {
10126 if w.min(h) < 8 {
10127 excluded += 1;
10128 assert!(
10129 w == 4 || h == 4,
10130 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
10131 );
10132 continue;
10133 }
10134 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
10135 panic!(
10136 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
10137 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
10138 )
10139 });
10140 assert!(
10141 row < 17,
10142 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
10143 );
10144 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
10145 }
10146 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
10147 assert_eq!(
10148 rows.len(),
10149 17,
10150 "17 eligible footprints must fill all 17 rows of the motion_mode table"
10151 );
10152}
10153
10154fn decode_intra_rect_in_inter(
10155 dec: &mut SymbolDecoder,
10156 cdfs: &mut Cdfs,
10157 neighbours: &mut Neighbours,
10158 at: (usize, usize),
10159 bw: usize,
10160 bh: usize,
10161 skip: bool,
10162 allow_screen_content_tools: bool,
10163 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
10164 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
10165 strip16: Option<(bool, bool)>,
10166 y: &mut PlaneBuf<'static>,
10167 u: &mut PlaneBuf<'static>,
10168 v: &mut PlaneBuf<'static>,
10169 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
10170) -> Result<()> {
10171 // `at` is in MI units (the inter path's own unit since lane-inter4);
10172 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
10173 // below are still keyed by.
10174 let (mi_r, mi_c) = at;
10175 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10176 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
10177 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
10178 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
10179 // finding -- the category is NOT the same for every strip size).
10180 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
10181 // it is refused by name rather than read from the wrong CDF row.
10182 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
10183 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
10184 // tx-depth category is 1 -- but nothing here has to know either, because
10185 // the strip decodes through the very body the KEY FRAME path proves for
10186 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
10187 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
10188 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
10189 // inter-frame difference is the mode-info read, which
10190 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
10191 // `y_mode[0]` plus the `skip` this caller already read.
10192 if let Some((horz, has_chroma)) = strip16 {
10193 // lane-t900 r22: the screen-content refusal here was STALE (class
10194 // stale-premise): [`decode_rect4_16_strip`] takes
10195 // `allow_screen_content_tools` and reads the whole palette syntax
10196 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
10197 // pair) -- the key frame proves that body. Lifted with the 10-bit
10198 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
10199 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
10200 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
10201 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
10202 let res = decode_rect4_16_strip(
10203 dec,
10204 cdfs,
10205 neighbours,
10206 (mi_r, mi_c),
10207 horz,
10208 has_chroma,
10209 // The inter strips of the same partition publish their own
10210 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
10211 // has nothing to add here.
10212 None,
10213 y,
10214 u,
10215 v,
10216 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10217 allow_screen_content_tools,
10218 base_q_idx,
10219 fctx.tx_select_inter.with(std::cell::Cell::get),
10220 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10221 );
10222 fctx.intra_in_inter_mode.with(|c| c.set(None));
10223 let (mode, uv, (tx_w, tx_h)) = res?;
10224 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
10225 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
10226 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
10227 // block of an inter frame, intra ones included, and
10228 // `txfm_partition_update` for the var-tx context. The key-frame body
10229 // writes neither (a key frame has no var-tx tree and its own readers
10230 // use the deblock grid), so the block AFTER this strip read a stale
10231 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
10232 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
10233 // 16x16 row.
10234 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10235 for i in 0..bw / MI {
10236 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10237 *cell = tx_w as u8;
10238 }
10239 }
10240 for i in 0..bh / MI {
10241 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10242 *cell = tx_h as u8;
10243 }
10244 }
10245 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
10246 // coarse 16-px cell holds one entry for the whole 16x16 and the last
10247 // block to write it wins).
10248 neighbours.above_mode[c] = mode;
10249 neighbours.left_mode[r] = mode;
10250 if let Some(uvm) = uv {
10251 neighbours.above_uv_mode[c] = uvm;
10252 neighbours.left_uv_mode[r] = uvm;
10253 }
10254 neighbours.above_side[c] = bw;
10255 neighbours.left_side[r] = bh;
10256 if crate::envflags::env_flag!("EC_INTRA16X4") {
10257 eprintln!(
10258 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
10259 mi_c * MI,
10260 mi_r * MI
10261 );
10262 }
10263 hit_do! {
10264 INTRA16X4_IN_INTER_HITS.with(|h| {
10265 let mut v = h.get();
10266 v[usize::from(!horz)] += 1;
10267 v[2] += usize::from(has_chroma);
10268 h.set(v);
10269 });
10270 }
10271 return Ok(());
10272 }
10273 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
10274 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
10275 // puts BLOCK_128X64/64X128/128X128 in group 3 and
10276 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
10277 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
10278 // block decodes through the very body the KEY FRAME path proves for this
10279 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
10280 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
10281 // `Reach` rule and the frame-edge write clip). The only inter-frame
10282 // differences live inside that body: the mode-info read
10283 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
10284 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
10285 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
10286 // palette (>64) do not exist at this size and are refused by name there.
10287 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
10288 // `intra128_in_inter_witness2.obu` (gate
10289 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
10290 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
10291 // all 15 frames, so the hits are counted out of exact frames (class
10292 // `counter-from-refused-stream`). What r16/r17 could not find, and what
10293 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
10294 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
10295 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
10296 // where the frame EDGE forces it: a partial last superblock row has
10297 // `has_rows128 == false`, so the 128x64 top half is implied, and a
10298 // partial last column implies the 64x128 left half. Put content no
10299 // reference holds (a fresh smooth ramp) in exactly those two bands of an
10300 // inter frame and the encoder codes those forced halves INTRA.
10301 if bw.max(bh) == 128 {
10302 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
10303 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
10304 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
10305 // palette_syntax`), so a 128-root half consumes no palette syntax and
10306 // a screen-content frame's half is syntactically identical to the
10307 // non-screen one this arm already decodes byte-exact.
10308 if coeff_trace_on() {
10309 // lane-t900 r16: which decode-order frame this arm fires in --
10310 // interleaved with the `EC_COEFF_FRAME` markers, this is what
10311 // proves the hit is counted out of a frame that compares exact
10312 // (class `counter-from-refused-stream`).
10313 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
10314 }
10315 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
10316 let res = decode_block_128rect(
10317 dec,
10318 cdfs,
10319 neighbours,
10320 (r, c),
10321 bw,
10322 bh,
10323 y,
10324 u,
10325 v,
10326 base_q_idx,
10327 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10328 allow_screen_content_tools,
10329 fctx.tx_select_inter.with(std::cell::Cell::get),
10330 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10331 );
10332 fctx.intra_in_inter_mode.with(|c| c.set(None));
10333 return res;
10334 }
10335 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
10336 if crate::envflags::env_flag!("EC_OBMCREC") {
10337 eprintln!(
10338 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
10339 );
10340 }
10341 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
10342 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
10343 // can arrive here are enumerated against the measured block-shape
10344 // census ([`INTER_BLOCK_SHAPES`]) by
10345 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
10346 // -- every one of them has a row, so this arm names a shape no stream
10347 // has been able to present.
10348 return Err(unsupported(format!(
10349 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
10350 )));
10351 };
10352 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
10353 // screen-content frame ("palette syntax is consumed for square blocks
10354 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
10355 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
10356 // it, while the 2:1 reader inlined further down now codes the same syntax
10357 // itself. A real `--tune-content=screen` inter stream reached this refusal
10358 // on 8x16 / 16x8 strips (gate
10359 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
10360 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
10361 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
10362 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
10363 // luma/chroma transform tables, the per-unit split walk and the strip's
10364 // own neighbour records). The ONLY difference on an inter frame is the
10365 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
10366 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
10367 // this caller already read. `tx_cat` above is the same category those
10368 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
10369 // `decode_block_rect64`), asserted here so a future shape cannot drift.
10370 if bw.max(bh) == 4 * bw.min(bh) {
10371 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
10372 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
10373 let res = if bw.max(bh) == 64 {
10374 decode_block_rect64(
10375 dec,
10376 cdfs,
10377 neighbours,
10378 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
10379 bw,
10380 bh,
10381 y,
10382 u,
10383 v,
10384 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10385 allow_screen_content_tools,
10386 base_q_idx,
10387 fctx.tx_select_inter.with(std::cell::Cell::get),
10388 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10389 )
10390 } else {
10391 decode_block_rect4(
10392 dec,
10393 cdfs,
10394 neighbours,
10395 (mi_r, mi_c),
10396 bw,
10397 bh,
10398 None,
10399 y,
10400 u,
10401 v,
10402 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10403 allow_screen_content_tools,
10404 base_q_idx,
10405 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10406 )
10407 .map(|_| ())
10408 };
10409 fctx.intra_in_inter_mode.with(|c| c.set(None));
10410 res?;
10411 let shape = match (bw, bh) {
10412 (64, 16) => 0,
10413 (16, 64) => 1,
10414 (32, 8) => 2,
10415 _ => 3,
10416 };
10417 hit_do! {
10418 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10419 let mut v = h.get();
10420 v[shape] += 1;
10421 h.set(v);
10422 });
10423 }
10424 return Ok(());
10425 }
10426 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10427 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10428 // own, so a cross-decoder bisection could only see the block's first
10429 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10430 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10431 if step_trace {
10432 eprintln!(
10433 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10434 dec.debug_state().0
10435 );
10436 }
10437 if mode >= 13 {
10438 return Err(unsupported(
10439 "an intra mode this decoder does not code (round 2)",
10440 ));
10441 }
10442 // lane-angleinter (merged on main for the square intra-in-inter arm):
10443 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10444 // directional predictor; this arm refused a nonzero one before the merge.
10445 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10446 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10447 } else {
10448 0
10449 };
10450 if angle_delta_y != 0 {
10451 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10452 }
10453 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10454 // superblock-level strip reads the no-CFL alphabet -- the same split
10455 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10456 let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
10457 let uv_mode = if cfl_allowed {
10458 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10459 } else {
10460 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10461 };
10462 if step_trace {
10463 eprintln!(
10464 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10465 u8::from(cfl_allowed),
10466 dec.debug_state().0
10467 );
10468 }
10469 if (9..=12).contains(&uv_mode) {
10470 hit!(SMOOTH_UV_HITS);
10471 }
10472 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10473 Some(read_cfl_alphas(dec, cdfs))
10474 } else {
10475 None
10476 };
10477 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10478 DC_PRED
10479 } else {
10480 uv_mode
10481 };
10482 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10483 hit!(DIRECTIONAL_UV_HITS);
10484 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10485 } else {
10486 0
10487 };
10488 if angle_delta_uv != 0 {
10489 hit!(UV_ANGLE_DELTA_HITS);
10490 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10491 }
10492 // `read_palette_mode_info` (spec 5.11.13), in the position
10493 // `read_intra_block_mode_info` writes it: after the chroma mode and
10494 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10495 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10496 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10497 // skipping the syntax here desynced the tile at the strip's own symbol.
10498 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10499 // context and colour cache at its own mi position, and the two
10500 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10501 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10502 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10503 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10504 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10505 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10506 if allow_screen_content_tools
10507 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10508 {
10509 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10510 let use_palette_y =
10511 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10512 if use_palette_y {
10513 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10514 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10515 }
10516 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10517 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10518 let use_palette_uv =
10519 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10520 if crate::envflags::env_flag!("EC_PALSYN") {
10521 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);
10522 }
10523 if use_palette_uv {
10524 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10525 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10526 palette_uv_pending = Some((n, u_colors, v_colors));
10527 }
10528 }
10529 // lane-fiinter (merged on main for the square intra-in-inter arm):
10530 // `read_filter_intra_mode_info` is the tail of
10531 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10532 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10533 // 2:1 strips with both sides <= 32 -- their own CDF rows
10534 // ([`filter_intra_size_class_rect`]).
10535 let mut filter_intra = None;
10536 if mode == DC_PRED
10537 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10538 // `av1_filter_intra_allowed` excludes a palette-Y block.
10539 && palette_y_pending.is_none()
10540 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10541 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10542 {
10543 hit!(FILTER_INTRA_HITS);
10544 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10545 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10546 }
10547 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10548 let palette_y = palette_y_pending.map(|(n, colors)| {
10549 let map =
10550 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
10551 hit!(PALETTE_HITS);
10552 hit!(PALETTE_RECT_HITS);
10553 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10554 PaletteY { size: n, colors, map }
10555 });
10556 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10557 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10558 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch));
10559 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
10560 hit!(PALETTE_UV_HITS);
10561 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10562 PaletteUv { size: n, u_colors, v_colors, map }
10563 });
10564 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10565 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10566 // chroma ones -- [`decode_block_rect`]'s own pair.
10567 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10568 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10569 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10570 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10571 // one exactly as [`decode_leaf8`] already does (class
10572 // context-read-from-one-cell).
10573 let coarse_pair = neighbours.modes_above_left(r, c);
10574 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10575 if (nb_above_mode, nb_left_mode) != coarse_pair {
10576 hit!(EDGE_FILTER_MI_FIX_HITS);
10577 }
10578 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10579 if smooth_neighbor {
10580 hit!(SMOOTH_LUMA_HITS);
10581 }
10582 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10583 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10584 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
10585 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
10586 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10587 let d = match tx_cat {
10588 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10589 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10590 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10591 };
10592 if step_trace {
10593 eprintln!(
10594 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10595 dec.debug_state().0
10596 );
10597 }
10598 d
10599 } else {
10600 0
10601 };
10602 if depth != 0 || lossless(fctx) {
10603 hit!(TX_DEPTH_HITS);
10604 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10605 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10606 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10607 hit_do! {
10608 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10609 let mut v = h.get();
10610 v[depth.min(2)] += 1;
10611 h.set(v);
10612 });
10613 }
10614 }
10615 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10616 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10617 // the two are indistinguishable when the diagnostic fires on splits alone.
10618 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10619 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10620 }
10621 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10622 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10623 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10624 // of an inter frame, intra ones included -- with the skip term 0 it
10625 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10626 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10627 // wrote neither, so the next block's var-tx `txfm_partition` context read
10628 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10629 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10630 // mi(16,0) and desyncing the tile at that symbol.
10631 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10632 let modes = RectStripModes {
10633 skip,
10634 mode,
10635 angle_delta_y,
10636 uv_predict_mode,
10637 angle_delta_uv,
10638 alpha,
10639 filter_intra,
10640 smooth_neighbor,
10641 smooth_neighbor_uv,
10642 palette_y: palette_y
10643 .as_ref()
10644 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10645 palette_uv: palette_uv.as_ref().map(|p| {
10646 (
10647 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10648 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10649 )
10650 }),
10651 };
10652 decode_rect_split(
10653 dec,
10654 cdfs,
10655 neighbours,
10656 (mi_r, mi_c),
10657 bw,
10658 bh,
10659 tx_w,
10660 tx_h,
10661 &modes,
10662 y,
10663 u,
10664 v,
10665 base_q_idx,
10666 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10667 )?;
10668 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
10669 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
10670 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
10671 // left column over its height. This arm wrote neither before lane-intrasplit
10672 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
10673 // context across the strip's footprint.
10674 for i in 0..bw / MI {
10675 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10676 *cell = tx_w as u8;
10677 }
10678 }
10679 for i in 0..bh / MI {
10680 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10681 *cell = tx_h as u8;
10682 }
10683 }
10684 // The strip's own palette state into the mi-granular neighbour bands, so
10685 // the next block's colour cache and `palette_y_mode` context are libaom's.
10686 record_strip_palette(
10687 neighbours,
10688 (mi_r, mi_c),
10689 bw,
10690 bh,
10691 palette_y.as_ref().map_or(0, |p| p.size),
10692 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
10693 palette_uv.as_ref().map_or(0, |p| p.size),
10694 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
10695 );
10696 let class = match bw.max(bh) {
10697 64 => 0,
10698 32 => 1,
10699 _ => 2,
10700 };
10701 hit_do! {
10702 INTRA_RECT_IN_INTER_HITS.with(|h| {
10703 let mut v = h.get();
10704 v[class] += 1;
10705 h.set(v);
10706 });
10707 }
10708 Ok(())
10709}
10710
10711/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
10712/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
10713/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
10714/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
10715/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
10716/// has no rectangular-transform coefficient reader, and a chroma plane here
10717/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
10718/// with no depth-based square-tiling escape the way luma's own resolved
10719/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
10720/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
10721#[allow(clippy::too_many_arguments)]
10722fn decode_block_rect(
10723 dec: &mut SymbolDecoder,
10724 cdfs: &mut Cdfs,
10725 neighbours: &mut Neighbours,
10726 at: (usize, usize),
10727 bw: usize,
10728 bh: usize,
10729 y: &mut PlaneBuf<'static>,
10730 u: &mut PlaneBuf<'static>,
10731 v: &mut PlaneBuf<'static>,
10732 enable_filter_intra: bool,
10733 allow_screen_content_tools: bool,
10734 base_q_idx: u8,
10735 tx_select: bool,
10736 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10737) -> Result<()> {
10738 let (r, c) = at;
10739 let (px, py) = (c * SUB, r * SUB);
10740 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10741 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10742 let palette_uv_cache = neighbours.palette_uv_cache(at);
10743 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10744 read_intra_mode_rect(
10745 dec,
10746 cdfs,
10747 nb_above_mode,
10748 nb_left_mode,
10749 true,
10750 true,
10751 bw,
10752 bh,
10753 enable_filter_intra,
10754 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10755 allow_screen_content_tools,
10756 Some((palette_ctx, &palette_cache)),
10757 &palette_uv_cache,
10758 r * (SUB / MI),
10759 c * (SUB / MI), fctx,
10760 )?;
10761 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10762 if smooth_neighbor {
10763 hit!(SMOOTH_LUMA_HITS);
10764 }
10765 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
10766 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
10767 // `uv_mode`, not the luma one.
10768 let smooth_neighbor_uv =
10769 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10770 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
10771 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
10772 // rectangle just as happily), so a `use_filter_intra` strip at this level
10773 // predicts instead of refusing. The below-16x16 leaf arm
10774 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
10775 if filter_intra.is_some() {
10776 hit!(FILTER_INTRA_RECT_HITS);
10777 }
10778 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10779 DC_PRED
10780 } else {
10781 uv_mode
10782 };
10783 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10784 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
10785 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
10786 // one did not, so with `--enable-tx-size-search=0` -- which several gate
10787 // recipes use -- the decoder consumed a symbol the encoder never wrote and
10788 // desynced the tile from that point on. That is why both strips of the
10789 // pinned HORZ quadrant were wrong from their very first pixel, and why our
10790 // range after the read equalled the oracle's range for the whole block.
10791 let depth = if tx_select {
10792 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10793 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10794 // the 16x4 intra-in-inter strips already do); the key frame's
10795 // deblock-grid approximation is only right where those bands were never
10796 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10797 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10798 // `tx_size_cat2` row 1 where libaom reads row 2.
10799 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10800 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10801 } else {
10802 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10803 };
10804 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10805 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10806 eprintln!(
10807 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10808 dec.debug_state().0
10809 );
10810 }
10811 d
10812 } else {
10813 0
10814 };
10815 if depth != 0 || lossless(fctx) {
10816 hit!(TX_DEPTH_HITS);
10817 // lane-rectsplit r1: a split transform is predicted and reconstructed
10818 // per transform unit, each unit taking its edges from the previous
10819 // unit's reconstruction inside this same strip (spec 5.11.36) --
10820 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10821 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10822 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10823 eprintln!(
10824 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10825 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10826 angle_y={angle_delta_y}"
10827 );
10828 }
10829 let modes = RectStripModes {
10830 skip,
10831 mode,
10832 angle_delta_y,
10833 uv_predict_mode,
10834 angle_delta_uv,
10835 alpha,
10836 filter_intra,
10837 smooth_neighbor,
10838 smooth_neighbor_uv,
10839 palette_y: palette_y
10840 .as_ref()
10841 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10842 palette_uv: palette_uv.as_ref().map(|p| {
10843 (
10844 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10845 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10846 )
10847 }),
10848 };
10849 if palette_y.is_some() || palette_uv.is_some() {
10850 hit!(PALETTE_SPLIT_TX_HITS);
10851 }
10852 decode_rect_split(
10853 dec,
10854 cdfs,
10855 neighbours,
10856 (mi_r, mi_c),
10857 bw,
10858 bh,
10859 tx_w,
10860 tx_h,
10861 &modes,
10862 y,
10863 u,
10864 v,
10865 base_q_idx,
10866 reduced_tx_set, fctx,
10867 )?;
10868 // This early return skips this fn's own tail, so the palette
10869 // neighbour state has to be stamped HERE too: without it a split-tx
10870 // strip left the above/left palette arrays holding a DEAD block's
10871 // colours, and the next block's colour cache
10872 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
10873 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
10874 // and only those pixels were wrong (lane-palette2 r10).
10875 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10876 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10877 let (puv_size, puv_colors) =
10878 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10879 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10880 hit!(RECT_PARTITION_HITS);
10881 return Ok(());
10882 }
10883 let (tx_w, tx_h) = (bw, bh);
10884 let (cpx, cpy) = (px / 2, py / 2);
10885 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10886 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10887 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10888 let (rng, _) = dec.debug_state();
10889 eprintln!(
10890 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
10891 skip={} tx={depth} rng={rng}",
10892 skip as i32
10893 );
10894 }
10895 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
10896 // block's prediction is the reconstructed colour-index map, set fresh
10897 // right before each `reconstruct_rect` call below (lane-palette2 r4).
10898 if let Some(ref pyv) = palette_y {
10899 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10900 set_palette_pred(buf, fctx);
10901 }
10902 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10903 (
10904 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10905 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10906 )
10907 });
10908 if skip {
10909 push_intra_rect(0,
10910 px,
10911 py,
10912 bw,
10913 bh,
10914 mode,
10915 angle_delta_y,
10916 reach,
10917 &ZERO_RESIDUAL[..bw * bh],
10918 None,
10919 filter_intra,
10920 smooth_neighbor, fctx,
10921 );
10922 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10923 if let Some((ub, _)) = &palette_uv_bufs {
10924 set_palette_pred(ub.clone(), fctx);
10925 }
10926 push_intra_rect(1,
10927 cpx,
10928 cpy,
10929 chroma_w,
10930 chroma_h,
10931 uv_predict_mode,
10932 angle_delta_uv,
10933 reach,
10934 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10935 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10936 None,
10937 smooth_neighbor_uv, fctx,
10938 );
10939 if let Some((_, vb)) = &palette_uv_bufs {
10940 set_palette_pred(vb.clone(), fctx);
10941 }
10942 push_intra_rect(2,
10943 cpx,
10944 cpy,
10945 chroma_w,
10946 chroma_h,
10947 uv_predict_mode,
10948 angle_delta_uv,
10949 reach,
10950 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10951 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10952 None,
10953 smooth_neighbor_uv, fctx,
10954 );
10955 neighbours.record_rect(
10956 at,
10957 bw,
10958 bh,
10959 mode,
10960 uv_predict_mode,
10961 &[
10962 &ZERO_RESIDUAL[..bw * bh],
10963 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10964 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10965 ],
10966 );
10967 } else {
10968 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
10969 // reduces both size pairs to their square-up CDF sets
10970 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
10971 // doc comments); the scan order and 2D context tables are the real
10972 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
10973 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
10974 (&SCAN_32X16, &SCAN_16X8)
10975 } else {
10976 (&SCAN_16X32, &SCAN_8X16)
10977 };
10978 // lane-rectwire r3: real coefficients desync a pixel-exact gate
10979 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
10980 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
10981 // pixel (not a subtle context-table off-by-one), while the sibling
10982 // non-rect quadrants of the same frame match. Range-ladder bisection
10983 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
10984 // but the intra key-frame path has no traced symbol between the
10985 // partition read and the first coefficient block (mode/skip/tx_depth
10986 // reads are all untraced in libaom's decodeframe.c intra path, unlike
10987 // the inter EC_TRACE_MODE this round added), so a same-length range
10988 // comparison wasn't reachable within budget -- see
10989 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10990 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10991 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10992 // libaom and match). lane-rectwire r4: range-ladder against the
10993 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10994 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10995 // both confirmed in sync -- rng=58692 on both sides right after
10996 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10997 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10998 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10999 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
11000 // its own tx_size read) unless oracle's tx symbol is a near-certainty
11001 // CDF that barely narrows the range -- i.e. this decoder's
11002 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
11003 // a 32x16/16x32 strip is the first diverging symbol, not the
11004 // coefficient-context math r3 already cleared. Not confirmed byte-
11005 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
11006 // `read_tx_size`'s own rng, not attempted this round -- budget), so
11007 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
11008 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
11009 // it unconditionally where both square paths gate on `tx_select`. With
11010 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
11011 // decoder consumed one that was never there.
11012 {
11013 let around = neighbours.around_rect(at, bw, bh);
11014 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
11015 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11016 dec,
11017 &mut luma_coding,
11018 luma_scan,
11019 bw,
11020 bh,
11021 0,
11022 dc_sign_ctx(around[0].2),
11023 TxType::DctDct,
11024 )?;
11025 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11026 let (rng, _) = dec.debug_state();
11027 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11028 }
11029 let luma_residual = dequant_and_inverse_typed_wh(
11030 &luma_levels,
11031 bw,
11032 bh,
11033 crate::decode::bit_depth(fctx),
11034 block_q_idx(fctx),
11035 plane_q_delta(0, fctx).0,
11036 plane_q_delta(0, fctx).1,
11037 luma_tx_type,
11038 );
11039 push_intra_rect(0,
11040 px,
11041 py,
11042 bw,
11043 bh,
11044 mode,
11045 angle_delta_y,
11046 reach,
11047 &luma_residual,
11048 None,
11049 filter_intra,
11050 smooth_neighbor, fctx,
11051 );
11052 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11053 if let Some((ub, _)) = &palette_uv_bufs {
11054 set_palette_pred(ub.clone(), fctx);
11055 }
11056 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11057 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11058 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11059 let (u_levels, u_tx_type) = read_coeffs_rect(
11060 dec,
11061 &mut u_coding,
11062 chroma_scan,
11063 chroma_w,
11064 chroma_h,
11065 u_skip_ctx,
11066 dc_sign_ctx(around[1].2),
11067 u_default_tx,
11068 )?;
11069 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11070 let (rng, _) = dec.debug_state();
11071 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11072 }
11073 let u_residual = dequant_and_inverse_typed_wh(
11074 &u_levels,
11075 chroma_w,
11076 chroma_h,
11077 crate::decode::bit_depth(fctx),
11078 block_q_idx(fctx),
11079 plane_q_delta(1, fctx).0,
11080 plane_q_delta(1, fctx).1,
11081 u_tx_type,
11082 );
11083 push_intra_rect(1,
11084 cpx,
11085 cpy,
11086 chroma_w,
11087 chroma_h,
11088 uv_predict_mode,
11089 angle_delta_uv,
11090 reach,
11091 &u_residual,
11092 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11093 None,
11094 smooth_neighbor_uv, fctx,
11095 );
11096 if let Some((_, vb)) = &palette_uv_bufs {
11097 set_palette_pred(vb.clone(), fctx);
11098 }
11099 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11100 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11101 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11102 let (v_levels, v_tx_type) = read_coeffs_rect(
11103 dec,
11104 &mut v_coding,
11105 chroma_scan,
11106 chroma_w,
11107 chroma_h,
11108 v_skip_ctx,
11109 dc_sign_ctx(around[2].2),
11110 v_default_tx,
11111 )?;
11112 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11113 let (rng, _) = dec.debug_state();
11114 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11115 }
11116 let v_residual = dequant_and_inverse_typed_wh(
11117 &v_levels,
11118 chroma_w,
11119 chroma_h,
11120 crate::decode::bit_depth(fctx),
11121 block_q_idx(fctx),
11122 plane_q_delta(2, fctx).0,
11123 plane_q_delta(2, fctx).1,
11124 v_tx_type,
11125 );
11126 push_intra_rect(2,
11127 cpx,
11128 cpy,
11129 chroma_w,
11130 chroma_h,
11131 uv_predict_mode,
11132 angle_delta_uv,
11133 reach,
11134 &v_residual,
11135 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11136 None,
11137 smooth_neighbor_uv, fctx,
11138 );
11139 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11140 hit!(RECT_COEFF_HITS);
11141 }
11142 }
11143 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11144 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
11145 let (puv_size, puv_colors) =
11146 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11147 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
11148 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
11149 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
11150 hit!(RECT_PARTITION_HITS);
11151 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11152 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
11153 }
11154 Ok(())
11155}
11156
11157/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
11158/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
11159/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
11160/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
11161/// the second strip of a HORZ/VERT split sits offset by half the 16x16
11162/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
11163/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
11164/// previous strip is directly above (same column, `mi_h` rows up) or
11165/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
11166/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
11167/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
11168/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
11169/// this strip's real position, never the coarse `record_rect` (which the
11170/// caller uses once, after both strips, exactly like the `VERT_B` arm next
11171/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
11172/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
11173/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
11174/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
11175#[allow(clippy::too_many_arguments)]
11176fn decode_leaf_rect(
11177 dec: &mut SymbolDecoder,
11178 cdfs: &mut Cdfs,
11179 neighbours: &mut Neighbours,
11180 outer_at: (usize, usize),
11181 leaf_mi: (usize, usize),
11182 bw: usize,
11183 bh: usize,
11184 prev_leaf: Option<((usize, usize), usize)>,
11185 y: &mut PlaneBuf<'static>,
11186 u: &mut PlaneBuf<'static>,
11187 v: &mut PlaneBuf<'static>,
11188 enable_filter_intra: bool,
11189 allow_screen_content_tools: bool,
11190 base_q_idx: u8,
11191 tx_select: bool,
11192 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11193) -> Result<usize> {
11194 let _ = base_q_idx;
11195 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11196 eprintln!(
11197 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
11198 dec.debug_state().0
11199 );
11200 }
11201 let (r, c) = outer_at;
11202 let mut above_mode = neighbours.above_mode[c];
11203 let mut left_mode = neighbours.left_mode[r];
11204 let (mi_w, mi_h) = (bw / MI, bh / MI);
11205 if let Some(((pr, pc), pmode)) = prev_leaf {
11206 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
11207 above_mode = pmode;
11208 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
11209 left_mode = pmode;
11210 }
11211 }
11212 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
11213 // cannot hold the modes a split (or a pair of strips) leaves behind, so
11214 // when the map holds the block at exactly this strip's above/left mi it
11215 // is the neighbour libaom's `above_mi`/`left_mi` reads.
11216 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
11217 // availability-correct -- four 16x8 strips share one coarse 16x16
11218 // `left_mode` cell too, so the fallback must not stand in for an absent
11219 // tile-edge neighbour.
11220 let (above_mode, left_mode) =
11221 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
11222 let smooth_neighbor =
11223 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11224 if smooth_neighbor {
11225 hit!(SMOOTH_LUMA_HITS);
11226 }
11227 // The palette-Y mode CDF row is picked by the neighbours' palette use
11228 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
11229 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
11230 // a palette narrows the wrong interval and desyncs the tile even when the
11231 // decoded bit is the same. The cell is the 16px-SUB cell containing the
11232 // leaf (the palette neighbour arrays have no finer granularity).
11233 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
11234 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
11235 // exclusion and the neighbour palette lookup itself are mi-granular
11236 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
11237 let pal_at = leaf_mi;
11238 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11239 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11240 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11241 read_intra_mode_rect(
11242 dec,
11243 cdfs,
11244 above_mode,
11245 left_mode,
11246 true,
11247 true,
11248 bw,
11249 bh,
11250 enable_filter_intra,
11251 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
11252 allow_screen_content_tools,
11253 Some((palette_ctx, &palette_cache)),
11254 &palette_uv_cache,
11255 leaf_mi.0,
11256 leaf_mi.1, fctx,
11257 )?;
11258 // lane-kf900 r4: palette prediction on this shape, the same colour-index
11259 // map -> base colours buffer [`decode_block_rect`] hands each
11260 // `reconstruct_rect` through [`set_palette_pred`].
11261 if palette_y.is_some() || palette_uv.is_some() {
11262 hit!(RECT4_PALETTE_HITS);
11263 }
11264 let palette_y_buf: Option<Vec<u16>> = palette_y
11265 .as_ref()
11266 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11267 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11268 (
11269 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11270 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11271 )
11272 });
11273 let (pal_y_size, pal_y_colors) =
11274 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11275 let (pal_uv_size, pal_uv_colors) =
11276 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11277 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11278 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
11279 }
11280 if filter_intra.is_some() {
11281 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
11282 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
11283 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
11284 // below already makes; this refusal was square-only prose.
11285 hit!(FILTER_INTRA_RECT_HITS);
11286 hit!(FILTER_INTRA_RECT_SUB16_HITS);
11287 }
11288 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11289 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
11290 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
11291 // a constant `false`.
11292 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
11293 let depth = if tx_select {
11294 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
11295 // every other rect reader now does -- a no-op on a key frame.
11296 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11297 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
11298 } else {
11299 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
11300 };
11301 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
11302 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
11303 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
11304 // count (3), different CDF row: a wrong-table read of a real symbol,
11305 // the class that cost lane-rectsplit r1 its 64x32 depth.
11306 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
11307 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
11308 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
11309 // function also decodes) sit at depth 2, so they read
11310 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
11311 // while `tx_size_cat2` belongs to the 32-level shapes
11312 // ([`decode_block_rect`]). Both tables carry three symbols, so the
11313 // wrong one decodes a plausible depth from the wrong probabilities:
11314 // the range diverges silently at the first such leaf and every later
11315 // symbol in the tile is read from the wrong place (class
11316 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
11317 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
11318 } else {
11319 0
11320 };
11321 if depth != 0 || lossless(fctx) {
11322 // The same per-transform-unit walk the bigger strips take
11323 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
11324 // depth 2), addressed at this leaf's own mi position.
11325 hit!(TX_DEPTH_HITS);
11326 hit!(SUB16_SPLIT_HITS);
11327 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11328 let modes = RectStripModes {
11329 skip,
11330 mode,
11331 angle_delta_y,
11332 uv_predict_mode,
11333 angle_delta_uv,
11334 alpha,
11335 filter_intra,
11336 smooth_neighbor,
11337 // lane-rectsplitx r3: the split arm hard-coded `false` here while
11338 // the unsplit arm below passes the real neighbour answer -- chroma
11339 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
11340 smooth_neighbor_uv,
11341 palette_y: palette_y_buf.clone(),
11342 palette_uv: palette_uv_bufs.clone(),
11343 };
11344 if palette_y.is_some() || palette_uv.is_some() {
11345 hit!(PALETTE_SPLIT_TX_HITS);
11346 }
11347 decode_rect_split(
11348 dec,
11349 cdfs,
11350 neighbours,
11351 leaf_mi,
11352 bw,
11353 bh,
11354 tx_w,
11355 tx_h,
11356 &modes,
11357 y,
11358 u,
11359 v,
11360 base_q_idx,
11361 reduced_tx_set, fctx,
11362 )?;
11363 record_strip_palette(
11364 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11365 );
11366 return Ok(mode);
11367 }
11368 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11369 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11370 let (cpx, cpy) = (px / 2, py / 2);
11371 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11372 let (luma_levels, u_levels, v_levels);
11373 if skip {
11374 luma_levels = Grid::Zero(bw * bh);
11375 u_levels = Grid::Zero(chroma_w * chroma_h);
11376 v_levels = Grid::Zero(chroma_w * chroma_h);
11377 if let Some(b) = &palette_y_buf {
11378 set_palette_pred(b.clone(), fctx);
11379 }
11380 push_intra_rect(0,
11381 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
11382 smooth_neighbor, fctx,
11383 );
11384 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11385 if let Some((ub, _)) = &palette_uv_bufs {
11386 set_palette_pred(ub.clone(), fctx);
11387 }
11388 push_intra_rect(1,
11389 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
11390 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11391 );
11392 if let Some((_, vb)) = &palette_uv_bufs {
11393 set_palette_pred(vb.clone(), fctx);
11394 }
11395 push_intra_rect(2,
11396 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
11397 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11398 );
11399 } else {
11400 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
11401 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
11402 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
11403 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
11404 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
11405 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
11406 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
11407 (&SCAN_16X8, &SCAN_8X4)
11408 } else {
11409 (&SCAN_8X16, &SCAN_4X8)
11410 };
11411 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
11412 let luma_set = if reduced_tx_set {
11413 TxbSet::LumaRect16x8
11414 } else {
11415 TxbSet::LumaRect16x8Set1
11416 };
11417 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
11418 let (l_levels, luma_tx_type) = read_coeffs_rect(
11419 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
11420 )?;
11421 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11422 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
11423 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
11424 }
11425 luma_levels = l_levels;
11426 let luma_residual = dequant_and_inverse_typed_wh(
11427 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
11428 block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, 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, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
11435 smooth_neighbor, fctx,
11436 );
11437 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11438 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11439 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11440 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11441 let (u_l, u_tx_type) = read_coeffs_rect(
11442 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11443 dc_sign_ctx(around[1].2), u_default_tx,
11444 )?;
11445 u_levels = u_l;
11446 let u_residual = dequant_and_inverse_typed_wh(
11447 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11448 block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
11449 );
11450 if let Some((ub, _)) = &palette_uv_bufs {
11451 set_palette_pred(ub.clone(), fctx);
11452 }
11453 push_intra_rect(1,
11454 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
11455 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11456 );
11457 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11458 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11459 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11460 let (v_l, v_tx_type) = read_coeffs_rect(
11461 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11462 dc_sign_ctx(around[2].2), v_default_tx,
11463 )?;
11464 v_levels = v_l;
11465 let v_residual = dequant_and_inverse_typed_wh(
11466 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11467 block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
11468 );
11469 if let Some((_, vb)) = &palette_uv_bufs {
11470 set_palette_pred(vb.clone(), fctx);
11471 }
11472 push_intra_rect(2,
11473 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
11474 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11475 );
11476 hit!(RECT_LEAF_COEFF_HITS);
11477 }
11478 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11479 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
11480 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11481 // The leaf's own palette state (`0` clears, as this site always did
11482 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
11483 // AXIS only until the pair's closing leaf: the coarse cell holds one
11484 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
11485 // real left neighbour leaf 1 reads (lane-kf900 r4).
11486 record_strip_palette(
11487 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11488 );
11489 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
11490 // rows -- record the whole span, not one cell.
11491 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
11492 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
11493 Ok(mode)
11494}
11495
11496/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
11497/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
11498/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
11499/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
11500/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
11501/// strip's mode so this one's mode context sees its true above/left
11502/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
11503///
11504/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
11505/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
11506/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
11507/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
11508/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
11509/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
11510/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
11511///
11512/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
11513/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
11514/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
11515/// unexamined.
11516#[allow(clippy::too_many_arguments)]
11517fn decode_block_rect4(
11518 dec: &mut SymbolDecoder,
11519 cdfs: &mut Cdfs,
11520 neighbours: &mut Neighbours,
11521 strip_mi: (usize, usize),
11522 bw: usize,
11523 bh: usize,
11524 prev_strip: Option<((usize, usize), usize)>,
11525 y: &mut PlaneBuf<'static>,
11526 u: &mut PlaneBuf<'static>,
11527 v: &mut PlaneBuf<'static>,
11528 enable_filter_intra: bool,
11529 allow_screen_content_tools: bool,
11530 base_q_idx: u8,
11531 tx_select: bool, fctx: &crate::decode::FrameCtx,
11532) -> Result<(usize, usize)> {
11533 let _ = base_q_idx;
11534 let (mi_r, mi_c) = strip_mi;
11535 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11536 let (mi_w, mi_h) = (bw / MI, bh / MI);
11537 let mut above_mode = neighbours.above_mode[c];
11538 let mut left_mode = neighbours.left_mode[r];
11539 if let Some(((pr, pc), pmode)) = prev_strip {
11540 if pc == mi_c && mi_r == pr + mi_h {
11541 above_mode = pmode;
11542 } else if pr == mi_r && mi_c == pc + mi_w {
11543 left_mode = pmode;
11544 }
11545 }
11546 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
11547 // availability-correct neighbour modes (see
11548 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
11549 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
11550 let (above_mode, left_mode) =
11551 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
11552 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
11553 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
11554 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
11555 // wrong interval, so a screen-content tile desynced at the first strip
11556 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
11557 let pal_at = (mi_r, mi_c);
11558 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11559 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11560 let (
11561 skip,
11562 mode,
11563 angle_delta_y,
11564 uv_mode,
11565 angle_delta_uv,
11566 alpha,
11567 filter_intra,
11568 palette_y,
11569 palette_uv,
11570 ) = read_intra_mode_rect(
11571 dec,
11572 cdfs,
11573 above_mode,
11574 left_mode,
11575 true,
11576 true,
11577 bw,
11578 bh,
11579 enable_filter_intra,
11580 neighbours.skip_txfm_ctx(mi_r, mi_c),
11581 allow_screen_content_tools,
11582 Some((palette_ctx, &palette_cache)),
11583 &palette_uv_cache,
11584 mi_r,
11585 mi_c, fctx,
11586 )?;
11587 // lane-kf900 r4: palette prediction on this shape, exactly as
11588 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
11589 // mapped through the base colours IS the prediction (it reads no edge
11590 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
11591 if palette_y.is_some() || palette_uv.is_some() {
11592 hit!(RECT4_PALETTE_HITS);
11593 }
11594 let palette_y_buf: Option<Vec<u16>> = palette_y
11595 .as_ref()
11596 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11597 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11598 (
11599 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11600 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11601 )
11602 });
11603 let (pal_y_size, pal_y_colors) =
11604 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11605 let (pal_uv_size, pal_uv_colors) =
11606 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11607 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11608 if smooth_neighbor {
11609 hit!(SMOOTH_LUMA_HITS);
11610 }
11611 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
11612 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
11613 // `r * (SUB / MI)` names a different mi column and the chroma
11614 // edge-filter strength was read from the wrong neighbour (measured:
11615 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
11616 // with luma bit-exact).
11617 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11618 if filter_intra.is_some() {
11619 hit!(FILTER_INTRA_RECT_HITS);
11620 if bw > bh {
11621 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
11622 } else {
11623 hit!(FILTER_INTRA_RECT4_VERT_HITS);
11624 }
11625 }
11626 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11627 DC_PRED
11628 } else {
11629 uv_mode
11630 };
11631 let depth = if tx_select {
11632 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11633 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11634 // the 16x4 intra-in-inter strips already do); the key frame's
11635 // deblock-grid approximation is only right where those bands were never
11636 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11637 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11638 // `tx_size_cat2` row 1 where libaom reads row 2.
11639 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11640 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11641 } else {
11642 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11643 };
11644 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11645 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11646 eprintln!(
11647 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11648 dec.debug_state().0
11649 );
11650 }
11651 d
11652 } else {
11653 0
11654 };
11655 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11656 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11657 publish_txfm_bands_if_in_inter(
11658 neighbours,
11659 (mi_r, mi_c),
11660 depth_to_tx_wh(bw, bh, depth, fctx),
11661 (bw, bh), fctx,
11662 );
11663 if depth != 0 || lossless(fctx) {
11664 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
11665 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
11666 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
11667 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
11668 // both interleave in every real stream.
11669 hit!(TX_DEPTH_HITS);
11670 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11671 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
11672 // predicted -- depth 1 fires FIRST in every attempt that splits at
11673 // all, so a depth-2-only lift could never be gated. The r1 mismatch
11674 // was never the rect unit: it was the neighbour MODE the strip reads
11675 // (see `modes_above_left_mi`).
11676 let which = if depth == 1 {
11677 &RECT4_SPLIT_DEPTH1_HITS
11678 } else {
11679 &RECT4_SPLIT_DEPTH2_HITS
11680 };
11681 hit_do! { which.with(|c| c.set(c.get() + 1)); }
11682 let modes = RectStripModes {
11683 skip,
11684 mode,
11685 angle_delta_y,
11686 uv_predict_mode,
11687 angle_delta_uv,
11688 alpha,
11689 filter_intra,
11690 smooth_neighbor,
11691 smooth_neighbor_uv,
11692 palette_y: palette_y_buf.clone(),
11693 palette_uv: palette_uv_bufs.clone(),
11694 };
11695 if palette_y.is_some() || palette_uv.is_some() {
11696 hit!(PALETTE_SPLIT_TX_HITS);
11697 }
11698 decode_rect_split(
11699 dec,
11700 cdfs,
11701 neighbours,
11702 (mi_r, mi_c),
11703 bw,
11704 bh,
11705 tx_w,
11706 tx_h,
11707 &modes,
11708 y,
11709 u,
11710 v,
11711 base_q_idx,
11712 false, fctx,
11713 )?;
11714 record_strip_palette(
11715 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11716 pal_uv_colors,
11717 );
11718 if bw > bh {
11719 hit!(RECT4_32_HORZ_HITS);
11720 } else {
11721 hit!(RECT4_32_VERT_HITS);
11722 }
11723 if !skip {
11724 hit!(RECT4_COEFF_HITS);
11725 }
11726 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11727 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11728 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11729 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11730 // transform size in both TXFM_CONTEXT bands. Without it the next block
11731 // reads the row's stale value.
11732 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11733 return Ok((mode, uv_predict_mode));
11734 }
11735 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
11736 // that is 8 px tall, so each strip stamps every cell it touches and the
11737 // LAST strip wins -- which is the right answer for the block below/right
11738 // of the 32x32, the only reader outside it. Written after this strip's
11739 // own context read above, never before.
11740 for cell in 0..bw.div_ceil(SUB) {
11741 neighbours.above_mode[c + cell] = mode;
11742 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
11743 neighbours.above_side[c + cell] = bw;
11744 }
11745 for cell in 0..bh.div_ceil(SUB) {
11746 neighbours.left_mode[r + cell] = mode;
11747 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
11748 neighbours.left_side[r + cell] = bh;
11749 }
11750 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
11751 // [`decode_leaf_rect`] does (the split arm above records these through
11752 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
11753 // `sub8_mode_row` holding the previous block, and the next 32x32's
11754 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
11755 // fixture).
11756 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
11757 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
11758 let (px, py) = (mi_c * MI, mi_r * MI);
11759 let (cpx, cpy) = (px / 2, py / 2);
11760 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11761 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11762 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
11763 (&SCAN_32X8, &SCAN_16X4)
11764 } else {
11765 (&SCAN_8X32, &SCAN_4X16)
11766 };
11767 let (luma_levels, u_levels, v_levels) = if skip {
11768 (
11769 vec![0i32; bw * bh],
11770 vec![0i32; chroma_w * chroma_h],
11771 vec![0i32; chroma_w * chroma_h],
11772 )
11773 } else {
11774 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11775 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
11776 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11777 dec,
11778 &mut luma_coding,
11779 luma_scan,
11780 bw,
11781 bh,
11782 0,
11783 dc_sign_ctx(around[0].2),
11784 TxType::DctDct,
11785 )?;
11786 let mut planes = Vec::with_capacity(2);
11787 for plane in 1..3 {
11788 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11789 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11790 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11791 let (levels, tx_type) = read_coeffs_rect(
11792 dec,
11793 &mut coding,
11794 chroma_scan,
11795 chroma_w,
11796 chroma_h,
11797 skip_ctx,
11798 dc_sign_ctx(around[plane].2),
11799 default_tx,
11800 )?;
11801 planes.push((levels, tx_type));
11802 }
11803 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11804 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11805 hit!(RECT4_COEFF_HITS);
11806 let luma_residual = dequant_and_inverse_typed_wh(
11807 &luma_levels,
11808 bw,
11809 bh,
11810 crate::decode::bit_depth(fctx),
11811 block_q_idx(fctx),
11812 plane_q_delta(0, fctx).0,
11813 plane_q_delta(0, fctx).1,
11814 luma_tx_type,
11815 );
11816 if let Some(b) = &palette_y_buf {
11817 set_palette_pred(b.clone(), fctx);
11818 }
11819 push_intra_rect(0,
11820 px,
11821 py,
11822 bw,
11823 bh,
11824 mode,
11825 angle_delta_y,
11826 reach,
11827 &luma_residual,
11828 None,
11829 filter_intra,
11830 smooth_neighbor, fctx,
11831 );
11832 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11833 for (plane, _buf, levels, tx_type) in [
11834 (1usize, &mut *u, &u_levels, u_tx_type),
11835 (2, &mut *v, &v_levels, v_tx_type),
11836 ] {
11837 let residual = dequant_and_inverse_typed_wh(
11838 levels,
11839 chroma_w,
11840 chroma_h,
11841 crate::decode::bit_depth(fctx),
11842 block_q_idx(fctx),
11843 plane_q_delta(plane, fctx).0,
11844 plane_q_delta(plane, fctx).1,
11845 tx_type,
11846 );
11847 if let Some((ub, vb)) = &palette_uv_bufs {
11848 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11849 }
11850 push_intra_rect(plane,
11851 cpx,
11852 cpy,
11853 chroma_w,
11854 chroma_h,
11855 uv_predict_mode,
11856 angle_delta_uv,
11857 reach,
11858 &residual,
11859 alpha
11860 .zip(ac)
11861 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11862 None,
11863 smooth_neighbor_uv, fctx,
11864 );
11865 }
11866 neighbours.record_mi_rect(
11867 (mi_r, mi_c),
11868 bw,
11869 bh,
11870 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
11871 );
11872 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11873 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11874 record_strip_palette(
11875 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11876 pal_uv_colors,
11877 );
11878 if bw > bh {
11879 hit!(RECT4_32_HORZ_HITS);
11880 } else {
11881 hit!(RECT4_32_VERT_HITS);
11882 }
11883 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11884 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11885 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11886 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11887 // transform size in both TXFM_CONTEXT bands. Without it the next block
11888 // reads the row's stale value.
11889 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11890 return Ok((mode, uv_predict_mode));
11891 };
11892 if let Some(b) = &palette_y_buf {
11893 set_palette_pred(b.clone(), fctx);
11894 }
11895 push_intra_rect(0,
11896 px,
11897 py,
11898 bw,
11899 bh,
11900 mode,
11901 angle_delta_y,
11902 reach,
11903 &luma_levels,
11904 None,
11905 filter_intra,
11906 smooth_neighbor, fctx,
11907 );
11908 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11909 if let Some((ub, _)) = &palette_uv_bufs {
11910 set_palette_pred(ub.clone(), fctx);
11911 }
11912 push_intra_rect(1,
11913 cpx,
11914 cpy,
11915 chroma_w,
11916 chroma_h,
11917 uv_predict_mode,
11918 angle_delta_uv,
11919 reach,
11920 &u_levels,
11921 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11922 None,
11923 smooth_neighbor_uv, fctx,
11924 );
11925 if let Some((_, vb)) = &palette_uv_bufs {
11926 set_palette_pred(vb.clone(), fctx);
11927 }
11928 push_intra_rect(2,
11929 cpx,
11930 cpy,
11931 chroma_w,
11932 chroma_h,
11933 uv_predict_mode,
11934 angle_delta_uv,
11935 reach,
11936 &v_levels,
11937 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11938 None,
11939 smooth_neighbor_uv, fctx,
11940 );
11941 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11942 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11943 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11944 record_strip_palette(
11945 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11946 );
11947 if bw > bh {
11948 hit!(RECT4_32_HORZ_HITS);
11949 } else {
11950 hit!(RECT4_32_VERT_HITS);
11951 }
11952 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11953 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11954 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11955 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11956 // transform size in both TXFM_CONTEXT bands. Without it the next block
11957 // reads the row's stale value.
11958 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11959 Ok((mode, uv_predict_mode))
11960}
11961
11962/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
11963/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
11964/// down, and the first shape here whose luma block is a single mi row (or
11965/// column).
11966///
11967/// What is new at this size is CHROMA. `is_chroma_reference`
11968/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
11969/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
11970/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
11971/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
11972/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
11973/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
11974/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
11975///
11976/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
11977/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
11978/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
11979/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
11980/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
11981/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
11982/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
11983/// shape's own CDF row.
11984///
11985/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
11986/// refuses by name rather than guess-decode.
11987#[allow(clippy::too_many_arguments)]
11988fn decode_rect4_16(
11989 dec: &mut SymbolDecoder,
11990 cdfs: &mut Cdfs,
11991 neighbours: &mut Neighbours,
11992 at16: (usize, usize),
11993 horz: bool,
11994 y: &mut PlaneBuf<'static>,
11995 u: &mut PlaneBuf<'static>,
11996 v: &mut PlaneBuf<'static>,
11997 enable_filter_intra: bool,
11998 allow_screen_content_tools: bool,
11999 base_q_idx: u8,
12000 tx_select: bool,
12001 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12002) -> Result<()> {
12003 let (r, c) = at16;
12004 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
12005 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
12006 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
12007 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
12008 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
12009 let mut prev: Option<((usize, usize), usize)> = None;
12010 let mut last_mode = DC_PRED;
12011 let mut last_uv_mode = DC_PRED;
12012 for i in 0..4usize {
12013 let lmi = if horz {
12014 (mi_row0 + i, mi_col0)
12015 } else {
12016 (mi_row0, mi_col0 + i)
12017 };
12018 let has_chroma = i % 2 == 1;
12019 let (mode, uv, _tx) = decode_rect4_16_strip(
12020 dec,
12021 cdfs,
12022 neighbours,
12023 lmi,
12024 horz,
12025 has_chroma,
12026 prev,
12027 y,
12028 u,
12029 v,
12030 enable_filter_intra,
12031 allow_screen_content_tools,
12032 base_q_idx,
12033 tx_select,
12034 reduced_tx_set, fctx,
12035 )?;
12036 if let Some(m) = uv {
12037 last_uv_mode = m;
12038 }
12039 last_mode = mode;
12040 prev = Some((lmi, mode));
12041 }
12042 // The coarse 16-px cell holds one entry for the whole 16x16: the last
12043 // strip is what a block below (right) sees through it, the mi-exact maps
12044 // above answering everything finer.
12045 neighbours.above_mode[c] = last_mode;
12046 neighbours.left_mode[r] = last_mode;
12047 neighbours.above_uv_mode[c] = last_uv_mode;
12048 neighbours.left_uv_mode[r] = last_uv_mode;
12049 neighbours.above_side[c] = bw;
12050 neighbours.left_side[r] = bh;
12051 Ok(())
12052}
12053
12054/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
12055/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
12056/// block path can decode a SINGLE intra strip of a partition whose other
12057/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
12058/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
12059/// every strip publishes its own mi-exact mode). Returns
12060/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
12061#[allow(clippy::too_many_arguments)]
12062fn decode_rect4_16_strip(
12063 dec: &mut SymbolDecoder,
12064 cdfs: &mut Cdfs,
12065 neighbours: &mut Neighbours,
12066 lmi: (usize, usize),
12067 horz: bool,
12068 has_chroma: bool,
12069 prev: Option<((usize, usize), usize)>,
12070 y: &mut PlaneBuf<'static>,
12071 u: &mut PlaneBuf<'static>,
12072 v: &mut PlaneBuf<'static>,
12073 enable_filter_intra: bool,
12074 allow_screen_content_tools: bool,
12075 base_q_idx: u8,
12076 tx_select: bool,
12077 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12078) -> Result<(usize, Option<usize>, (usize, usize))> {
12079 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
12080 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
12081 let (mi_w, mi_h) = (bw / MI, bh / MI);
12082 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
12083 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
12084 let mut last_uv_mode: Option<usize> = None;
12085 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
12086 // aliases all four strips onto one entry, so the mi-exact map wins and
12087 // the previous strip stands in on the split axis.
12088 let mut above_mode = neighbours.above_mode[c];
12089 let mut left_mode = neighbours.left_mode[r];
12090 if let Some(((pr, pc), pmode)) = prev {
12091 if pc == lmi.1 && lmi.0 == pr + mi_h {
12092 above_mode = pmode;
12093 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
12094 left_mode = pmode;
12095 }
12096 }
12097 let (above_mode, left_mode) =
12098 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
12099 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
12100 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
12101 // off CDF row 0 and every cache hit off an empty cache.
12102 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
12103 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
12104 let (
12105 skip,
12106 mode,
12107 angle_delta_y,
12108 uv_mode,
12109 angle_delta_uv,
12110 alpha,
12111 filter_intra,
12112 palette_y,
12113 palette_uv,
12114 ) = read_intra_mode_rect(
12115 dec,
12116 cdfs,
12117 above_mode,
12118 left_mode,
12119 true,
12120 has_chroma,
12121 bw,
12122 bh,
12123 enable_filter_intra,
12124 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
12125 allow_screen_content_tools,
12126 Some((palette_ctx, &palette_cache)),
12127 &palette_uv_cache,
12128 lmi.0,
12129 lmi.1, fctx,
12130 )?;
12131 if palette_y.is_some() || palette_uv.is_some() {
12132 hit!(RECT4_PALETTE_HITS);
12133 }
12134 // The colour-index map through the base colours IS the prediction.
12135 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
12136 // chroma transform this closing strip codes.
12137 let palette_y_buf: Option<Vec<u16>> = palette_y
12138 .as_ref()
12139 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12140 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12141 (
12142 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12143 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12144 )
12145 });
12146 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12147 if smooth_neighbor {
12148 hit!(SMOOTH_LUMA_HITS);
12149 }
12150 if filter_intra.is_some() {
12151 hit!(FILTER_INTRA_RECT_HITS);
12152 }
12153 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
12154 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
12155 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
12156 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
12157 let depth = if tx_select {
12158 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
12159 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
12160 // the 2:1 intra-in-inter strip already does); the key frame's
12161 // deblock-grid approximation is only right where those bands were
12162 // never written.
12163 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12164 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
12165 } else {
12166 tx_size_context_rect(neighbours, lmi, bw, bh)
12167 };
12168 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
12169 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12170 eprintln!(
12171 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
12172 lmi.0,
12173 lmi.1,
12174 dec.debug_state().0
12175 );
12176 }
12177 d
12178 } else {
12179 0
12180 };
12181 if depth != 0 {
12182 hit!(TX_DEPTH_HITS);
12183 hit!(RECT4_16_SPLIT_HITS);
12184 }
12185 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12186 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
12187 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12188 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
12189 if depth != 0 || lossless(fctx) {
12190 // [`decode_rect_split`]'s per-unit walk, inlined because the
12191 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
12192 // the strip (that function codes one chroma transform per block).
12193 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
12194 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
12195 // unit predicts off the units before it in raster order.
12196 let rect_unit = tx_w != tx_h;
12197 let zero_tu = vec![0i32; tx_w * tx_h];
12198 for tu_row in 0..bh / tx_h {
12199 for tu_col in 0..bw / tx_w {
12200 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
12201 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12202 let tu_reach = Reach::of_tu(
12203 bw,
12204 bh,
12205 tu_col * tx_w,
12206 tu_row * tx_h,
12207 tx_w,
12208 tx_h,
12209 reach,
12210 );
12211 if let Some(b) = &palette_y_buf {
12212 let tu_buf: Vec<u16> = (0..tx_h)
12213 .flat_map(|i| {
12214 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
12215 b[base..base + tx_w].iter().copied()
12216 })
12217 .collect();
12218 set_palette_pred(tu_buf, fctx);
12219 }
12220 if skip {
12221 push_intra_rect(0,
12222 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
12223 None, filter_intra, smooth_neighbor, fctx,
12224 );
12225 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12226 } else if rect_unit {
12227 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
12228 // 32 coded positions and the `TX_4X4` `tx_type` row:
12229 // exactly [`TxbSet::LumaRect4x8`].
12230 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12231 let tu_skip_ctx =
12232 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
12233 let set = if reduced_tx_set {
12234 TxbSet::LumaRect4x8
12235 } else {
12236 TxbSet::LumaRect4x8Set1
12237 };
12238 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
12239 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
12240 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12241 dec,
12242 &mut coding,
12243 tu_scan,
12244 tx_w,
12245 tx_h,
12246 tu_skip_ctx,
12247 dc_sign_ctx(tu_around.2),
12248 TxType::DctDct,
12249 )?;
12250 let residual = dequant_and_inverse_typed_wh(
12251 &tu_grid,
12252 tx_w,
12253 tx_h,
12254 crate::decode::bit_depth(fctx),
12255 block_q_idx(fctx),
12256 plane_q_delta(0, fctx).0,
12257 plane_q_delta(0, fctx).1,
12258 tu_tx_type,
12259 );
12260 push_intra_rect(0,
12261 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
12262 None, filter_intra, smooth_neighbor, fctx,
12263 );
12264 if tu_grid.iter().any(|&l| l != 0) {
12265 hit!(RECT4_16_COEFF_HITS);
12266 }
12267 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12268 } else {
12269 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12270 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12271 let tu_grid = read_plane(
12272 dec,
12273 cdfs,
12274 txbset_for(tx_w, reduced_tx_set),
12275 default_scan(tx_w),
12276 0,
12277 tu_around,
12278 mode,
12279 mode,
12280 angle_delta_y,
12281 tu_reach,
12282 y,
12283 tu_px,
12284 tu_py,
12285 tx_w,
12286 tx_w,
12287 base_q_idx,
12288 None,
12289 filter_intra,
12290 Some(tu_skip_ctx),
12291 smooth_neighbor, fctx,
12292 )?;
12293 if tu_grid.iter().any(|&l| l != 0) {
12294 hit!(RECT4_16_COEFF_HITS);
12295 }
12296 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12297 }
12298 }
12299 }
12300 } else {
12301 let levels = if skip {
12302 let zeros = Grid::Zero(bw * bh);
12303 if let Some(b) = &palette_y_buf {
12304 set_palette_pred(b.clone(), fctx);
12305 }
12306 push_intra_rect(0,
12307 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
12308 smooth_neighbor, fctx,
12309 );
12310 zeros
12311 } else {
12312 // The strip's luma TU *is* the strip (`plane_bsize ==
12313 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
12314 // `txb_skip_ctx` at 0.
12315 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
12316 let set = if reduced_tx_set {
12317 TxbSet::LumaRect16x4
12318 } else {
12319 TxbSet::LumaRect16x4Set1
12320 };
12321 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
12322 let (levels, tx_type) = read_coeffs_rect(
12323 dec,
12324 &mut coding,
12325 scan,
12326 bw,
12327 bh,
12328 0,
12329 dc_sign_ctx(around.2),
12330 TxType::DctDct,
12331 )?;
12332 let residual = dequant_and_inverse_typed_wh(
12333 &levels,
12334 bw,
12335 bh,
12336 crate::decode::bit_depth(fctx),
12337 block_q_idx(fctx),
12338 plane_q_delta(0, fctx).0,
12339 plane_q_delta(0, fctx).1,
12340 tx_type,
12341 );
12342 if let Some(b) = &palette_y_buf {
12343 set_palette_pred(b.clone(), fctx);
12344 }
12345 push_intra_rect(0,
12346 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
12347 smooth_neighbor, fctx,
12348 );
12349 hit!(RECT4_16_COEFF_HITS);
12350 levels
12351 };
12352 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
12353 }
12354 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
12355 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
12356 // `update_partition_context` writes `partition_context_lookup[
12357 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
12358 // the left (mirrored under VERT_4).
12359 for cell in 0..mi_w {
12360 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
12361 *slot = bw as u8;
12362 }
12363 }
12364 for cell in 0..mi_h {
12365 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
12366 *slot = bh as u8;
12367 }
12368 }
12369 if has_chroma {
12370 hit!(RECT4_16_CHROMA_HITS);
12371 let pair_mi = if horz {
12372 (lmi.0 - 1, lmi.1)
12373 } else {
12374 (lmi.0, lmi.1 - 1)
12375 };
12376 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
12377 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
12378 let (cpx, cpy) = (ppx / 2, ppy / 2);
12379 let (cw, ch) = (pw / 2, ph / 2);
12380 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12381 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
12382 hit!(RECT4_16_CHROMA_DIR_HITS);
12383 }
12384 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
12385 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
12386 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
12387 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
12388 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
12389 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
12390 // the pair's top-left luma mi, never this leaf's odd row/column.
12391 // Reading `lmi` here named the leaf directly above (a non-chroma
12392 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
12393 // SMOOTH neighbour: filt_type 0 instead of 1 turned
12394 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
12395 // directional chroma strip, moving 4 samples by 1.
12396 let smooth_neighbor_uv =
12397 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
12398 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
12399 {
12400 hit!(RECT4_16_UV_PAIR_FILT_HITS);
12401 }
12402 let (u_levels, v_levels) = if skip {
12403 let zeros = Grid::Zero(cw * ch);
12404 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
12405 // ~1000) predicts EVERY plane and only guards the residual on
12406 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
12407 // DC + alpha * luma-AC. Dropping the CfL term here left a
12408 // chroma-only bounded box on ReelC's key frames.
12409 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12410 if alpha.is_some() {
12411 hit!(CHROMA_SKIP_CFL_HITS);
12412 }
12413 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
12414 if let Some((ub, vb)) = &palette_uv_bufs {
12415 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12416 }
12417 push_intra_rect(plane,
12418 cpx,
12419 cpy,
12420 cw,
12421 ch,
12422 uv_predict_mode,
12423 angle_delta_uv,
12424 pair_reach,
12425 &zeros,
12426 alpha
12427 .zip(ac)
12428 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12429 None,
12430 smooth_neighbor_uv, fctx,
12431 );
12432 }
12433 (zeros.clone(), zeros)
12434 } else {
12435 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
12436 let mut planes = Vec::with_capacity(2);
12437 for plane in 1..3 {
12438 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12439 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12440 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12441 let (levels, tx_type) = read_coeffs_rect(
12442 dec,
12443 &mut coding,
12444 chroma_scan,
12445 cw,
12446 ch,
12447 skip_ctx,
12448 dc_sign_ctx(around[plane].2),
12449 default_tx,
12450 )?;
12451 planes.push((levels, tx_type));
12452 }
12453 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12454 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12455 // CfL averages the luma of the WHOLE pair, the region this one
12456 // chroma transform covers.
12457 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12458 for (plane, _buf, levels, tx_type) in [
12459 (1usize, &mut *u, &u_levels, u_tx_type),
12460 (2, &mut *v, &v_levels, v_tx_type),
12461 ] {
12462 let residual = dequant_and_inverse_typed_wh(
12463 levels,
12464 cw,
12465 ch,
12466 crate::decode::bit_depth(fctx),
12467 block_q_idx(fctx),
12468 plane_q_delta(plane, fctx).0,
12469 plane_q_delta(plane, fctx).1,
12470 tx_type,
12471 );
12472 if let Some((ub, vb)) = &palette_uv_bufs {
12473 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12474 }
12475 push_intra_rect(plane,
12476 cpx,
12477 cpy,
12478 cw,
12479 ch,
12480 uv_predict_mode,
12481 angle_delta_uv,
12482 pair_reach,
12483 &residual,
12484 alpha
12485 .zip(ac)
12486 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12487 None,
12488 smooth_neighbor_uv, fctx,
12489 );
12490 }
12491 (u_levels, v_levels)
12492 };
12493 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
12494 // The chroma planes' coefficient context, over the PAIR's mi span
12495 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
12496 // the luma one rounded up to its 4x4 unit).
12497 let u_state = neighbour_state(&u_levels);
12498 let v_state = neighbour_state(&v_levels);
12499 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12500 let bound_h = round_up_even(neighbours.mi_rows);
12501 let bound_w = round_up_even(neighbours.mi_cols);
12502 for cell in 0..(ph / MI) {
12503 if pair_mi.0 + cell < bound_h
12504 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
12505 {
12506 slot[1] = u_state;
12507 slot[2] = v_state;
12508 }
12509 }
12510 for cell in 0..(pw / MI) {
12511 if pair_mi.1 + cell < bound_w
12512 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
12513 {
12514 slot[1] = u_state;
12515 slot[2] = v_state;
12516 }
12517 }
12518 last_uv_mode = Some(uv_predict_mode);
12519 }
12520 if horz {
12521 hit!(RECT4_16_HORZ_HITS);
12522 } else {
12523 hit!(RECT4_16_VERT_HITS);
12524 }
12525 let (pal_y_size, pal_y_colors) =
12526 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12527 let (pal_uv_size, pal_uv_colors) =
12528 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12529 record_strip_palette(
12530 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12531 );
12532 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12533 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12534 // frame): the above row records `tx_size_wide` over the block's width and
12535 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12536 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12537 // and it published neither band -- so the block after a 64x16 strip read
12538 // the row's init value 64 as its left transform height and took
12539 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12540 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12541 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12542 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
12543 Ok((mode, last_uv_mode, (tx_w, tx_h)))
12544}
12545
12546
12547/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
12548/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
12549/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
12550/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
12551/// cap, so LUMA needs the same corner truncation [`decode_block`] already
12552/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
12553/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
12554/// this function's own charter/report), so both strips read a real 32x32
12555/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
12556/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
12557/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
12558/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
12559/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
12560/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
12561/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
12562/// that function, only the single-transform-unit (`tx_depth == 0`) case is
12563/// supported: a split transform refuses by name rather than guess-decode.
12564#[allow(clippy::too_many_arguments)]
12565fn decode_block_rect64(
12566 dec: &mut SymbolDecoder,
12567 cdfs: &mut Cdfs,
12568 neighbours: &mut Neighbours,
12569 at: (usize, usize),
12570 bw: usize,
12571 bh: usize,
12572 y: &mut PlaneBuf<'static>,
12573 u: &mut PlaneBuf<'static>,
12574 v: &mut PlaneBuf<'static>,
12575 enable_filter_intra: bool,
12576 allow_screen_content_tools: bool,
12577 base_q_idx: u8,
12578 tx_select: bool,
12579 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12580) -> Result<()> {
12581 let (r, c) = at;
12582 let (px, py) = (c * SUB, r * SUB);
12583 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12584 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12585 let palette_uv_cache = neighbours.palette_uv_cache(at);
12586 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12587 read_intra_mode_rect(
12588 dec,
12589 cdfs,
12590 nb_above_mode,
12591 nb_left_mode,
12592 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
12593 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
12594 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
12595 // correct), CFL must never be offered here -- passing `true`
12596 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
12597 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
12598 // from this block's very first symbol (lane-sbpart r3 bisect).
12599 false,
12600 true,
12601 bw,
12602 bh,
12603 enable_filter_intra,
12604 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12605 allow_screen_content_tools,
12606 Some((palette_ctx, &palette_cache)),
12607 &palette_uv_cache,
12608 r * (SUB / MI),
12609 c * (SUB / MI), fctx,
12610 )?;
12611 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
12612 // lane-t900 r34: a non-skip palette block on a superblock-level strip
12613 // -- counted so its gate cannot go vacuous (this was a refusal until
12614 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
12615 // decodes_pixel_exact`).
12616 hit!(PALETTE_SB_STRIP_HITS);
12617 }
12618 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12619 if smooth_neighbor {
12620 hit!(SMOOTH_LUMA_HITS);
12621 }
12622 let smooth_neighbor_uv =
12623 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
12624 if filter_intra.is_some() {
12625 // `filter_intra_size_class_rect` already returns `None` for both
12626 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
12627 // 32 on both axes), so this symbol is never read at this level --
12628 // kept only as the same defensive refusal [`decode_block_rect`] has.
12629 return Err(unsupported(
12630 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
12631 av1_filter_intra_allowed_bsize caps at 32x32)",
12632 ));
12633 }
12634 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12635 DC_PRED
12636 } else {
12637 uv_mode
12638 };
12639 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12640 let depth = if tx_select {
12641 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
12642 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
12643 // the 16x4 intra-in-inter strips already do); the key frame's
12644 // deblock-grid approximation is only right where those bands were never
12645 // written. Measured on the 10-bit 1920x792 128-superblock stream,
12646 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12647 // `tx_size_cat2` row 1 where libaom reads row 2.
12648 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12649 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
12650 } else {
12651 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12652 };
12653 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
12654 // counts `sub_tx_size_map` steps from the block's own max rect
12655 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
12656 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
12657 // steps, so this level's category is 3 (the same one a 64x64 square
12658 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
12659 // here was a wrong-table read of a real symbol.
12660 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
12661 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12662 eprintln!(
12663 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
12664 dec.debug_state().0
12665 );
12666 }
12667 d
12668 } else {
12669 0
12670 };
12671 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12672 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12673 publish_txfm_bands_if_in_inter(
12674 neighbours,
12675 (mi_r, mi_c),
12676 depth_to_tx_wh(bw, bh, depth, fctx),
12677 (bw, bh), fctx,
12678 );
12679 if depth != 0 || lossless(fctx) {
12680 hit!(TX_DEPTH_HITS);
12681 // lane-rectsplit r1/r4: the superblock-level strip splits its
12682 // transform through the very same per-unit path as its 32x32-level
12683 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
12684 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
12685 // measured the old square formula mis-tiling exactly that strip).
12686 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12687 if bw.max(bh) / bw.min(bh) == 4 {
12688 let which = if depth == 1 {
12689 &RECT4_SPLIT_DEPTH1_HITS
12690 } else {
12691 &RECT4_SPLIT_DEPTH2_HITS
12692 };
12693 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12694 }
12695 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12696 eprintln!(
12697 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12698 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12699 angle_y={angle_delta_y}"
12700 );
12701 }
12702 let modes = RectStripModes {
12703 skip,
12704 mode,
12705 angle_delta_y,
12706 uv_predict_mode,
12707 angle_delta_uv,
12708 alpha,
12709 filter_intra,
12710 smooth_neighbor,
12711 smooth_neighbor_uv,
12712 palette_y: palette_y
12713 .as_ref()
12714 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12715 palette_uv: palette_uv.as_ref().map(|p| {
12716 (
12717 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12718 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12719 )
12720 }),
12721 };
12722 if palette_y.is_some() || palette_uv.is_some() {
12723 hit!(PALETTE_SPLIT_TX_HITS);
12724 }
12725 decode_rect_split(
12726 dec,
12727 cdfs,
12728 neighbours,
12729 (mi_r, mi_c),
12730 bw,
12731 bh,
12732 tx_w,
12733 tx_h,
12734 &modes,
12735 y,
12736 u,
12737 v,
12738 base_q_idx,
12739 reduced_tx_set, fctx,
12740 )?;
12741 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
12742 // (lane-palette2 r10): this return skips the fn's own tail, so a
12743 // split-tx superblock strip would otherwise leave the above/left
12744 // palette arrays holding a dead block's colours.
12745 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12746 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12747 let (puv_size, puv_colors) =
12748 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12749 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12750 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
12751 // return skips the fn's own tail, so a SPLIT superblock-level strip
12752 // published no TXFM_CONTEXT band and the next block read the row's init
12753 // value 64 as its left transform height. Measured on the 10-bit
12754 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
12755 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
12756 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
12757 // bands carry the SPLIT unit's size, not the block's.
12758 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12759 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
12760 hit!(RECT_PARTITION_HITS);
12761 return Ok(());
12762 }
12763 let (tx_w, tx_h) = (bw, bh);
12764 let (cpx, cpy) = (px / 2, py / 2);
12765 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12766 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12767 if let Some(ref pyv) = palette_y {
12768 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12769 set_palette_pred(buf, fctx);
12770 }
12771 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12772 (
12773 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12774 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12775 )
12776 });
12777 if skip {
12778 push_intra_rect(0,
12779 px,
12780 py,
12781 bw,
12782 bh,
12783 mode,
12784 angle_delta_y,
12785 reach,
12786 &ZERO_RESIDUAL[..bw * bh],
12787 None,
12788 filter_intra,
12789 smooth_neighbor, fctx,
12790 );
12791 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12792 if let Some((ub, _)) = &palette_uv_bufs {
12793 set_palette_pred(ub.clone(), fctx);
12794 }
12795 push_intra_rect(1,
12796 cpx,
12797 cpy,
12798 chroma_w,
12799 chroma_h,
12800 uv_predict_mode,
12801 angle_delta_uv,
12802 reach,
12803 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12804 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12805 None,
12806 smooth_neighbor_uv, fctx,
12807 );
12808 if let Some((_, vb)) = &palette_uv_bufs {
12809 set_palette_pred(vb.clone(), fctx);
12810 }
12811 push_intra_rect(2,
12812 cpx,
12813 cpy,
12814 chroma_w,
12815 chroma_h,
12816 uv_predict_mode,
12817 angle_delta_uv,
12818 reach,
12819 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12820 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12821 None,
12822 smooth_neighbor_uv, fctx,
12823 );
12824 neighbours.record_rect(
12825 at,
12826 bw,
12827 bh,
12828 mode,
12829 uv_predict_mode,
12830 &[
12831 &ZERO_RESIDUAL[..bw * bh],
12832 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12833 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12834 ],
12835 );
12836 } else {
12837 let around = neighbours.around_rect(at, bw, bh);
12838 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
12839 // (see this function's own doc comment). A 64-length axis codes only
12840 // its low 32 coefficients, so the corner is `min(bw, 32)` x
12841 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
12842 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
12843 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
12844 let scan32 = default_scan(TX32);
12845 if coeff_trace_on() {
12846 let (rng, _) = dec.debug_state();
12847 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
12848 }
12849 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
12850 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
12851 read_coeffs(
12852 dec,
12853 &mut luma_coding,
12854 &scan32,
12855 0,
12856 dc_sign_ctx(around[0].2),
12857 TxType::DctDct,
12858 Some((bw, bh)),
12859 )?
12860 } else {
12861 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
12862 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
12863 // (`scan.c`) gives both the very same `default_scan_32x16` /
12864 // `default_scan_16x32` the 2:1 sizes use ("Half of the
12865 // coefficients of tx64 at higher frequencies are set to zeros. So
12866 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
12867 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
12868 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
12869 // 512-position eob group) -- BOTH identical to TX_32X16, so the
12870 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
12871 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
12872 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
12873 // what `base_ctx_rect` computes at (32, 16).
12874 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
12875 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
12876 read_coeffs_rect(
12877 dec,
12878 &mut luma_coding,
12879 luma_scan,
12880 luma_cw,
12881 luma_ch,
12882 0,
12883 dc_sign_ctx(around[0].2),
12884 TxType::DctDct,
12885 )?
12886 };
12887 if coeff_trace_on() {
12888 let (rng, _) = dec.debug_state();
12889 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
12890 }
12891 let mut luma_levels = vec![0i32; bw * bh];
12892 for row in 0..luma_ch {
12893 luma_levels[row * bw..][..luma_cw]
12894 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
12895 }
12896 {
12897 let cur = block_q_idx(fctx);
12898 if cur != i32::from(base_q_idx) {
12899 hit!(RECT64_QIDX_DRIFT_HITS);
12900 }
12901 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12902 eprintln!(
12903 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
12904 );
12905 }
12906 }
12907 let luma_residual = dequant_and_inverse_typed_wh(
12908 &luma_levels,
12909 bw,
12910 bh,
12911 crate::decode::bit_depth(fctx),
12912 block_q_idx(fctx),
12913 plane_q_delta(0, fctx).0,
12914 plane_q_delta(0, fctx).1,
12915 luma_tx_type,
12916 );
12917 push_intra_rect(0,
12918 px,
12919 py,
12920 bw,
12921 bh,
12922 mode,
12923 angle_delta_y,
12924 reach,
12925 &luma_residual,
12926 None,
12927 filter_intra,
12928 smooth_neighbor, fctx,
12929 );
12930 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12931 let leftcol: Vec<u16> = if px > 0 {
12932 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
12933 } else {
12934 vec![]
12935 };
12936 eprintln!(
12937 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
12938 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
12939 luma_corner.iter().any(|&v| v != 0),
12940 &y.data[py * y.width + px..][..bw],
12941 leftcol,
12942 );
12943 }
12944 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
12945 // corner crop needed (see doc comment).
12946 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12947 // The chroma plane is never truncated (both axes <= 32 after
12948 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
12949 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
12950 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
12951 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
12952 // set, and only the scan is new (lane-tx64x16).
12953 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
12954 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
12955 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
12956 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12957 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12958 };
12959 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12960 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12961 if coeff_trace_on() {
12962 let (rng, _) = dec.debug_state();
12963 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12964 }
12965 let (u_levels, u_tx_type) = read_coeffs_rect(
12966 dec,
12967 &mut u_coding,
12968 chroma_scan,
12969 chroma_w,
12970 chroma_h,
12971 u_skip_ctx,
12972 dc_sign_ctx(around[1].2),
12973 TxType::DctDct,
12974 )?;
12975 if coeff_trace_on() {
12976 let (rng, _) = dec.debug_state();
12977 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
12978 }
12979 {
12980 let cur = block_q_idx(fctx);
12981 if cur != i32::from(base_q_idx) {
12982 hit!(RECT64_QIDX_DRIFT_HITS);
12983 }
12984 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12985 eprintln!(
12986 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
12987 );
12988 }
12989 }
12990 let u_residual = dequant_and_inverse_typed_wh(
12991 &u_levels,
12992 chroma_w,
12993 chroma_h,
12994 crate::decode::bit_depth(fctx),
12995 block_q_idx(fctx),
12996 plane_q_delta(1, fctx).0,
12997 plane_q_delta(1, fctx).1,
12998 u_tx_type,
12999 );
13000 // lane-t900 r34: the UV-palette prediction override, exactly as the
13001 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
13002 // set-then-take, so it must be filled again right before each plane's
13003 // own reconstruct; leaving this out of the non-skip arm predicted a
13004 // palette block's chroma off its block edges (measured: testsrc2
13005 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
13006 // luma exact, both chroma planes wrong over its whole 16x32).
13007 if let Some((ub, _)) = &palette_uv_bufs {
13008 set_palette_pred(ub.clone(), fctx);
13009 }
13010 push_intra_rect(1,
13011 cpx,
13012 cpy,
13013 chroma_w,
13014 chroma_h,
13015 uv_predict_mode,
13016 angle_delta_uv,
13017 reach,
13018 &u_residual,
13019 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13020 None,
13021 smooth_neighbor_uv, fctx,
13022 );
13023 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
13024 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
13025 if coeff_trace_on() {
13026 let (rng, _) = dec.debug_state();
13027 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
13028 }
13029 let (v_levels, v_tx_type) = read_coeffs_rect(
13030 dec,
13031 &mut v_coding,
13032 chroma_scan,
13033 chroma_w,
13034 chroma_h,
13035 v_skip_ctx,
13036 dc_sign_ctx(around[2].2),
13037 TxType::DctDct,
13038 )?;
13039 if coeff_trace_on() {
13040 let (rng, _) = dec.debug_state();
13041 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
13042 }
13043 {
13044 let cur = block_q_idx(fctx);
13045 if cur != i32::from(base_q_idx) {
13046 hit!(RECT64_QIDX_DRIFT_HITS);
13047 }
13048 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13049 eprintln!(
13050 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
13051 );
13052 }
13053 }
13054 let v_residual = dequant_and_inverse_typed_wh(
13055 &v_levels,
13056 chroma_w,
13057 chroma_h,
13058 crate::decode::bit_depth(fctx),
13059 block_q_idx(fctx),
13060 plane_q_delta(2, fctx).0,
13061 plane_q_delta(2, fctx).1,
13062 v_tx_type,
13063 );
13064 if let Some((_, vb)) = &palette_uv_bufs {
13065 set_palette_pred(vb.clone(), fctx);
13066 }
13067 push_intra_rect(2,
13068 cpx,
13069 cpy,
13070 chroma_w,
13071 chroma_h,
13072 uv_predict_mode,
13073 angle_delta_uv,
13074 reach,
13075 &v_residual,
13076 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13077 None,
13078 smooth_neighbor_uv, fctx,
13079 );
13080 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
13081 hit!(RECT_COEFF_HITS);
13082 }
13083 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
13084 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
13085 let (puv_size, puv_colors) =
13086 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
13087 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
13088 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
13089 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
13090 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
13091 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
13092 // frame): the above row records `tx_size_wide` over the block's width and
13093 // the left column `tx_size_high` over its height. This 1:4 strip reader is
13094 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
13095 // and it published neither band -- so the block after a 64x16 strip read
13096 // the row's init value 64 as its left transform height and took
13097 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
13098 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
13099 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
13100 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13101 hit!(SB_RECT_HITS);
13102 match (bw, bh) {
13103 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
13104 (16, 64) => hit!(SB_RECT4_VERT_HITS),
13105 _ => {}
13106 }
13107 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13108 let (rng, _) = dec.debug_state();
13109 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
13110 }
13111 Ok(())
13112}
13113
13114/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
13115/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
13116/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
13117/// it lands away from zero, for gate tests to prove a real stream fired one.
13118fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
13119 let symbol = dec.symbol(cdf);
13120 if symbol != ANGLE_DELTA_ZERO {
13121 hit!(ANGLE_DELTA_HITS);
13122 }
13123 symbol as i32 - ANGLE_DELTA_ZERO as i32
13124}
13125
13126#[allow(clippy::too_many_arguments)]
13127fn read_intra_mode(
13128 dec: &mut SymbolDecoder,
13129 cdfs: &mut Cdfs,
13130 above_mode: usize,
13131 left_mode: usize,
13132 cfl: bool,
13133 side: usize,
13134 enable_filter_intra: bool,
13135 skip_ctx: usize,
13136 allow_screen_content_tools: bool,
13137 allow_intrabc: bool,
13138 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
13139 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
13140 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
13141 // `None` at the excluded call sites (the 8x8-leaf path), which still read
13142 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
13143 // decoder reads either way -- but refuse by name the moment it fires,
13144 // exactly the old behaviour.
13145 palette: Option<(usize, &[u16])>,
13146 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
13147 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
13148 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
13149 // `use_palette_y`, not a neighbour lookup).
13150 palette_uv_cache: &[u16],
13151 mi_r: usize,
13152 mi_c: usize, fctx: &crate::decode::FrameCtx,
13153) -> Result<(
13154 bool,
13155 usize,
13156 i32,
13157 usize,
13158 i32,
13159 Option<(i32, i32)>,
13160 Option<usize>,
13161 Option<PaletteY>,
13162 Option<PaletteUv>,
13163)> {
13164 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
13165 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
13166 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
13167 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
13168 // line against the instrumented aomdec, not just `tell()`.
13169 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13170 if ec_istep {
13171 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
13172 // (decodemv.c:818), printed at the same point: before the first
13173 // mode-info symbol of the block, so a cross-decoder range ladder can
13174 // be keyed on the BLOCK, not just on the symbol sequence.
13175 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
13176 }
13177 macro_rules! istep {
13178 ($name:literal, $val:expr) => {
13179 if ec_istep {
13180 let (rng, _) = dec.debug_state();
13181 eprintln!(
13182 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
13183 $name, $val
13184 );
13185 }
13186 };
13187 }
13188 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
13189 // point every square caller routes through (see `read_intra_mode_rect`).
13190 let cfl = if cfl && side > 32 {
13191 hit!(NOCFL_UV_MODE_HITS);
13192 false
13193 } else {
13194 cfl
13195 };
13196 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
13197 // `skip` when `SegIdPreSkip`, and after it otherwise.
13198 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
13199 if seg_id_pre_skip(fctx) {
13200 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
13201 }
13202 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
13203 if trace {
13204 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
13205 }
13206 istep!("skip", skip as i32);
13207 if !seg_id_pre_skip(fctx) {
13208 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
13209 }
13210 // spec order (see the comment below on `read_intrabc_info`): `skip`,
13211 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
13212 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
13213 istep!("cdef", 0);
13214 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
13215 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
13216 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
13217 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
13218 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
13219 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
13220 istep!("dq", 0);
13221 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
13222 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
13223 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
13224 // intra frame whose header set `allow_intrabc`. Actual intra block copy
13225 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
13226 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
13227 // draws the line at consuming this one flag symbol and refusing by name
13228 // when it fires, so the arithmetic decoder still resyncs for a stream
13229 // that merely allows (but never uses) intrabc.
13230 if allow_intrabc {
13231 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
13232 if trace {
13233 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
13234 }
13235 if use_intrabc {
13236 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
13237 if trace {
13238 eprintln!("TRACE intrabc dv={dv:?}");
13239 }
13240 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
13241 hit!(INTRABC_HITS);
13242 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
13243 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
13244 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
13245 // `DC_PRED` (which is also what the neighbour mode contexts and
13246 // the loop filter then see).
13247 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
13248 }
13249 }
13250 let above_ctx = INTRA_MODE_CTX[above_mode];
13251 let left_ctx = INTRA_MODE_CTX[left_mode];
13252 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
13253 if trace {
13254 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
13255 }
13256 istep!("mode", mode as i32);
13257 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13258 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
13259 if trace {
13260 eprintln!(
13261 "TRACE angle_delta value={}",
13262 delta + ANGLE_DELTA_ZERO as i32
13263 );
13264 }
13265 delta
13266 } else {
13267 0
13268 };
13269 istep!("angle_y", angle_delta_y);
13270 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
13271 // here so every `decode_block` caller (64x64 and 128x128 roots included)
13272 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
13273 let cfl = cfl && cfl_allowed_px(side, side, fctx);
13274 let uv_mode = if cfl {
13275 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13276 } else {
13277 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13278 };
13279 if trace {
13280 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
13281 }
13282 istep!("uv_mode", uv_mode as i32);
13283 let alpha = if cfl && uv_mode == UV_CFL_PRED {
13284 Some(read_cfl_alphas(dec, cdfs))
13285 } else {
13286 None
13287 };
13288 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
13289 // from this lane's directional chroma: a corner block with neither
13290 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
13291 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
13292 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
13293 // bug in that fallback this lane's own scope does not cover. Keep it
13294 // refused here rather than ship a silently-wrong decode.
13295 if (9..=12).contains(&uv_mode) {
13296 hit!(SMOOTH_UV_HITS);
13297 }
13298 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
13299 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
13300 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
13301 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
13302 // the `else` branch below and never reads one either way.
13303 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13304 hit!(DIRECTIONAL_UV_HITS);
13305 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13306 } else {
13307 0
13308 };
13309 istep!("angle_uv", angle_delta_uv);
13310 if angle_delta_uv != 0 {
13311 hit!(UV_ANGLE_DELTA_HITS);
13312 }
13313 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
13314 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
13315 // gated by `av1_allow_palette` (blockd.h -- size bound only,
13316 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
13317 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
13318 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
13319 // read the same CDF row whenever every neighbour really is non-palette).
13320 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
13321 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
13322 // neighbour lookup at all), so it is exact even at the excluded call
13323 // sites once Y decodes real syntax there too.
13324 //
13325 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
13326 // inline from `read_palette_mode_info` -- it runs later, from
13327 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
13328 // after the WHOLE mode-info read for the block, including UV palette
13329 // mode_info (`read_palette_mode_info`'s own second half, right below)
13330 // and `read_filter_intra_mode_info`. So this branch now only reads
13331 // mode/size/colours for both planes (deferring the two colour-index-map
13332 // decodes to after `filter_intra`, below) -- r6's range trace pinned
13333 // this exact ordering bug (`compare-range-not-tell`: ranges matched
13334 // bit-for-bit through the Y colours, diverged only at the old inline
13335 // `decode_color_index_map` call).
13336 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13337 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13338 if allow_screen_content_tools
13339 && let Some(bsize_ctx) = palette_bsize_ctx(side)
13340 {
13341 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
13342 if mode == DC_PRED {
13343 if trace {
13344 let (rng, _) = dec.debug_state();
13345 eprintln!(
13346 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
13347 );
13348 }
13349 }
13350 let use_palette_y =
13351 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
13352 if mode == DC_PRED && trace {
13353 let (rng, _) = dec.debug_state();
13354 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
13355 }
13356 if use_palette_y {
13357 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13358 if trace {
13359 let (rng, _) = dec.debug_state();
13360 eprintln!("TRACE palette_y_size n={n} rng={rng}");
13361 }
13362 let colors = read_palette_colors_y(dec, n, cache, fctx);
13363 if trace {
13364 let (rng, _) = dec.debug_state();
13365 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
13366 }
13367 palette_y_pending = Some((n, colors));
13368 }
13369 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
13370 // unconditionally at this bit position whenever `uv_mode ==
13371 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
13372 // scope always reconstructs chroma alongside luma (`decode_block`
13373 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
13374 // is always true here and does not need threading in.
13375 let palette_uv_mode_ctx = usize::from(use_palette_y);
13376 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
13377 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13378 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
13379 palette_uv_pending = Some((n, u_colors, v_colors));
13380 }
13381 }
13382 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
13383 // `use_filter_intra` symbol this decoder never read at all until
13384 // lane-av1real r10 -- silently skipping it left every bit past a
13385 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
13386 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
13387 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
13388 // symbol's bits were never consumed).
13389 let mut filter_intra = None;
13390 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
13391 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
13392 // `use_filter_intra` symbol for a Y-palette block, and reading one here
13393 // desynced every screen-content stream from the first palette block on
13394 // (it surfaced as a bogus "partition below 8x8" refusal further down the
13395 // tile).
13396 if mode == DC_PRED
13397 && enable_filter_intra
13398 && palette_y_pending.is_none()
13399 && let Some(class) = filter_intra_size_class(side)
13400 {
13401 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
13402 if trace {
13403 eprintln!(
13404 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
13405 use_filter_intra as i32
13406 );
13407 }
13408 istep!("use_filter_intra", use_filter_intra as i32);
13409 if use_filter_intra {
13410 hit!(FILTER_INTRA_HITS);
13411 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13412 if trace {
13413 eprintln!("TRACE filter_intra_mode value={fi_mode}");
13414 }
13415 istep!("filter_intra_mode", fi_mode as i32);
13416 filter_intra = Some(fi_mode);
13417 }
13418 }
13419 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
13420 // shared U/V map) -- the same order libaom's own loop visits them in.
13421 let palette_y = palette_y_pending.map(|(n, colors)| {
13422 let map =
13423 decode_color_index_map(dec, cdfs, n, side, palette_onscreen(mi_r, mi_c, side, side, fctx), false);
13424 hit!(PALETTE_HITS);
13425 if trace {
13426 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
13427 }
13428 PaletteY { size: n, colors, map }
13429 });
13430 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13431 let on = palette_onscreen_uv(
13432 (side, side),
13433 palette_onscreen(mi_r, mi_c, side, side, fctx),
13434 (side / 2, side / 2),
13435 );
13436 let map = decode_color_index_map(dec, cdfs, n, side / 2, on, true);
13437 hit!(PALETTE_UV_HITS);
13438 if trace {
13439 eprintln!(
13440 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
13441 &u_colors[..n],
13442 &v_colors[..n]
13443 );
13444 }
13445 PaletteUv { size: n, u_colors, v_colors, map }
13446 });
13447 Ok((
13448 skip,
13449 mode,
13450 angle_delta_y,
13451 uv_mode,
13452 angle_delta_uv,
13453 alpha,
13454 filter_intra,
13455 palette_y,
13456 palette_uv,
13457 ))
13458}
13459
13460/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
13461/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
13462/// intra modes.
13463const UV_CFL_PRED: usize = 13;
13464
13465/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
13466/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
13467/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
13468/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
13469/// joint sign the same way. Returns each plane's final signed `alpha_q3`
13470/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
13471fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
13472 hit!(CFL_BLOCK_HITS);
13473 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
13474 let sign_u = ((joint_sign + 1) * 11) >> 5;
13475 let sign_v = (joint_sign + 1) - 3 * sign_u;
13476 let alpha_u = if sign_u == 0 {
13477 0
13478 } else {
13479 let ctx_u = (joint_sign + 1 - 3) as usize;
13480 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
13481 if sign_u == 2 { mag } else { -mag }
13482 };
13483 let alpha_v = if sign_v == 0 {
13484 0
13485 } else {
13486 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
13487 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
13488 if sign_v == 2 { mag } else { -mag }
13489 };
13490 (alpha_u, alpha_v)
13491}
13492
13493/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
13494/// the reconstructed luma samples under a `side`-square block, subsampled
13495/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
13496/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13497/// to give the AC values [`cfl_scaled`] scales by alpha.
13498fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13499 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13500}
13501
13502/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
13503/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
13504/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
13505/// reconstruction through THIS function rather than a second transcription of
13506/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
13507pub(crate) fn cfl_ac_q3_at(
13508 px: usize,
13509 py: usize,
13510 bw: usize,
13511 bh: usize,
13512 sample: impl Fn(usize, usize) -> i32,
13513) -> Vec<i32> {
13514 let (cw, ch) = (bw / 2, bh / 2);
13515 let mut ac = vec![0i32; cw * ch];
13516 let mut sum = 0i32;
13517 for cy in 0..ch {
13518 for cx in 0..cw {
13519 let (lx, ly) = (px + cx * 2, py + cy * 2);
13520 let q3 = (sample(lx, ly)
13521 + sample(lx + 1, ly)
13522 + sample(lx, ly + 1)
13523 + sample(lx + 1, ly + 1))
13524 << 1;
13525 ac[cy * cw + cx] = q3;
13526 sum += q3;
13527 }
13528 }
13529 let num_pel = (cw * ch) as i32;
13530 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13531 ac.iter_mut().for_each(|v| *v -= avg);
13532 ac
13533}
13534
13535/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13536/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13537/// ties away from zero on the shifted-out sign).
13538pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13539 let v = alpha_q3 * ac_q3;
13540 if v >= 0 {
13541 (v + 32) >> 6
13542 } else {
13543 -((-v + 32) >> 6)
13544 }
13545}
13546
13547/// One plane's reconstruction buffer, `width * height` samples, and the
13548/// prediction/residual reads and writes into it — the decode-side twin of
13549/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
13550/// (own-edge and reach clamps both), passing what it gathers straight to
13551/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
13552/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
13553/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
13554/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
13555/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
13556/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
13557/// lane-mc64 r1: the decode-order index the stage dumps below key their file
13558/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
13559/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
13560/// without this every frame overwrote `.f0` and a per-frame bisection silently
13561/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
13562#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
13563fn stage_dump_idx() -> usize {
13564 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
13565}
13566
13567fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
13568 use std::io::Write;
13569 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
13570 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
13571 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
13572 // not be read out at all.
13573 if let Ok(path) = crate::envflags::var(var)
13574 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13575 {
13576 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))] {
13577 for row in 0..h {
13578 let mut bytes = Vec::with_capacity(w * 2);
13579 for &s in &p.data[row * p.width..][..w] {
13580 bytes.extend_from_slice(&s.to_le_bytes());
13581 }
13582 let _ = f.write_all(&bytes);
13583 }
13584 }
13585 }
13586}
13587
13588/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
13589/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
13590/// every frame overwrote the previous one and only the LAST frame survived,
13591/// which silently defeats any per-frame filter-stage bisection.
13592fn dump_stage_idx(var: &str) -> usize {
13593 use std::collections::HashMap;
13594 use std::sync::{Mutex, OnceLock};
13595 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
13596 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
13597 let e = m.entry(var.to_string()).or_insert(0);
13598 let i = *e;
13599 *e += 1;
13600 i
13601}
13602
13603fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
13604 use std::io::Write;
13605 if let Ok(path) = crate::envflags::var(var)
13606 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13607 {
13608 for p in [y, u, v] {
13609 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
13610 let _ = f.write_all(&narrow);
13611 }
13612 }
13613}
13614
13615/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
13616/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
13617/// at most 4095), so a decode that hashes identically under the flag proves
13618/// the output does not depend on the plane buffer's initial content.
13619const PLANE_SENTINEL: u16 = 0xDEAD;
13620
13621/// A frame plane's own backing store, `n` samples, UNINITIALISED.
13622///
13623/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
13624/// by the tile walk's reconstruction before anything reads it, so the
13625/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
13626/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
13627/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
13628/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
13629/// ways (see the lane report) and the two agree, which is the proof that no
13630/// unwritten sample reaches the output.
13631fn fresh_plane(n: usize) -> Vec<u16> {
13632 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
13633 return vec![PLANE_SENTINEL; n];
13634 }
13635 let mut v: Vec<u16> = Vec::with_capacity(n);
13636 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
13637 // capacity was just reserved, so the vector owns `n` initialised-or-not
13638 // `u16` slots. Every one is written by reconstruction before it is read
13639 // (proven by the sentinel gate above).
13640 #[allow(unsafe_code)]
13641 unsafe {
13642 v.set_len(n);
13643 }
13644 v
13645}
13646
13647#[derive(Clone)]
13648struct PlaneBuf<'a> {
13649 data: std::borrow::Cow<'a, [u16]>,
13650 width: usize,
13651 height: usize,
13652 /// The frame's true, decodable extent in this plane's own units — past
13653 /// this, samples are the padded coding surface's invented tail, never a
13654 /// real decoder's edge or reach reads.
13655 true_width: usize,
13656 true_height: usize,
13657 /// This plane's own tile's top-left pixel origin (spec: intra prediction
13658 /// never reaches across a tile boundary even though an earlier-decoded
13659 /// tile's real pixels sit right there in the shared buffer) — set via
13660 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
13661 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
13662 /// is threaded (the two-tile column-split stage 1 fixture's tile always
13663 /// ends at the frame's own right/bottom edge); a non-last tile's own
13664 /// right/bottom reach bound is still open, tracked in the report.
13665 tile_x0: usize,
13666 tile_y0: usize,
13667 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
13668 /// (exclusive) -- a non-last tile column/row's own reach must stop at
13669 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
13670 /// full padded extent) for the single-tile/last-tile case, matching the
13671 /// old unclipped behaviour exactly.
13672 tile_x1: usize,
13673 tile_y1: usize,
13674}
13675
13676/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
13677/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
13678/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
13679/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13680/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13681/// `ALTREF2`/`ALTREF`).
13682
13683impl PlaneBuf<'_> {
13684 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
13685 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
13686 /// are already in this plane's own units (luma pixels for `y`, chroma
13687 /// pixels — halved — for `u`/`v`).
13688 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
13689 self.tile_x0 = x0;
13690 self.tile_y0 = y0;
13691 self.tile_x1 = x1;
13692 self.tile_y1 = y1;
13693 }
13694
13695 fn edges(
13696 &self,
13697 x: usize,
13698 y: usize,
13699 side: usize,
13700 reach: Reach,
13701 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13702 let own_across = x + side.min(self.true_width.saturating_sub(x));
13703 let across = if reach.above_right {
13704 own_across + side.min(self.true_width.saturating_sub(own_across))
13705 } else {
13706 own_across
13707 }
13708 .min(self.width)
13709 .min(self.tile_x1);
13710 let own_down = y + side.min(self.true_height.saturating_sub(y));
13711 let down = if reach.below_left {
13712 own_down + side.min(self.true_height.saturating_sub(own_down))
13713 } else {
13714 own_down
13715 }
13716 .min(self.height)
13717 .min(self.tile_y1);
13718 let above = (y > self.tile_y0 && across > x)
13719 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13720 let left = (x > self.tile_x0 && down > y).then(|| {
13721 (y..down)
13722 .map(|row| self.data[row * self.width + x - 1])
13723 .collect::<Vec<_>>()
13724 });
13725 let corner =
13726 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13727 (above, left, corner)
13728 }
13729
13730 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
13731 /// the above/left reach each extend by their OWN axis (`bw` across,
13732 /// `bh` down), not one shared `side`.
13733 fn edges_rect(
13734 &self,
13735 x: usize,
13736 y: usize,
13737 bw: usize,
13738 bh: usize,
13739 reach: Reach,
13740 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13741 let own_across = x + bw.min(self.true_width.saturating_sub(x));
13742 let across = if reach.above_right {
13743 own_across + bw.min(self.true_width.saturating_sub(own_across))
13744 } else {
13745 own_across
13746 }
13747 .min(self.width)
13748 .min(self.tile_x1);
13749 let own_down = y + bh.min(self.true_height.saturating_sub(y));
13750 let down = if reach.below_left {
13751 own_down + bh.min(self.true_height.saturating_sub(own_down))
13752 } else {
13753 own_down
13754 }
13755 .min(self.height)
13756 .min(self.tile_y1);
13757 let above = (y > self.tile_y0 && across > x)
13758 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13759 let left = (x > self.tile_x0 && down > y).then(|| {
13760 (y..down)
13761 .map(|row| self.data[row * self.width + x - 1])
13762 .collect::<Vec<_>>()
13763 });
13764 let corner =
13765 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13766 if matches!((bw, bh), (16, 8) | (8, 16)) {
13767 hit!(RECT_STRIP_PRED_HITS);
13768 if across > own_across || down > own_down {
13769 hit!(RECT_STRIP_REACH_HITS);
13770 }
13771 }
13772 (above, left, corner)
13773 }
13774
13775 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
13776 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
13777 /// already-rect-capable `(bw, bh)` pair.
13778 #[allow(clippy::too_many_arguments)]
13779 #[track_caller]
13780 fn reconstruct_rect(
13781 &mut self,
13782 x: usize,
13783 y: usize,
13784 bw: usize,
13785 bh: usize,
13786 mode: usize,
13787 angle_delta: i32,
13788 reach: Reach,
13789 residual: &[i32],
13790 cfl: Option<(i32, &[i32])>,
13791 filter_intra: Option<usize>,
13792 smooth_neighbor: bool,
13793 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13794 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13795 // than by this replay.
13796 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13797 ) {
13798 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
13799 // (lane-palette2 r4): a palette block's prediction is the
13800 // reconstructed colour-index map, needing no edge pixels at all.
13801 let prediction = if let Some(buf) = pred {
13802 buf
13803 } else {
13804 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
13805 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
13806 eprintln!(
13807 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
13808 above.as_ref().map(|a| (a.len(), a[0])),
13809 left.as_ref().map(|l| l.len()),
13810 left.as_ref().map(|l| l[0]),
13811 self.tile_x0, self.tile_y0, self.true_width, self.true_height
13812 );
13813 }
13814 let mut prediction = vec![0u16; bw * bh];
13815 if let Some(fi_mode) = filter_intra {
13816 crate::intra::predict_filter_intra(
13817 fi_mode,
13818 above.as_deref(),
13819 left.as_deref(),
13820 corner,
13821 bw,
13822 bh,
13823 &mut prediction, fctx,
13824 );
13825 } else {
13826 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13827 predict(
13828 mode as u8,
13829 angle_delta,
13830 above.as_deref(),
13831 left.as_deref(),
13832 corner,
13833 bw,
13834 bh,
13835 enable_edge_filter,
13836 smooth_neighbor,
13837 &mut prediction, fctx,
13838 );
13839 }
13840 prediction
13841 };
13842 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13843 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13844 if crate::envflags::env_flag!("EC_PRED") {
13845 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13846 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
13847 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
13848 eprintln!(
13849 "@{} 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)
13850 );
13851 }
13852 let residual = dense_residual(residual, bw * bh);
13853 for row in 0..bh {
13854 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
13855 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
13856 // whose padded width is not superblock aligned hangs past it.
13857 if y + row >= self.height {
13858 break;
13859 }
13860 for col in 0..bw {
13861 if x + col >= self.width {
13862 break;
13863 }
13864 let idx = row * bw + col;
13865 let mut base = i32::from(prediction[idx]);
13866 if let Some((alpha_q3, ac_q3)) = cfl {
13867 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13868 }
13869 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13870 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13871 }
13872 }
13873 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
13874 // -- a block whose prediction matches the oracle's but whose written
13875 // samples do not is either a residual defect or a later overwrite, and
13876 // only this print separates the two.
13877 if crate::envflags::env_flag!("EC_PRED") {
13878 let row0: Vec<u16> =
13879 (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect();
13880 let col0: Vec<u16> =
13881 (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect();
13882 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
13883 }
13884 }
13885
13886 /// Predicts under `mode` then adds `residual` (side*side, raster),
13887 /// writing the clamped reconstruction back into the plane at `(x, y)`.
13888 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
13889 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
13890 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
13891 /// order (cfl.c).
13892 #[track_caller]
13893 fn reconstruct(
13894 &mut self,
13895 x: usize,
13896 y: usize,
13897 side: usize,
13898 mode: usize,
13899 angle_delta: i32,
13900 reach: Reach,
13901 residual: &[i32],
13902 cfl: Option<(i32, &[i32])>,
13903 filter_intra: Option<usize>,
13904 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
13905 // libaom `get_filt_type`): true when the block's above OR left
13906 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
13907 // Callers pass their own plane's neighbour-mode check
13908 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
13909 // callers until a smooth/paeth `uv_mode` can reach this call at all
13910 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
13911 // keeps `false` exact for chroma without this fn needing to know why.
13912 smooth_neighbor: bool,
13913 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13914 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13915 // than by this replay.
13916 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13917 ) {
13918 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
13919 // takes priority over `predict()`/`predict_filter_intra` entirely --
13920 // palette prediction needs no edge pixels at all.
13921 let prediction = if let Some(buf) = pred {
13922 buf
13923 } else {
13924 let (above, left, corner) = self.edges(x, y, side, reach);
13925 let mut prediction = vec![0u16; side * side];
13926 if let Some(fi_mode) = filter_intra {
13927 crate::intra::predict_filter_intra(
13928 fi_mode,
13929 above.as_deref(),
13930 left.as_deref(),
13931 corner,
13932 side,
13933 side,
13934 &mut prediction, fctx,
13935 );
13936 } else {
13937 // `enable_intra_edge_filter` is the sequence header's own flag
13938 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
13939 // call, never per-block) -- threading it through every
13940 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
13941 // dozen sites for a value that never changes mid-decode, so it
13942 // rides a thread-local instead (this decoder is single-threaded
13943 // per stream).
13944 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13945 predict(
13946 mode as u8,
13947 angle_delta,
13948 above.as_deref(),
13949 left.as_deref(),
13950 corner,
13951 side,
13952 side,
13953 enable_edge_filter,
13954 smooth_neighbor,
13955 &mut prediction, fctx,
13956 );
13957 }
13958 prediction
13959 };
13960 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13961 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13962 if crate::envflags::env_flag!("EC_PRED") {
13963 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13964 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
13965 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
13966 eprintln!(
13967 "@{} 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)
13968 );
13969 }
13970 let residual = dense_residual(residual, side * side);
13971 for row in 0..side {
13972 // lane-sb128c r8: libaom's frame buffer is superblock
13973 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
13974 // transform unit of a 128x64 block at the BOTTOM frame edge
13975 // can hang past the last padded row (1920x792: a unit at
13976 // y=768 wants 832 rows of an 800-row buffer, which panicked
13977 // the film's key frames). Those samples are outside the
13978 // frame: never output, and no block below ever references
13979 // them.
13980 if y + row >= self.height {
13981 break;
13982 }
13983 for col in 0..side {
13984 if x + col >= self.width {
13985 break;
13986 }
13987 let idx = row * side + col;
13988 let mut base = i32::from(prediction[idx]);
13989 if let Some((alpha_q3, ac_q3)) = cfl {
13990 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13991 }
13992 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13993 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13994 }
13995 }
13996 }
13997}
13998
13999/// Reads one plane's transform block, reconstructs it into `plane` at
14000/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
14001#[allow(clippy::too_many_arguments)]
14002fn read_plane(
14003 dec: &mut SymbolDecoder,
14004 cdfs: &mut Cdfs,
14005 set: TxbSet,
14006 scan: &[u16],
14007 plane_idx: usize,
14008 around: (bool, bool, i32),
14009 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
14010 // it for every plane's `txb` lookup (it is what an intra transform type's
14011 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
14012 tx_mode: usize,
14013 predict_mode: usize,
14014 angle_delta: i32,
14015 reach: Reach,
14016 // lane-wave1 step (i): unread -- this reader records its write
14017 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
14018 // stays in the signature so every call site still proves the plane is
14019 // exclusively held while its coefficients are parsed.
14020 _plane: &mut PlaneBuf<'static>,
14021 x: usize,
14022 y: usize,
14023 side: usize,
14024 tx_side: usize,
14025 base_q_idx: u8,
14026 cfl: Option<(i32, CflSrc)>,
14027 filter_intra: Option<usize>,
14028 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
14029 // smaller than its own block (spec `get_txb_ctx_general`'s
14030 // `plane_bsize != tx_size` branch), carrying the already-looked-up
14031 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
14032 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
14033 // formula below.
14034 luma_skip_ctx: Option<usize>,
14035 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
14036 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
14037) -> Result<Grid> {
14038 let skip_ctx = if plane_idx == 0 {
14039 luma_skip_ctx.unwrap_or(0)
14040 } else {
14041 // libaom `get_txb_ctx`: a chroma unit's context is
14042 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
14043 // plane block is bigger than the transform. Our chroma tables hold the
14044 // offset-7 rows first, so the caller adds 3 for the bigger-block case
14045 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
14046 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
14047 };
14048 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
14049 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
14050 // not by the block's ordinary `mode` (which is always DC_PRED whenever
14051 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
14052 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
14053 // filter-intra in AV1).
14054 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
14055 let mut coding = cdfs.txb(set, tx_mode);
14056 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
14057 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
14058 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
14059 // plane of a lossless block (the residual then goes through the WHT, so
14060 // the type only picks the scan, which is the default one).
14061 if lossless(fctx) {
14062 coding.tx_type = None;
14063 }
14064 // Luma's `default_tx_type` is only a fallback for the sizes whose
14065 // `TxbSet` carries no symbol at all (32-point and up), which the spec
14066 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
14067 // *never* its own coded symbol (`coding.tx_type` is always `None` for
14068 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
14069 // the plane's own predicted mode (`default_intra_tx_type`) -- except
14070 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
14071 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
14072 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
14073 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
14074 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
14075 // narrows there — only `Chroma32` and up do).
14076 let default_tx_type = if plane_idx == 0 || side >= 32 {
14077 TxType::DctDct
14078 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
14079 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
14080 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
14081 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
14082 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
14083 // [`read_inter_plane`]'s own `side < 32` guard).
14084 inherited
14085 } else {
14086 default_intra_tx_type(predict_mode as u8)
14087 };
14088 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
14089 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
14090 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
14091 let (grid, tx_type) = read_coeffs(
14092 dec,
14093 &mut coding,
14094 scan,
14095 skip_ctx,
14096 dc_sign_ctx(around.2),
14097 default_tx_type,
14098 None,
14099 )?;
14100 note_chroma_class1(plane_idx, tx_type);
14101 if plane_idx == 0 {
14102 fctx.luma_tx_type.with(|c| c.set(tx_type));
14103 }
14104 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
14105 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
14106 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
14107 // guard also assumes.
14108 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
14109 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
14110 // keyed by that true size, not the coded corner's -- so the corner
14111 // goes into the top-left of a `side`-sized grid, not the reverse.
14112 let levels = extend_corner(grid, tx_side, tx_side, side, side);
14113 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
14114 let tx = TxParams {
14115 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
14116 ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
14117 };
14118 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14119 let residual = tx.run(&levels);
14120 eprintln!(
14121 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
14122 );
14123 }
14124 push_intra_tx(
14125 plane_idx,
14126 x,
14127 y,
14128 side,
14129 side,
14130 false,
14131 predict_mode,
14132 angle_delta,
14133 reach,
14134 tx,
14135 &levels,
14136 cfl,
14137 filter_intra,
14138 smooth_neighbor, fctx,
14139 );
14140 // `record`'s neighbour state only reads whether *the coded grid* (not the
14141 // residual) has nonzero entries, so the levels this function already
14142 // built are what it wants back -- both arms of the old `tx_side == side`
14143 // branch returned exactly that, one of them through a full `to_vec` copy
14144 // of the grid per intra transform unit (lane-coefbuf).
14145 Ok(levels)
14146}
14147
14148/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
14149/// three planes, reconstructing them into `y`/`u`/`v` and updating
14150/// `neighbours`.
14151#[allow(clippy::too_many_arguments)]
14152fn decode_block(
14153 dec: &mut SymbolDecoder,
14154 cdfs: &mut Cdfs,
14155 neighbours: &mut Neighbours,
14156 at: (usize, usize),
14157 side: usize,
14158 luma_set: TxbSet,
14159 chroma_set: TxbSet,
14160 luma_tx: usize,
14161 chroma_tx: usize,
14162 scans: (&[u16], &[u16]),
14163 cfl: bool,
14164 y: &mut PlaneBuf<'static>,
14165 u: &mut PlaneBuf<'static>,
14166 v: &mut PlaneBuf<'static>,
14167 base_q_idx: u8,
14168 enable_filter_intra: bool,
14169 allow_screen_content_tools: bool,
14170 allow_intrabc: bool,
14171 scan32: &[u16],
14172 scan16: &[u16],
14173 scan8: &[u16],
14174 scan4: &[u16],
14175 tx_select: bool,
14176 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14177) -> Result<()> {
14178 // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
14179 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
14180 // tables/scans are replaced by the 4x4 ones and the block always takes the
14181 // multi-transform-unit path below.
14182 let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
14183 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
14184 } else {
14185 (luma_set, chroma_set, luma_tx, chroma_tx, scans)
14186 };
14187 let (r, c) = at;
14188 let (px, py) = (c * SUB, r * SUB);
14189 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14190 let palette_uv_cache = neighbours.palette_uv_cache(at);
14191 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14192 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
14193 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14194 read_intra_mode(
14195 dec,
14196 cdfs,
14197 nb_above_mode,
14198 nb_left_mode,
14199 cfl,
14200 side,
14201 enable_filter_intra,
14202 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14203 allow_screen_content_tools,
14204 allow_intrabc,
14205 Some((palette_ctx, &palette_cache)),
14206 &palette_uv_cache,
14207 r * (SUB / MI),
14208 c * (SUB / MI), fctx,
14209 )?;
14210 if at_tile_left && palette_y.is_some() {
14211 hit!(PALETTE_TILE_LEFT_HITS);
14212 }
14213 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
14214 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
14215 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
14216 // actual chroma-from-luma correlation, same as this decoder always did.
14217 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14218 DC_PRED
14219 } else {
14220 uv_mode
14221 };
14222 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14223 if smooth_neighbor {
14224 hit!(SMOOTH_LUMA_HITS);
14225 }
14226 let smooth_neighbor_uv =
14227 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
14228 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14229 eprintln!(
14230 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
14231 angle_delta_uv={angle_delta_uv}"
14232 );
14233 }
14234 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14235 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
14236 // block, skipped or not. `logical_tx` is what the loop filter's edge
14237 // lookup and the next block's own `tx_size_context` want (the *nominal*
14238 // transform size -- 64 even for the 64x64 corner-scanned case, spec
14239 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
14240 // which only differs from it at that one corner case.
14241 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
14242 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
14243 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
14244 // intrabc block reads NO tx-size symbol at all -- it takes
14245 // `maxRectTxSize` -- while every ordinary skipped intra block does read
14246 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
14247 // the tile from that block on (class `equal-range-means-unread`).
14248 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
14249 // tree instead (`read_var_tx_size`), the same syntax the inter block path
14250 // has always read -- libaom's `parse_decode_block` dispatches on
14251 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
14252 // intrabc block as inter.
14253 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
14254 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
14255 let intrabc_leaves = if intrabc_vartx {
14256 let max_tx = side.min(64);
14257 // `max_block_wide`/`max_block_high`: the frame's own mi grid
14258 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
14259 // right/bottom edge reads no split symbol for the units outside it.
14260 let mi_cols = 2 * y.true_width.div_ceil(8);
14261 let mi_rows = 2 * y.true_height.div_ceil(8);
14262 let side_mi = side / MI;
14263 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
14264 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
14265 let mut leaves = Vec::new();
14266 for row in (0..side_mi).step_by(max_tx / MI) {
14267 for col in (0..side_mi).step_by(max_tx / MI) {
14268 read_var_tx_size(
14269 dec, cdfs, neighbours, (mi_r, mi_c), side,
14270 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
14271 );
14272 }
14273 }
14274 hit!(INTRABC_VARTX_HITS);
14275 // The luma reconstruct loop below is a UNIFORM grid of one square
14276 // transform (the intra `tx_depth` shape), so a tree that resolved to
14277 // mixed leaf sizes is refused by name rather than reconstructed at the
14278 // wrong stride.
14279 let uniform = leaves
14280 .first()
14281 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
14282 if !uniform {
14283 return Err(unsupported(
14284 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
14285 ));
14286 }
14287 Some(leaves[0].2)
14288 } else {
14289 None
14290 };
14291 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
14292 (tx, if tx == 64 { 32 } else { tx })
14293 } else if tx_select && !intrabc_skip_tx {
14294 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
14295 (resolved, if resolved == 64 { 32 } else { resolved })
14296 } else {
14297 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
14298 // TX_64X64, so a 128x128 block is always FOUR luma transform units
14299 // even with `tx_select` off -- the TU loop below, never the
14300 // single-unit path.
14301 (lossless_tx(side.min(64), fctx), luma_tx)
14302 };
14303 if tx_select && logical_tx < side && uv_mode != DC_PRED {
14304 hit!(SQ_CHROMA_TX_HITS);
14305 }
14306 let luma_set = if tx_select {
14307 txbset_for(logical_tx, reduced_tx_set)
14308 } else {
14309 luma_set
14310 };
14311 let luma_set = if intrabc_dv.is_some() {
14312 txbset_for_inter(logical_tx, reduced_tx_set)
14313 } else {
14314 luma_set
14315 };
14316 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
14317 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
14318 let (cpx, cpy) = (px / 2, py / 2);
14319 let chroma_side = side / 2;
14320 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
14321 // frame's own pre-loop-filter reconstruction (all loop filters are off
14322 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
14323 // block vector, with the BILINEAR kernel libaom forces for intrabc --
14324 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
14325 // odd, which is exactly what the bilinear taps then interpolate.
14326 flush_recon(fctx, y, u, v);
14327 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14328 let mut yb = vec![0u16; side * side];
14329 mc::predict_with_filter(
14330 &y.data, y.width, y.true_width, y.true_height,
14331 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14332 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14333 );
14334 let mut ub = vec![0u16; chroma_side * chroma_side];
14335 mc::predict_with_filter(
14336 &u.data, u.width, u.true_width, u.true_height,
14337 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14338 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14339 );
14340 let mut vb = vec![0u16; chroma_side * chroma_side];
14341 mc::predict_with_filter(
14342 &v.data, v.width, v.true_width, v.true_height,
14343 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14344 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14345 );
14346 (yb, ub, vb)
14347 });
14348 // A palette-Y block's own prediction is the reconstructed colour-index
14349 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
14350 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
14351 // parameter through this function's dozen `y.reconstruct`/`read_plane`
14352 // sites. A split luma transform (`tx_select && logical_tx != side`)
14353 // would need the map sliced per-TU -- untested against a real
14354 // `--enable-palette=1` stream this round, so refuse by name rather than
14355 // guess at the slicing (charter's own named-acceptable fallback).
14356 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
14357 py.map
14358 .iter()
14359 .map(|&idx| py.colors[idx as usize])
14360 .collect()
14361 });
14362 // lane-t900 r32: the intrabc luma prediction rides the very same
14363 // whole-block override slot, so the multi-TU loop below windows it per
14364 // transform unit exactly like a palette map -- setting it once up front
14365 // handed the whole `side`x`side` buffer to the FIRST unit and left every
14366 // later one predicting off block edges (the var-tx tree above is what
14367 // first makes `logical_tx < side` reachable for an intrabc block).
14368 let palette_y_buf = match &intrabc_bufs {
14369 Some((yb, _, _)) => Some(yb.clone()),
14370 None => palette_y_buf,
14371 };
14372 // With one luma transform unit the whole `side`x`side` map is the
14373 // prediction; with several (`logical_tx != side`) each unit takes its own
14374 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
14375 // below (lane-palette2 r7) -- setting the full-block buffer here would be
14376 // taken by the FIRST unit and indexed at the wrong stride.
14377 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
14378 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
14379 // `split_tx_skip` walk), so its map must be armed here even when the
14380 // transform is split. Gating the arm on `logical_tx == side` alone left a
14381 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
14382 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
14383 // key frame; class override-slot-on-one-arm). Neither prediction is
14384 // edge-derived, so the whole-block buffer at the block's own stride is
14385 // exactly what that single call wants.
14386 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
14387 // that reaches this block apart from one that never does (class
14388 // gate-blind-to-feature).
14389 if palette_y_buf.is_some() && skip && logical_tx < side {
14390 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
14391 }
14392 if let Some(buf) = &palette_y_buf
14393 && (logical_tx == side || skip)
14394 {
14395 set_palette_pred(buf.clone(), fctx);
14396 }
14397 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
14398 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
14399 // plane's own `reconstruct`/`read_plane` call below (never both planes at
14400 // once), since Y's own set-then-take already emptied the slot by the time
14401 // either of these run.
14402 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14403 (
14404 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
14405 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
14406 )
14407 });
14408 // The chroma half of the intrabc prediction rides the same per-plane
14409 // override slot the UV-palette buffers do (set fresh before each plane's
14410 // own `reconstruct`/`read_plane` call below).
14411 let palette_uv_bufs = match &intrabc_bufs {
14412 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
14413 None => palette_uv_bufs,
14414 };
14415 if skip {
14416 // A skipped block codes no residual syntax at all (spec 5.11.34):
14417 // straight prediction, on every plane.
14418 //
14419 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
14420 // is skipped (only an INTER skip forces the largest transform), and
14421 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
14422 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
14423 // already written left/above of it inside this same block. Predicting
14424 // the whole `side`x`side` at once gives a different (uniformly off by
14425 // ~1) answer, which is exactly the residue this lane was chasing.
14426 // The palette/intrabc override path keeps the single-call shape (its
14427 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
14428 // untested for skip and unreachable in these streams).
14429 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
14430 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
14431 // per-unit prediction is keyed on the transform being smaller than
14432 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
14433 // narrower meaning (a READ split tx depth).
14434 let split_tx_skip =
14435 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
14436 if split_tx_skip {
14437 if tx_select {
14438 hit!(SKIP_SPLIT_TX_HITS);
14439 }
14440 let n_axis = side / logical_tx;
14441 for tu_row in 0..n_axis {
14442 for tu_col in 0..n_axis {
14443 let tu_px = px + tu_col * logical_tx;
14444 let tu_py = py + tu_row * logical_tx;
14445 if tu_px >= y.true_width || tu_py >= y.true_height {
14446 continue;
14447 }
14448 let tu_reach = tu_reach(
14449 side,
14450 side,
14451 tu_col * logical_tx,
14452 tu_row * logical_tx,
14453 logical_tx,
14454 reach,
14455 px,
14456 py,
14457 y.width,
14458 y.height, fctx,
14459 );
14460 push_intra(0,
14461 tu_px,
14462 tu_py,
14463 logical_tx,
14464 mode,
14465 angle_delta_y,
14466 tu_reach,
14467 &ZERO_RESIDUAL[..logical_tx * logical_tx],
14468 None,
14469 filter_intra,
14470 smooth_neighbor, fctx,
14471 );
14472 }
14473 }
14474 } else {
14475 push_intra(0,
14476 px,
14477 py,
14478 side,
14479 mode,
14480 angle_delta_y,
14481 reach,
14482 &ZERO_RESIDUAL[..side * side],
14483 None,
14484 filter_intra,
14485 smooth_neighbor, fctx,
14486 );
14487 }
14488 let ac = alpha.map(|_| cfl_src(px, py, side));
14489 let cn = (chroma_side / chroma_tx).max(1);
14490 for cu_row in 0..cn {
14491 for cu_col in 0..cn {
14492 let luma_span = chroma_tx * 2;
14493 let cu_r = if cn == 1 {
14494 reach
14495 } else {
14496 tu_reach(
14497 side, side,
14498 cu_col * luma_span, cu_row * luma_span, luma_span,
14499 reach, px, py, y.width, y.height, fctx,
14500 )
14501 };
14502 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14503 if let Some((ub, _)) = &palette_uv_bufs {
14504 set_palette_pred(ub.clone(), fctx);
14505 }
14506 push_intra(1,
14507 cu_x,
14508 cu_y,
14509 chroma_tx,
14510 uv_predict_mode,
14511 angle_delta_uv,
14512 cu_r,
14513 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14514 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14515 None,
14516 smooth_neighbor_uv, fctx,
14517 );
14518 if let Some((_, vb)) = &palette_uv_bufs {
14519 set_palette_pred(vb.clone(), fctx);
14520 }
14521 push_intra(2,
14522 cu_x,
14523 cu_y,
14524 chroma_tx,
14525 uv_predict_mode,
14526 angle_delta_uv,
14527 cu_r,
14528 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14529 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14530 None,
14531 smooth_neighbor_uv, fctx,
14532 );
14533 }
14534 }
14535 let luma_grid = vec![0i32; side * side];
14536 let u_grid = vec![0i32; chroma_side * chroma_side];
14537 let v_grid = vec![0i32; chroma_side * chroma_side];
14538 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14539 } else if logical_tx == side {
14540 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
14541 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
14542 // that arm was redundant -- and wrong at 128, where
14543 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
14544 // block is four units whether or not `tx_select` is on.
14545 // A single luma transform unit -- the old path, unchanged (including
14546 // the 64x64 corner case, `logical_tx == side == 64` with
14547 // `coeff_tx_side == 32`).
14548 let around = neighbours.around(at, side);
14549 let luma_grid = read_plane(
14550 dec,
14551 cdfs,
14552 luma_set,
14553 luma_scan,
14554 0,
14555 around[0],
14556 mode,
14557 mode,
14558 angle_delta_y,
14559 reach,
14560 y,
14561 px,
14562 py,
14563 side,
14564 coeff_tx_side,
14565 base_q_idx,
14566 None,
14567 filter_intra,
14568 None,
14569 smooth_neighbor, fctx,
14570 )?;
14571 let ac = alpha.map(|_| cfl_src(px, py, side));
14572 // Armed for exactly this block's two chroma reads (see
14573 // [`INTRABC_CHROMA_TX`]); the luma call above just set
14574 // [`LUMA_TX_TYPE`] to the type it coded.
14575 if intrabc_dv.is_some() {
14576 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14577 }
14578 if let Some((ub, _)) = &palette_uv_bufs {
14579 set_palette_pred(ub.clone(), fctx);
14580 }
14581 let u_grid = read_plane(
14582 dec,
14583 cdfs,
14584 chroma_set,
14585 scans.1,
14586 1,
14587 around[1],
14588 mode,
14589 uv_predict_mode,
14590 angle_delta_uv,
14591 reach,
14592 u,
14593 cpx,
14594 cpy,
14595 chroma_side,
14596 chroma_tx,
14597 base_q_idx,
14598 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14599 None,
14600 None,
14601 smooth_neighbor_uv, fctx,
14602 )?;
14603 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14604 eprintln!(
14605 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
14606 &u.data[cpy * u.width + cpx..][..chroma_side]
14607 );
14608 }
14609 if let Some((_, vb)) = &palette_uv_bufs {
14610 set_palette_pred(vb.clone(), fctx);
14611 }
14612 let v_grid = read_plane(
14613 dec,
14614 cdfs,
14615 chroma_set,
14616 scans.1,
14617 2,
14618 around[2],
14619 mode,
14620 uv_predict_mode,
14621 angle_delta_uv,
14622 reach,
14623 v,
14624 cpx,
14625 cpy,
14626 chroma_side,
14627 chroma_tx,
14628 base_q_idx,
14629 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14630 None,
14631 None,
14632 smooth_neighbor_uv, fctx,
14633 )?;
14634 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14635 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14636 } else {
14637 // Several luma transform units, raster order (spec
14638 // `transform_block`'s loop): the block's resolved transform is
14639 // genuinely smaller than its own side, so each tile of it predicts
14640 // and codes independently, its own context read fresh off whatever
14641 // the earlier tiles in this same block already wrote -- the same
14642 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
14643 let n_axis = side / logical_tx;
14644 let cn = (chroma_side / chroma_tx).max(1);
14645 // libaom's transform-block loop is over 64x64 luma "mu" chunks
14646 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
14647 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
14648 // before moving to the next one. Below 128 a block is a single chunk,
14649 // so this is byte-for-byte the all-luma-then-all-chroma order that has
14650 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
14651 // and reading all four luma units first desyncs the tile at the second
14652 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
14653 let nchunk = (side / 64).max(1);
14654 // `cn > 1` means the uv plane block is larger than the uv transform,
14655 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
14656 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
14657 let tpc = (n_axis / nchunk).max(1);
14658 let cpc = (cn / nchunk).max(1);
14659 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14660 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
14661 for ch_row in 0..nchunk {
14662 for ch_col in 0..nchunk {
14663 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14664 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14665 let tu_mi = (
14666 mi_r + tu_row * (logical_tx / MI),
14667 mi_c + tu_col * (logical_tx / MI),
14668 );
14669 let tu_px = px + tu_col * logical_tx;
14670 let tu_py = py + tu_row * logical_tx;
14671 // Same libaom clip as `decode_rect_split`'s loop above; a
14672 // square block only hangs off the frame when the frame's mi
14673 // dimensions are odd at the block's own level.
14674 if tu_px >= y.true_width || tu_py >= y.true_height {
14675 continue;
14676 }
14677 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14678 // A transform unit inside a block is NOT a block at that
14679 // position (lane-palette2 r12): `Reach::of` granted the
14680 // top-right 8x8 unit of a 16x16 D203 block bottom-left
14681 // pixels libaom refuses outright (`col_off > 0`), which is
14682 // the diagonal wedge seed 46 reconstructed wrong.
14683 let tu_reach = tu_reach(
14684 side,
14685 side,
14686 tu_col * logical_tx,
14687 tu_row * logical_tx,
14688 logical_tx,
14689 reach,
14690 px,
14691 py,
14692 y.width,
14693 y.height, fctx,
14694 );
14695 // This transform unit's own bsize (`logical_tx`) is smaller
14696 // than the block it sits in (`side`), so `txb_skip_ctx` is
14697 // the neighbour-magnitude table, not the lone-TU 0 (spec
14698 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
14699 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14700 if let Some(buf) = &palette_y_buf {
14701 hit!(PALETTE_SPLIT_TX_HITS);
14702 let mut window = vec![0u16; logical_tx * logical_tx];
14703 for row in 0..logical_tx {
14704 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
14705 window[row * logical_tx..][..logical_tx]
14706 .copy_from_slice(&buf[src..][..logical_tx]);
14707 }
14708 set_palette_pred(window, fctx);
14709 }
14710 let tu_grid = read_plane(
14711 dec,
14712 cdfs,
14713 luma_set,
14714 luma_scan,
14715 0,
14716 tu_around,
14717 mode,
14718 mode,
14719 angle_delta_y,
14720 tu_reach,
14721 y,
14722 tu_px,
14723 tu_py,
14724 logical_tx,
14725 // The unit's own COEFFICIENT grid, half its side at
14726 // TX_64X64 (a 64-point transform codes nothing past 32);
14727 // identical to `logical_tx` at every smaller size
14728 // (lane-sb128b r1).
14729 coeff_tx_side,
14730 base_q_idx,
14731 None,
14732 filter_intra,
14733 Some(tu_skip_ctx),
14734 smooth_neighbor, fctx,
14735 )?;
14736 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14737 eprintln!(
14738 "TRACE tu_bitpos mi=({},{}) tell={}",
14739 tu_mi.0,
14740 tu_mi.1,
14741 dec.debug_bitpos()
14742 );
14743 }
14744 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14745 }
14746 }
14747 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
14748 // this still runs after every luma unit of the block.
14749 let ac = alpha.map(|_| cfl_src(px, py, side));
14750 // The block's uv plane block is `chroma_side` across but its uv
14751 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
14752 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
14753 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
14754 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
14755 // FOUR units (lane-sb128b r2) -- one per mu chunk.
14756 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
14757 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
14758 // the chunk, then every V unit. At one unit per plane per chunk --
14759 // every non-lossless case this decoder reaches -- that is the same
14760 // symbol order as the interleaved pair this loop used to read; a
14761 // lossless frame's 4x4 chroma units are the case where it differs
14762 // (lane-lossless2).
14763 let mut u_pass: Vec<Grid> = Vec::new();
14764 for plane_pass in 1..=2usize {
14765 let mut pass_idx = 0usize;
14766 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
14767 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
14768 // The chroma context arrays are indexed in LUMA mi, so this
14769 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
14770 // pixels span `2 * chroma_tx` luma ones.
14771 let luma_span = chroma_tx * 2;
14772 let cu_mi = (
14773 mi_r + cu_row * (luma_span / MI),
14774 mi_c + cu_col * (luma_span / MI),
14775 );
14776 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14777 let cu_reach = if cn == 1 {
14778 reach
14779 } else {
14780 tu_reach(
14781 side, side,
14782 cu_col * luma_span, cu_row * luma_span, luma_span,
14783 reach, px, py, y.width, y.height, fctx,
14784 )
14785 };
14786 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14787 if let Some((ub, vb)) = &palette_uv_bufs {
14788 let pbuf = if plane_pass == 1 { ub } else { vb };
14789 set_palette_pred(
14790 palette_window(
14791 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
14792 chroma_tx, chroma_tx,
14793 ),
14794 fctx,
14795 );
14796 }
14797 let buf: &mut PlaneBuf<'static> =
14798 if plane_pass == 1 { &mut *u } else { &mut *v };
14799 let cu_grid = read_plane(
14800 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
14801 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
14802 chroma_tx, chroma_tx, base_q_idx,
14803 alpha.zip(ac).map(|((au, av), ac)| {
14804 (if plane_pass == 1 { au } else { av }, ac)
14805 }),
14806 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14807 )?;
14808 if cn > 1 {
14809 hit!(CHROMA_SPLIT_TX_HITS);
14810 // Immediately, so the NEXT unit of this same block reads
14811 // this one's coefficient context (libaom's chroma
14812 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
14813 // 1 from this left neighbour -- measured against aomdec).
14814 // The same writes are replayed after `record_split_luma`
14815 // below, which would otherwise clobber them whole-block.
14816 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
14817 }
14818 if plane_pass == 1 {
14819 u_pass.push(cu_grid);
14820 } else {
14821 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
14822 if cn > 1 {
14823 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
14824 }
14825 last_grids = [u_grid, cu_grid];
14826 }
14827 pass_idx += 1;
14828 }
14829 }
14830 }
14831 }
14832 }
14833 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
14834 // context write; at `cn > 1` the per-unit writes above are what the
14835 // next block reads, so they run after this (last writer wins).
14836 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
14837 for (cu_mi, luma_span, u_grid, v_grid) in &units {
14838 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
14839 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
14840 }
14841 }
14842 // Unconditional, `size == 0` for a non-palette block: clears any stale
14843 // neighbour palette state the same way [`Neighbours::record`] always
14844 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
14845 // (the split-luma-TU branch above always refuses before reaching here
14846 // when `palette_y` is `Some`, so it is never live for that branch).
14847 let (py_size, py_colors) = palette_y
14848 .as_ref()
14849 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14850 neighbours.record_palette_y(at, side, py_size, py_colors);
14851 let (puv_size, puv_colors) = palette_uv
14852 .as_ref()
14853 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14854 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
14855 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
14856 neighbours.fill_lf_grid(
14857 (r * (SUB / MI), c * (SUB / MI)),
14858 side / MI,
14859 logical_tx as u8,
14860 0, fctx,
14861 );
14862 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
14863 // `decode_block`, key frames included, and the intrabc var-tx read above
14864 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
14865 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
14866 // row. Armed by the frame's own `allow_intrabc` so every other key frame
14867 // (whose readers use the deblock-grid approximation) is untouched.
14868 if allow_intrabc {
14869 set_txfm_ctxs(
14870 neighbours,
14871 (mi_r, mi_c),
14872 logical_tx,
14873 side / MI,
14874 side / MI,
14875 skip && intrabc_dv.is_some(),
14876 );
14877 }
14878 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
14879 Ok(())
14880}
14881
14882thread_local! {
14883 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
14884 /// root's HORZ arm, and 64x128 ones at its VERT arm.
14885 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14886 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14887 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
14888 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
14889 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
14890 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
14891 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
14892 /// inter frame) -- (128x64, 64x128).
14893 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
14894 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
14895 /// handed back var-tx leaves, so the per-transform-unit luma publication
14896 /// loop never ran and the block has to clear its own luma coefficient
14897 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
14898 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
14899 /// non-vacuous.
14900 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14901}
14902
14903/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
14904pub fn skip_vartx_luma_reset_hits() -> usize {
14905 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
14906}
14907
14908/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
14909pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
14910 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
14911}
14912
14913/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
14914/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
14915pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
14916 (
14917 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
14918 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
14919 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
14920 )
14921}
14922
14923/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
14924/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
14925/// `decode_inter_block`'s own rect path).
14926///
14927/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
14928/// transform unit, with the 128-specific geometry:
14929/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
14930/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
14931/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
14932/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
14933/// same CDF a 64x64 square block reads).
14934/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
14935/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
14936/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
14937/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
14938/// a chunk before moving to the next (the interleave lane-sb128b r3
14939/// measured at the 128x128 NONE root).
14940/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
14941/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
14942/// No CfL, no filter intra (both cap at 32x32) and no palette
14943/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
14944/// reader's own size gates already say so, and the guard below is defensive.
14945#[allow(clippy::too_many_arguments)]
14946fn decode_block_128rect(
14947 dec: &mut SymbolDecoder,
14948 cdfs: &mut Cdfs,
14949 neighbours: &mut Neighbours,
14950 at: (usize, usize),
14951 bw: usize,
14952 bh: usize,
14953 y: &mut PlaneBuf<'static>,
14954 u: &mut PlaneBuf<'static>,
14955 v: &mut PlaneBuf<'static>,
14956 base_q_idx: u8,
14957 enable_filter_intra: bool,
14958 allow_screen_content_tools: bool,
14959 tx_select: bool,
14960 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14961) -> Result<()> {
14962 let (r, c) = at;
14963 let (px, py) = (c * SUB, r * SUB);
14964 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14965 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14966 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14967 let palette_uv_cache = neighbours.palette_uv_cache(at);
14968 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14969 read_intra_mode_rect(
14970 dec,
14971 cdfs,
14972 nb_above_mode,
14973 nb_left_mode,
14974 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
14975 // 13-symbol no-CFL CDF here, never the 14-symbol one.
14976 false,
14977 true,
14978 bw,
14979 bh,
14980 enable_filter_intra,
14981 neighbours.skip_txfm_ctx(mi_r, mi_c),
14982 allow_screen_content_tools,
14983 Some((palette_ctx, &palette_cache)),
14984 &palette_uv_cache,
14985 mi_r,
14986 mi_c, fctx,
14987 )?;
14988 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
14989 return Err(unsupported(
14990 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
14991 their size gates caps at 64x64 or below, so none of these symbols exists there)",
14992 ));
14993 }
14994 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14995 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14996 if smooth_neighbor {
14997 hit!(SMOOTH_LUMA_HITS);
14998 }
14999 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
15000 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
15001 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
15002 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
15003 let depth = if tx_select {
15004 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
15005 // the real `TXFM_CONTEXT` bands, and compares them against
15006 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
15007 // every 128-axis block, hence the `min(64)`.
15008 let ctx = if in_inter {
15009 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
15010 } else {
15011 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
15012 };
15013 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
15014 } else {
15015 0
15016 };
15017 if depth != 0 {
15018 hit!(TX_DEPTH_HITS);
15019 }
15020 hit_do! {
15021 INTRA_SB128_DEPTH_HITS.with(|c| {
15022 let mut h = c.get();
15023 h[depth.min(2)] += 1;
15024 c.set(h);
15025 });
15026 }
15027 let logical_tx = 64 >> depth;
15028 // A 64-point transform codes nothing past its low 32 coefficients.
15029 let coeff_tx_side = logical_tx.min(32);
15030 let luma_set = txbset_for(logical_tx, reduced_tx_set);
15031 let luma_scan = default_scan(coeff_tx_side);
15032 let chroma_tx = 32;
15033 let chroma_scan = default_scan(chroma_tx);
15034 let (cpx, cpy) = (px / 2, py / 2);
15035 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
15036 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15037 let (nch_x, nch_y) = (bw / 64, bh / 64);
15038 // One 32x32 chroma unit per mu chunk, per plane.
15039 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
15040 let tpc = 64 / logical_tx;
15041 let zero_tu = vec![0i32; logical_tx * logical_tx];
15042 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
15043 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
15044 let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new();
15045 for ch_row in 0..nch_y {
15046 for ch_col in 0..nch_x {
15047 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
15048 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
15049 let tu_mi = (
15050 mi_r + tu_row * (logical_tx / MI),
15051 mi_c + tu_col * (logical_tx / MI),
15052 );
15053 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
15054 // libaom clips the transform loop to
15055 // `max_blocks_wide/high`: a unit whose top-left sample is
15056 // outside the frame is never coded.
15057 if tu_px >= y.true_width || tu_py >= y.true_height {
15058 continue;
15059 }
15060 // Edge availability of a unit INSIDE a block, with the
15061 // 128 geometry -- `has_top_right` is false for a block
15062 // whose largest side is > 64, which [`Reach::of_rect`]
15063 // already answered for the block and [`tu_reach`] carries
15064 // down to the units on its own top row.
15065 let tu_r = tu_reach(
15066 bw,
15067 bh,
15068 tu_col * logical_tx,
15069 tu_row * logical_tx,
15070 logical_tx,
15071 reach,
15072 px,
15073 py,
15074 y.width,
15075 y.height, fctx,
15076 );
15077 if skip {
15078 push_intra(0,
15079 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
15080 None, smooth_neighbor, fctx,
15081 );
15082 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
15083 continue;
15084 }
15085 // The unit is smaller than its block, so `txb_skip_ctx`
15086 // is the neighbour-magnitude table, never the lone-TU 0.
15087 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
15088 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
15089 let tu_grid = read_plane(
15090 dec,
15091 cdfs,
15092 luma_set,
15093 &luma_scan,
15094 0,
15095 tu_around,
15096 mode,
15097 mode,
15098 angle_delta_y,
15099 tu_r,
15100 y,
15101 tu_px,
15102 tu_py,
15103 logical_tx,
15104 coeff_tx_side,
15105 base_q_idx,
15106 None,
15107 None,
15108 Some(tu_skip_ctx),
15109 smooth_neighbor, fctx,
15110 )?;
15111 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
15112 }
15113 }
15114 // The chroma context arrays are indexed in LUMA mi, so this
15115 // unit's anchor is its own 64x64 mu chunk.
15116 let luma_span = chroma_tx * 2;
15117 let cu_mi = (
15118 mi_r + ch_row * (luma_span / MI),
15119 mi_c + ch_col * (luma_span / MI),
15120 );
15121 let cu_r = tu_reach(
15122 bw,
15123 bh,
15124 ch_col * luma_span,
15125 ch_row * luma_span,
15126 luma_span,
15127 reach,
15128 px,
15129 py,
15130 y.width,
15131 y.height, fctx,
15132 );
15133 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
15134 if skip {
15135 push_intra(1,
15136 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
15137 None, smooth_neighbor_uv, fctx,
15138 );
15139 push_intra(2,
15140 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
15141 None, smooth_neighbor_uv, fctx,
15142 );
15143 continue;
15144 }
15145 let cu_around = neighbours.around_mi(cu_mi, luma_span);
15146 let u_grid = read_plane(
15147 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
15148 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
15149 Some(3), smooth_neighbor_uv, fctx,
15150 )?;
15151 let v_grid = read_plane(
15152 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
15153 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
15154 Some(3), smooth_neighbor_uv, fctx,
15155 )?;
15156 hit!(CHROMA_SPLIT_TX_HITS);
15157 // Immediately, so the NEXT unit of this same block reads this
15158 // one's coefficient context; replayed after `record_split_luma_rect`
15159 // below, which would otherwise clobber them whole-block.
15160 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
15161 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
15162 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
15163 last_grids = [u_grid, v_grid];
15164 }
15165 }
15166 if skip {
15167 neighbours.record_rect(
15168 at,
15169 bw,
15170 bh,
15171 mode,
15172 uv_predict_mode,
15173 &[
15174 &ZERO_RESIDUAL[..bw * bh],
15175 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15176 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15177 ],
15178 );
15179 } else {
15180 neighbours.record_split_luma_rect(
15181 at,
15182 bw,
15183 bh,
15184 mode,
15185 uv_predict_mode,
15186 [&last_grids[0], &last_grids[1]],
15187 );
15188 for (cu_mi, u_grid, v_grid) in &units {
15189 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
15190 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
15191 }
15192 }
15193 // No palette exists at this size; the unconditional stamp clears any
15194 // stale neighbour palette state, as every other block path does.
15195 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
15196 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
15197 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15198 neighbours.fill_lf_grid_rect(
15199 (mi_r, mi_c),
15200 bw / MI,
15201 bh / MI,
15202 logical_tx as u8,
15203 logical_tx as u8,
15204 0, fctx,
15205 );
15206 if in_inter {
15207 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
15208 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
15209 // inter frame, intra ones included: an intra block stamps its
15210 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
15211 // A key frame has no var-tx tree and its readers use the deblock grid,
15212 // so this is the inter path's alone.
15213 txfm_partition_update_rect(
15214 neighbours,
15215 (mi_r, mi_c),
15216 (logical_tx, logical_tx),
15217 (bw, bh),
15218 );
15219 hit_do! {
15220 INTRA128_IN_INTER_HITS.with(|c| {
15221 let mut h = c.get();
15222 h[usize::from(bw < bh)] += 1;
15223 c.set(h);
15224 });
15225 }
15226 } else if bw > bh {
15227 hit!(INTRA_SB128_HORZ_HITS);
15228 } else {
15229 hit!(INTRA_SB128_VERT_HITS);
15230 }
15231 Ok(())
15232}
15233
15234
15235/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
15236/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
15237/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
15238/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
15239/// just-decoded mode, not the enclosing slot's stale one, is the true
15240/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
15241/// units, which is what its coefficient context (finer than [`SUB`]) is read
15242/// at. Returns the mode this leaf decoded, for the caller's own
15243/// `prev_leaf`/final mode-writeback bookkeeping.
15244#[allow(clippy::too_many_arguments)]
15245/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
15246/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
15247/// `above_mode[col]`, and its true above neighbour is the mi directly above
15248/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
15249/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
15250/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
15251/// (bottom-right) into both, as this path did, is right only when all four
15252/// leaves happen to share a mode. `done` may be short at the true frame edge
15253/// (the straddle caller filters positions off the frame), so each side falls
15254/// back to the last leaf actually decoded.
15255fn write_back_split_modes(
15256 neighbours: &mut Neighbours,
15257 done: &[((usize, usize), usize)],
15258 parent_mi: (usize, usize),
15259 slot: (usize, usize),
15260) {
15261 let (sr, sc) = slot;
15262 let Some(&(_, last)) = done.last() else {
15263 return;
15264 };
15265 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
15266 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
15267 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
15268}
15269
15270fn decode_leaf8(
15271 dec: &mut SymbolDecoder,
15272 cdfs: &mut Cdfs,
15273 neighbours: &mut Neighbours,
15274 outer_at: (usize, usize),
15275 leaf_mi: (usize, usize),
15276 scans: (&[u16], &[u16]),
15277 prev_leaf: Option<((usize, usize), usize)>,
15278 y: &mut PlaneBuf<'static>,
15279 u: &mut PlaneBuf<'static>,
15280 v: &mut PlaneBuf<'static>,
15281 base_q_idx: u8,
15282 enable_filter_intra: bool,
15283 allow_screen_content_tools: bool,
15284 allow_intrabc: bool,
15285 tx_select: bool,
15286 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15287) -> Result<usize> {
15288 let (r, c) = outer_at;
15289 // lane-modectx r1: the group's own availability-correct fallback pair, not
15290 // the raw coarse bands (which leak across a tile edge -- see
15291 // `modes_above_left`).
15292 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
15293 if let Some(((pr, pc), pmode)) = prev_leaf {
15294 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15295 above_mode = pmode;
15296 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15297 left_mode = pmode;
15298 }
15299 }
15300 // The mi-exact neighbour wins over both the coarse 16x16 slot and
15301 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
15302 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
15303 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
15304 // lane-rectsplitx r2 swept this arm into
15305 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
15306 // "no neighbour" at a tile edge, where the coarse cell holds the block
15307 // above/left of it inside the same 16x16.
15308 let (above_mode, left_mode) =
15309 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15310 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15311 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
15312 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
15313 // this leaf's `smooth_neighbor` is built from -- passing `false` here
15314 // filtered a directional chroma block's edge at the wrong strength
15315 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
15316 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
15317 // with the coarse [`SUB`] slot as the fallback when no block recorded
15318 // that exact mi cell.
15319 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15320 if smooth_neighbor {
15321 hit!(SMOOTH_LUMA_HITS);
15322 }
15323 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
15324 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
15325 // `decode_block` caller at 16x16 and up.
15326 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
15327 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
15328 // `read_palette_mode_info`), at its REAL mi position -- passing
15329 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
15330 // moment a real 8x8 palette block fired, which is where every 8-bit
15331 // `--tune-content=screen --min-partition-size=8` stream stopped.
15332 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
15333 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
15334 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
15335 read_intra_mode(
15336 dec,
15337 cdfs,
15338 above_mode,
15339 left_mode,
15340 true,
15341 8,
15342 enable_filter_intra,
15343 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15344 allow_screen_content_tools,
15345 allow_intrabc,
15346 Some((palette_ctx, &palette_cache)),
15347 &palette_uv_cache,
15348 leaf_mi.0,
15349 leaf_mi.1, fctx,
15350 )?;
15351 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
15352 // `read_intra_mode` and then decoded the block as if it were ordinary
15353 // intra. libaom's `is_inter_block` counts an intrabc block
15354 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
15355 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
15356 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
15357 // same value with a different interval, so the tile desynced at the very
15358 // next symbol (class `wrong-alphabet-same-value`). Everything below
15359 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
15360 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
15361 if intrabc_dv.is_some() {
15362 hit!(LEAF8_INTRABC_HITS);
15363 }
15364 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
15365 // index map, mapped through the base colours, IS the block's prediction --
15366 // carried to the next `reconstruct`/`read_plane` through the same
15367 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
15368 let palette_y_buf: Option<Vec<u16>> = palette_y
15369 .as_ref()
15370 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15371 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15372 (
15373 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15374 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15375 )
15376 });
15377 let (pal_y_size, pal_y_colors) =
15378 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15379 let (pal_uv_size, pal_uv_colors) =
15380 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15381 if palette_y.is_some() || palette_uv.is_some() {
15382 hit!(PALETTE_LEAF8_HITS);
15383 }
15384 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15385 DC_PRED
15386 } else {
15387 uv_mode
15388 };
15389 neighbours.above_uv_mode[c] = uv_predict_mode;
15390 neighbours.left_uv_mode[r] = uv_predict_mode;
15391 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15392 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
15393 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
15394 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
15395 // transform units, same raster-order per-TU pattern `decode_block`'s
15396 // multi-TU branch runs).
15397 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
15398 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
15399 // intrabc block, so a SKIPPED one takes the largest transform and an
15400 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
15401 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
15402 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
15403 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
15404 let mut leaves = Vec::new();
15405 let mi_cols = 2 * y.true_width.div_ceil(8);
15406 let mi_rows = 2 * y.true_height.div_ceil(8);
15407 read_var_tx_size(
15408 dec,
15409 cdfs,
15410 neighbours,
15411 leaf_mi,
15412 8,
15413 (
15414 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
15415 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
15416 ),
15417 (8, 8),
15418 0,
15419 0,
15420 0,
15421 &mut leaves,
15422 );
15423 hit!(INTRABC_VARTX_HITS);
15424 leaves.first().map_or(8, |l| l.2)
15425 } else if tx_select && intrabc_dv.is_none() {
15426 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
15427 } else {
15428 // lane-lossless: TX_4X4 on a lossless frame, no symbol
15429 // (libaom `read_tx_size`).
15430 lossless_tx(8, fctx)
15431 };
15432 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15433 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
15434 let (cpx, cpy) = (px / 2, py / 2);
15435 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
15436 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
15437 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
15438 // the full-pel block vector, with the BILINEAR kernel libaom forces.
15439 flush_recon(fctx, y, u, v);
15440 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
15441 let mut yb = vec![0u16; 8 * 8];
15442 mc::predict_with_filter(
15443 &y.data, y.width, y.true_width, y.true_height,
15444 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
15445 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
15446 );
15447 let mut ub = vec![0u16; 4 * 4];
15448 mc::predict_with_filter(
15449 &u.data, u.width, u.true_width, u.true_height,
15450 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15451 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
15452 );
15453 let mut vb = vec![0u16; 4 * 4];
15454 mc::predict_with_filter(
15455 &v.data, v.width, v.true_width, v.true_height,
15456 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15457 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
15458 );
15459 (yb, ub, vb)
15460 });
15461 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
15462 // `decode_block` uses: set fresh right before each plane's own
15463 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
15464 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
15465 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
15466 // first shape that reaches that loop with an override set).
15467 let palette_y_buf = match &intrabc_bufs {
15468 Some((yb, _, _)) => Some(yb.clone()),
15469 None => palette_y_buf,
15470 };
15471 let (luma_grid, u_grid, v_grid);
15472 if skip {
15473 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
15474 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
15475 // transform units, each off the units already written left/above of
15476 // it inside this same leaf -- an intra block's transform size is read
15477 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
15478 // A palette block's prediction is the whole-block index map, never
15479 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
15480 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
15481 // even when `tx_depth` resolved to TX_4X4.
15482 if resolved == 4 && palette_y_buf.is_none() {
15483 hit!(SKIP_SPLIT_TX_HITS);
15484 for tu_row in 0..2 {
15485 for tu_col in 0..2 {
15486 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
15487 if tu_px >= y.true_width || tu_py >= y.true_height {
15488 continue;
15489 }
15490 let tu_reach = tu_reach(
15491 8,
15492 8,
15493 tu_col * 4,
15494 tu_row * 4,
15495 4,
15496 reach,
15497 px,
15498 py,
15499 y.width,
15500 y.height, fctx,
15501 );
15502 push_intra(0,
15503 tu_px,
15504 tu_py,
15505 4,
15506 mode,
15507 angle_delta_y,
15508 tu_reach,
15509 &ZERO_RESIDUAL[..16],
15510 None,
15511 filter_intra,
15512 smooth_neighbor, fctx,
15513 );
15514 }
15515 }
15516 } else {
15517 if let Some(buf) = &palette_y_buf {
15518 set_palette_pred(buf.clone(), fctx);
15519 }
15520 push_intra(0,
15521 px,
15522 py,
15523 8,
15524 mode,
15525 angle_delta_y,
15526 reach,
15527 &ZERO_RESIDUAL[..64],
15528 None,
15529 filter_intra,
15530 smooth_neighbor, fctx,
15531 );
15532 }
15533 let ac = alpha.map(|_| cfl_src(px, py, 8));
15534 if let Some((_, ub, _)) = &intrabc_bufs {
15535 set_palette_pred(ub.clone(), fctx);
15536 } else if let Some((ub, _)) = &palette_uv_bufs {
15537 set_palette_pred(ub.clone(), fctx);
15538 }
15539 push_intra(1,
15540 cpx,
15541 cpy,
15542 4,
15543 uv_predict_mode,
15544 angle_delta_uv,
15545 reach,
15546 &ZERO_RESIDUAL[..16],
15547 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15548 None,
15549 smooth_neighbor_uv, fctx,
15550 );
15551 if let Some((_, _, vb)) = &intrabc_bufs {
15552 set_palette_pred(vb.clone(), fctx);
15553 } else if let Some((_, vb)) = &palette_uv_bufs {
15554 set_palette_pred(vb.clone(), fctx);
15555 }
15556 push_intra(2,
15557 cpx,
15558 cpy,
15559 4,
15560 uv_predict_mode,
15561 angle_delta_uv,
15562 reach,
15563 &ZERO_RESIDUAL[..16],
15564 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15565 None,
15566 smooth_neighbor_uv, fctx,
15567 );
15568 luma_grid = Grid::Zero(64);
15569 u_grid = Grid::Zero(16);
15570 v_grid = Grid::Zero(16);
15571 } else if resolved != 4 {
15572 let around = neighbours.around_mi(leaf_mi, 8);
15573 if let Some(buf) = &palette_y_buf {
15574 set_palette_pred(buf.clone(), fctx);
15575 }
15576 luma_grid = read_plane(
15577 dec,
15578 cdfs,
15579 if intrabc_dv.is_some() {
15580 txbset_for_inter(8, reduced_tx_set)
15581 } else if reduced_tx_set {
15582 TxbSet::Luma8
15583 } else {
15584 TxbSet::Luma8Set1
15585 },
15586 scans.0,
15587 0,
15588 around[0],
15589 mode,
15590 mode,
15591 angle_delta_y,
15592 reach,
15593 y,
15594 px,
15595 py,
15596 8,
15597 TX8,
15598 base_q_idx,
15599 None,
15600 filter_intra,
15601 None,
15602 smooth_neighbor, fctx,
15603 )?;
15604 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
15605 // an intrabc block's chroma tx_type is the colocated LUMA transform's
15606 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
15607 if intrabc_dv.is_some() {
15608 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15609 }
15610 let ac = alpha.map(|_| cfl_src(px, py, 8));
15611 if let Some((_, ub, _)) = &intrabc_bufs {
15612 set_palette_pred(ub.clone(), fctx);
15613 } else if let Some((ub, _)) = &palette_uv_bufs {
15614 set_palette_pred(ub.clone(), fctx);
15615 }
15616 u_grid = read_plane(
15617 dec,
15618 cdfs,
15619 TxbSet::Chroma4,
15620 scans.1,
15621 1,
15622 around[1],
15623 mode,
15624 uv_predict_mode,
15625 angle_delta_uv,
15626 reach,
15627 u,
15628 cpx,
15629 cpy,
15630 4,
15631 TX4,
15632 base_q_idx,
15633 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15634 None,
15635 None,
15636 smooth_neighbor_uv, fctx,
15637 )?;
15638 if let Some((_, _, vb)) = &intrabc_bufs {
15639 set_palette_pred(vb.clone(), fctx);
15640 } else if let Some((_, vb)) = &palette_uv_bufs {
15641 set_palette_pred(vb.clone(), fctx);
15642 }
15643 v_grid = read_plane(
15644 dec,
15645 cdfs,
15646 TxbSet::Chroma4,
15647 scans.1,
15648 2,
15649 around[2],
15650 mode,
15651 uv_predict_mode,
15652 angle_delta_uv,
15653 reach,
15654 v,
15655 cpx,
15656 cpy,
15657 4,
15658 TX4,
15659 base_q_idx,
15660 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15661 None,
15662 None,
15663 smooth_neighbor_uv, fctx,
15664 )?;
15665 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
15666 // two chroma reads (`decode_block`'s own tail does the same) -- left
15667 // set, every later chroma block would inherit this luma tx_type,
15668 // which picks the scan and the inverse transform.
15669 fctx.intrabc_chroma_tx.with(|c| c.set(None));
15670 } else {
15671 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
15672 // grid of 4x4 transform units, each predicted from the leaf's own
15673 // 8x8 `mode` and reading its own fresh context off the earlier
15674 // units in this same leaf (the same per-TU pattern `decode_block`'s
15675 // multi-TU branch runs at bigger blocks).
15676 for tu_row in 0..2 {
15677 for tu_col in 0..2 {
15678 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15679 let tu_px = px + tu_col * 4;
15680 let tu_py = py + tu_row * 4;
15681 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15682 if crate::encode::Reach::in_vert_ab() {
15683 hit!(VERT_AB_TX4_HITS);
15684 }
15685 let tu_reach = tu_reach(
15686 8,
15687 8,
15688 tu_col * 4,
15689 tu_row * 4,
15690 4,
15691 reach,
15692 px,
15693 py,
15694 y.width,
15695 y.height, fctx,
15696 );
15697 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15698 // Each 4x4 unit predicts from its own window of the block's
15699 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
15700 // 16x16 and up) -- the whole-block buffer would be taken by
15701 // the FIRST unit and indexed at the wrong stride.
15702 if let Some(buf) = &palette_y_buf {
15703 hit!(PALETTE_SPLIT_TX_HITS);
15704 let mut window = vec![0u16; 16];
15705 for row in 0..4 {
15706 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
15707 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
15708 }
15709 set_palette_pred(window, fctx);
15710 }
15711 let tu_grid = read_plane(
15712 dec,
15713 cdfs,
15714 if intrabc_dv.is_some() {
15715 txbset_for_inter(4, reduced_tx_set)
15716 } else if reduced_tx_set {
15717 TxbSet::Luma4
15718 } else {
15719 TxbSet::Luma4Set1
15720 },
15721 scans.1,
15722 0,
15723 tu_around,
15724 mode,
15725 mode,
15726 angle_delta_y,
15727 tu_reach,
15728 y,
15729 tu_px,
15730 tu_py,
15731 4,
15732 4,
15733 base_q_idx,
15734 None,
15735 filter_intra,
15736 Some(tu_skip_ctx),
15737 smooth_neighbor, fctx,
15738 )?;
15739 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15740 eprintln!(
15741 "TRACE tu_bitpos mi=({},{}) tell={}",
15742 tu_mi.0,
15743 tu_mi.1,
15744 dec.debug_bitpos()
15745 );
15746 }
15747 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15748 }
15749 }
15750 let ac = alpha.map(|_| cfl_src(px, py, 8));
15751 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15752 if let Some((ub, _)) = &palette_uv_bufs {
15753 set_palette_pred(ub.clone(), fctx);
15754 }
15755 u_grid = read_plane(
15756 dec,
15757 cdfs,
15758 TxbSet::Chroma4,
15759 scans.1,
15760 1,
15761 chroma_around[1],
15762 mode,
15763 uv_predict_mode,
15764 angle_delta_uv,
15765 reach,
15766 u,
15767 cpx,
15768 cpy,
15769 4,
15770 TX4,
15771 base_q_idx,
15772 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15773 None,
15774 None,
15775 smooth_neighbor_uv, fctx,
15776 )?;
15777 if let Some((_, vb)) = &palette_uv_bufs {
15778 set_palette_pred(vb.clone(), fctx);
15779 }
15780 v_grid = read_plane(
15781 dec,
15782 cdfs,
15783 TxbSet::Chroma4,
15784 scans.1,
15785 2,
15786 chroma_around[2],
15787 mode,
15788 uv_predict_mode,
15789 angle_delta_uv,
15790 reach,
15791 v,
15792 cpx,
15793 cpy,
15794 4,
15795 TX4,
15796 base_q_idx,
15797 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15798 None,
15799 None,
15800 smooth_neighbor_uv, fctx,
15801 )?;
15802 // `record_split_luma` expects a `record`-style `(r, c)` position in
15803 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
15804 // already in mi units, so calling it here double-scaled the
15805 // position. Plane 0 is already correct per-TU from the
15806 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
15807 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
15808 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
15809 // leaf's own 8x8 side over `MI`).
15810 let side_mi = 2;
15811 for cell in 0..side_mi {
15812 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
15813 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
15814 }
15815 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15816 let bound_h = round_up_even(neighbours.mi_rows);
15817 let bound_w = round_up_even(neighbours.mi_cols);
15818 let u_state = neighbour_state(&u_grid);
15819 let v_state = neighbour_state(&v_grid);
15820 for cell in 0..side_mi {
15821 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15822 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15823 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15824 }
15825 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15826 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15827 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15828 }
15829 }
15830 // This leaf's own palette state into the mi-granular above/left bands
15831 // (sizes 0 when it used none, which is what clears a previous block's
15832 // palette out of the next block's ctx and colour cache).
15833 {
15834 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15835 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15836 }
15837 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15838 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
15839 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15840 // own copy; only an intrabc var-tx read consumes these bands on the intra
15841 // path, so the write is armed by `allow_intrabc`.
15842 if allow_intrabc {
15843 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
15844 }
15845 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15846 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15847 return Ok(mode);
15848 }
15849 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15850 // This leaf's own palette state into the mi-granular above/left bands
15851 // (sizes 0 when it used none, which is what clears a previous block's
15852 // palette out of the next block's ctx and colour cache).
15853 {
15854 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15855 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15856 }
15857 hit!(INTER8_SKIP_BAND_HITS);
15858 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15859 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
15860 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
15861 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
15862 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
15863 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
15864 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
15865 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
15866 // wrong CDF row, so the msac range diverged mid-frame with no refusal
15867 // (class `wrong-alphabet-same-value`; the ReelB key frame at
15868 // -ss 900, first bad luma sample row 186 col 1803).
15869 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
15870 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15871 // own copy; only an intrabc var-tx read consumes these bands on the intra
15872 // path, so the write is armed by `allow_intrabc`.
15873 if allow_intrabc {
15874 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
15875 }
15876 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15877 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
15878 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
15879 // publish its own cells exactly like `decode_block` does.
15880 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15881 Ok(mode)
15882}
15883
15884/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
15885/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
15886/// bottom, where no partition symbol is read at all -- `decode_block` runs
15887/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
15888/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
15889/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
15890/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
15891/// of the 2x2 4x4 group carries chroma syntax at all.
15892#[allow(clippy::too_many_arguments)]
15893fn read_intra_mode_sub8(
15894 dec: &mut SymbolDecoder,
15895 cdfs: &mut Cdfs,
15896 above_mode: usize,
15897 left_mode: usize,
15898 has_chroma: bool,
15899 enable_filter_intra: bool,
15900 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
15901 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
15902 // from the wrong row is the same VALUE with a different interval, so it
15903 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
15904 fi_class: usize,
15905 skip_ctx: usize,
15906 allow_intrabc: bool,
15907 mi_r: usize,
15908 mi_c: usize,
15909 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
15910 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
15911 // left the second mi column at segment 0, which reads back as a
15912 // neighbour's `cdf_index`/prediction two blocks later.
15913 seg_w_mi: usize,
15914 seg_h_mi: usize, fctx: &crate::decode::FrameCtx,
15915) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
15916 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15917 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
15918 if ec_istep {
15919 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
15920 }
15921 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
15922 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
15923 macro_rules! istep {
15924 ($name:literal, $val:expr) => {
15925 if ec_istep {
15926 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0);
15927 }
15928 };
15929 }
15930 // lane-seg2: same `intra_segment_id` placement as the square and rect
15931 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
15932 // like any other block, over its own 1x1 mi footprint. Dropping it here
15933 // both ate a symbol (the tile desynced at the frame's first sub-8x8
15934 // split) and left `cur_segment_id` on the previous block, so the leaf
15935 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
15936 if seg_id_pre_skip(fctx) {
15937 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
15938 }
15939 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15940 if trace {
15941 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
15942 }
15943 istep!("skip", skip as i32);
15944 if !seg_id_pre_skip(fctx) {
15945 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
15946 }
15947 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
15948 istep!("cdef", 0);
15949 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15950 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15951 istep!("dq", 0);
15952 if allow_intrabc {
15953 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15954 if use_intrabc {
15955 return Err(unsupported(
15956 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
15957 ));
15958 }
15959 }
15960 let above_ctx = INTRA_MODE_CTX[above_mode];
15961 let left_ctx = INTRA_MODE_CTX[left_mode];
15962 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15963 istep!("mode", mode);
15964 if trace {
15965 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15966 }
15967 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
15968 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
15969 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
15970 // symbol. Reading one consumed a symbol the encoder never wrote and
15971 // desynced the tile at the very next element.
15972 let angle_delta_y = 0;
15973 let chroma = if has_chroma {
15974 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15975 if trace {
15976 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
15977 }
15978 if (9..=12).contains(&uv_mode) {
15979 hit!(SMOOTH_UV_HITS);
15980 }
15981 let alpha = if uv_mode == UV_CFL_PRED {
15982 Some(read_cfl_alphas(dec, cdfs))
15983 } else {
15984 None
15985 };
15986 if (V_PRED..=D67_PRED).contains(&uv_mode) {
15987 hit!(DIRECTIONAL_UV_HITS);
15988 }
15989 // See the luma comment above: no angle delta below 8x8.
15990 let angle_delta_uv = 0;
15991 Some((uv_mode, angle_delta_uv, alpha))
15992 } else {
15993 None
15994 };
15995 let mut filter_intra = None;
15996 if mode == DC_PRED && enable_filter_intra {
15997 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
15998 if trace {
15999 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
16000 }
16001 if use_filter_intra {
16002 hit!(FILTER_INTRA_HITS);
16003 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
16004 filter_intra = Some(fi_mode);
16005 }
16006 }
16007 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
16008}
16009
16010/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
16011/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
16012/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
16013/// bookkeeping needs no change. Each leaf reads its own luma mode info,
16014/// neighboured off the *previously decoded leaf in this same group* on
16015/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
16016/// pattern, one level deeper); chroma is read and reconstructed exactly
16017/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
16018/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
16019/// derivation.
16020#[allow(clippy::too_many_arguments)]
16021fn decode_leaf_split4(
16022 dec: &mut SymbolDecoder,
16023 cdfs: &mut Cdfs,
16024 neighbours: &mut Neighbours,
16025 outer_at: (usize, usize),
16026 leaf_mi: (usize, usize),
16027 scan4: &[u16],
16028 prev_leaf: Option<((usize, usize), usize)>,
16029 y: &mut PlaneBuf<'static>,
16030 u: &mut PlaneBuf<'static>,
16031 v: &mut PlaneBuf<'static>,
16032 base_q_idx: u8,
16033 enable_filter_intra: bool,
16034 allow_intrabc: bool,
16035 reduced_tx_set: bool,
16036 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
16037 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
16038 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
16039 fctx: &crate::decode::FrameCtx,
16040) -> Result<(usize, usize)> {
16041 hit!(SUB8_SPLIT_HITS);
16042 let (r, c) = outer_at;
16043 let mut above_mode = neighbours.above_mode[c];
16044 let mut left_mode = neighbours.left_mode[r];
16045 if let Some(((pr, pc), pmode)) = prev_leaf {
16046 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
16047 above_mode = pmode;
16048 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
16049 left_mode = pmode;
16050 }
16051 }
16052 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
16053 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
16054 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
16055 let mut leaf_modes = [0usize; 4];
16056 let mut leaf_skips = [false; 4];
16057 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
16058 for i in 0..4usize {
16059 let (dr, dc) = (i / 2, i % 2);
16060 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
16061 // Neighbour modes at real mi granularity: inside the group the
16062 // sibling leaf, outside it the split-leaf map when the adjacent mi
16063 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
16064 // `sub8_mode_col`'s doc).
16065 let leaf_above = if dr == 0 {
16066 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
16067 } else {
16068 leaf_modes[i - 2]
16069 };
16070 let leaf_left = if dc == 0 {
16071 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
16072 } else {
16073 leaf_modes[i - 1]
16074 };
16075 let has_chroma = i == 3;
16076 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
16077 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
16078 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
16079 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
16080 skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx,
16081 )?;
16082 leaf_modes[i] = mode;
16083 leaf_skips[i] = skip;
16084 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
16085 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
16086 if smooth_neighbor {
16087 hit!(SMOOTH_LUMA_HITS);
16088 }
16089 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
16090 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
16091 if skip {
16092 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
16093 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
16094 } else {
16095 let tu_around = neighbours.around_mi(lmi, 4)[0];
16096 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
16097 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
16098 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
16099 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
16100 // off the wrong CDF on the very first leaf and desynced the tile.
16101 let tu_grid = read_plane(
16102 dec,
16103 cdfs,
16104 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
16105 scan4,
16106 0,
16107 tu_around,
16108 mode,
16109 mode,
16110 angle_delta_y,
16111 reach,
16112 y,
16113 px,
16114 py,
16115 4,
16116 4,
16117 base_q_idx,
16118 None,
16119 filter_intra,
16120 None,
16121 smooth_neighbor, fctx,
16122 )?;
16123 neighbours.record_mi_luma(lmi, 4, &tu_grid);
16124 }
16125 neighbours.fill_skip_grid(lmi, 1, skip);
16126 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
16127 if has_chroma {
16128 last_uv = chroma;
16129 }
16130 }
16131 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16132 let (cpx, cpy) = (gpx / 2, gpy / 2);
16133 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
16134 let (uv_mode, angle_delta_uv, alpha) =
16135 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
16136 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16137 neighbours.above_uv_mode[c] = uv_predict_mode;
16138 neighbours.left_uv_mode[r] = uv_predict_mode;
16139 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16140 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
16141 // A skipped chroma block still gets its CfL contribution: libaom's
16142 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16143 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16144 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16145 // added -- `skip_txfm` only drops the residual, never the alpha.
16146 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16147 // merge keeps one fix and feeds both lanes' counters so neither of
16148 // their gates goes vacuous.
16149 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16150 if alpha.is_some() {
16151 hit!(CHROMA_SKIP_CFL_HITS);
16152 hit!(SKIP_CFL_HITS);
16153 }
16154 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);
16155 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);
16156 (Grid::Zero(16), Grid::Zero(16))
16157 } else {
16158 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16159 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16160 let ug = read_plane(
16161 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16162 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16163 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16164 )?;
16165 let vg = read_plane(
16166 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16167 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16168 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16169 )?;
16170 (ug, vg)
16171 };
16172 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
16173 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
16174 // rescaling is wrong for an already-mi-unit position, so this inlines
16175 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
16176 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
16177 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
16178 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
16179 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
16180 // bottom). libaom's `update_ext_partition_context` writes
16181 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
16182 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
16183 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
16184 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
16185 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
16186 // round's bug) makes the very next sibling 8x8's `partition_w8` read
16187 // with the wrong context and desync immediately.
16188 let side_mi = 2;
16189 for cell in 0..side_mi {
16190 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
16191 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
16192 }
16193 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16194 let bound_h = round_up_even(neighbours.mi_rows);
16195 let bound_w = round_up_even(neighbours.mi_cols);
16196 let u_state = neighbour_state(&u_grid);
16197 let v_state = neighbour_state(&v_grid);
16198 for cell in 0..side_mi {
16199 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
16200 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16201 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16202 }
16203 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
16204 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16205 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16206 }
16207 }
16208 // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette`
16209 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
16210 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
16211 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
16212 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
16213 // block above a 4x4 group left its size/colours standing in the mi-granular
16214 // bands: the block below the group read `palette_y_mode` off CDF row 1
16215 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
16216 // palette libaom never coded, and then skipped the `use_filter_intra`
16217 // symbol that a palette block has none of -- one symbol short, tile
16218 // desynced. Publishing the group's own zeros is the clear.
16219 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16220 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16221 Ok((leaf_modes[2], leaf_modes[1]))
16222}
16223
16224/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
16225/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
16226/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
16227/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
16228/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
16229/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
16230/// every sub-block one mi wide or high but the last) -- differing only where
16231/// the shape does:
16232///
16233/// * the transform is a true `TX_4X8`/`TX_8X4`
16234/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
16235/// `av1_inv_txfm_shift_ls` row already cover this size pair);
16236/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
16237/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
16238/// row -- see that variant's doc comment;
16239/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
16240/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
16241/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
16242/// ([`Reach::of_rect`]);
16243/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
16244/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
16245/// `BLOCK_4X4` split writes.
16246///
16247/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
16248/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
16249/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
16250/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
16251/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
16252/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
16253#[allow(clippy::too_many_arguments)]
16254fn decode_leaf_rect8(
16255 dec: &mut SymbolDecoder,
16256 cdfs: &mut Cdfs,
16257 neighbours: &mut Neighbours,
16258 outer_at: (usize, usize),
16259 leaf_mi: (usize, usize),
16260 vert: bool,
16261 scan4: &[u16],
16262 y: &mut PlaneBuf<'static>,
16263 u: &mut PlaneBuf<'static>,
16264 v: &mut PlaneBuf<'static>,
16265 base_q_idx: u8,
16266 enable_filter_intra: bool,
16267 allow_intrabc: bool,
16268 tx_select: bool,
16269 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
16270) -> Result<(usize, usize)> {
16271 let (r, c) = outer_at;
16272 // lane-modectx r1: availability-correct fallback pair (see
16273 // `modes_above_left`), not the raw coarse bands.
16274 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
16275 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
16276 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
16277 let (w_mi, h_mi) = (bw / MI, bh / MI);
16278 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
16279 let mut leaf_modes = [0usize; 2];
16280 let mut leaf_skips = [false; 2];
16281 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
16282 for i in 0..2usize {
16283 let lmi = if vert {
16284 (leaf_mi.0, leaf_mi.1 + i)
16285 } else {
16286 (leaf_mi.0 + i, leaf_mi.1)
16287 };
16288 // Inside the pair the sibling is the neighbour on the split axis;
16289 // outside it the mi-granular map, else the coarse 16x16 slot.
16290 let leaf_above = if !vert && i == 1 {
16291 leaf_modes[0]
16292 } else {
16293 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
16294 };
16295 let leaf_left = if vert && i == 1 {
16296 leaf_modes[0]
16297 } else {
16298 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
16299 };
16300 let has_chroma = i == 1;
16301 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
16302 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
16303 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
16304 filter_intra_size_class_rect(bw, bh)
16305 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
16306 skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx,
16307 )?;
16308 if filter_intra.is_some() {
16309 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
16310 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
16311 // same `reconstruct_rect`/`reconstruct` calls below -- and under
16312 // a split transform, per 4x4 unit with that unit's own edge,
16313 // which is exactly what the depth-1 loop already does.
16314 hit!(FILTER_INTRA_RECT_HITS);
16315 hit!(FILTER_INTRA_RECT_SUB8_HITS);
16316 }
16317 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
16318 // leaf too, and is read for every intra block, skipped or not. Its
16319 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
16320 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
16321 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
16322 // `tx_size_cat2` the 32x16 strips read -- with the rect context
16323 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
16324 // Missing this read consumed one symbol fewer than the encoder wrote
16325 // and desynced the tile at the very first rect leaf (class
16326 // `symbol-consumption-gap`).
16327 let depth = if tx_select {
16328 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
16329 // read every other rect reader now does -- a no-op on a key frame.
16330 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16331 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
16332 } else {
16333 tx_size_context_rect(neighbours, lmi, bw, bh)
16334 };
16335 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16336 } else {
16337 0
16338 };
16339 if depth != 0 {
16340 hit!(TX_DEPTH_HITS);
16341 hit!(RECT8_SPLIT_TX_HITS);
16342 }
16343 leaf_modes[i] = mode;
16344 leaf_skips[i] = skip;
16345 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
16346 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
16347 if smooth_neighbor {
16348 hit!(SMOOTH_LUMA_HITS);
16349 }
16350 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
16351 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16352 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
16353 // two 4x4 transform units along its long axis, each predicted from
16354 // the previous unit's reconstruction and reading its own `txb_skip`
16355 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
16356 // four. The per-TU path writes its own neighbour state, so the
16357 // block-level write below is skipped for it.
16358 let split = depth != 0 || lossless(fctx);
16359 if split {
16360 let mut done = 0usize;
16361 for tu in 0..2usize {
16362 let tu_mi = if vert {
16363 (lmi.0 + tu, lmi.1)
16364 } else {
16365 (lmi.0, lmi.1 + tu)
16366 };
16367 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
16368 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
16369 // Same per-TU rule as every other split-transform site
16370 // (lane-palette2 r12): a transform unit inside a block is not
16371 // a block at that position, so its reach comes from the
16372 // block's own row, offset by the unit's position.
16373 let tu_reach = tu_reach(
16374 bw,
16375 bh,
16376 tu_px - px,
16377 tu_py - py,
16378 4,
16379 reach,
16380 px,
16381 py,
16382 y.width,
16383 y.height, fctx,
16384 );
16385 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
16386 if skip {
16387 // A skipped leaf still predicts per transform unit: the
16388 // second 4x4 takes its above/left edge from the first
16389 // one's reconstruction, which is NOT what a single 4x8
16390 // prediction of the same mode produces.
16391 let zeros = vec![0i32; 16];
16392 push_intra(0,
16393 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
16394 filter_intra, smooth_neighbor, fctx,
16395 );
16396 neighbours.record_mi_luma(tu_mi, 4, &zeros);
16397 continue;
16398 }
16399 let tu_grid = read_plane(
16400 dec,
16401 cdfs,
16402 if reduced_tx_set {
16403 TxbSet::Luma4
16404 } else {
16405 TxbSet::Luma4Set1
16406 },
16407 scan4,
16408 0,
16409 tu_around,
16410 mode,
16411 mode,
16412 angle_delta_y,
16413 tu_reach,
16414 y,
16415 tu_px,
16416 tu_py,
16417 4,
16418 TX4,
16419 base_q_idx,
16420 None,
16421 filter_intra,
16422 Some(tu_skip_ctx),
16423 smooth_neighbor, fctx,
16424 )?;
16425 if tu_grid.iter().any(|&l| l != 0) {
16426 done += 1;
16427 }
16428 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
16429 }
16430 if done > 0 {
16431 if vert {
16432 hit!(TX4X8_CODED_HITS);
16433 } else {
16434 hit!(TX8X4_CODED_HITS);
16435 }
16436 }
16437 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16438 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
16439 if has_chroma {
16440 last_uv = chroma;
16441 }
16442 continue;
16443 }
16444 let grid = if skip {
16445 let zeros = Grid::Zero(bw * bh);
16446 push_intra_rect(0,
16447 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
16448 smooth_neighbor, fctx,
16449 );
16450 zeros
16451 } else {
16452 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
16453 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
16454 // at 0 -- see `decode_leaf_split4`'s own note.
16455 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
16456 let set = if reduced_tx_set {
16457 TxbSet::LumaRect4x8
16458 } else {
16459 TxbSet::LumaRect4x8Set1
16460 };
16461 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
16462 let (levels, tx_type) = read_coeffs_rect(
16463 dec,
16464 &mut coding,
16465 scan,
16466 bw,
16467 bh,
16468 0,
16469 dc_sign_ctx(around.2),
16470 TxType::DctDct,
16471 )?;
16472 if levels.iter().any(|&l| l != 0) {
16473 if vert {
16474 hit!(TX4X8_CODED_HITS);
16475 } else {
16476 hit!(TX8X4_CODED_HITS);
16477 }
16478 }
16479 let residual = dequant_and_inverse_typed_wh(
16480 &levels,
16481 bw,
16482 bh,
16483 crate::decode::bit_depth(fctx),
16484 // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at
16485 // every other dequant site (class `parsed-then-discarded`).
16486 block_q_idx(fctx),
16487 plane_q_delta(0, fctx).0,
16488 plane_q_delta(0, fctx).1,
16489 tx_type,
16490 );
16491 push_intra_rect(0,
16492 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
16493 smooth_neighbor, fctx,
16494 );
16495 levels
16496 };
16497 // Plane 0's per-TU coefficient context over this leaf's own mi span
16498 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
16499 // for the whole 8x8 group below).
16500 let state = neighbour_state(&grid);
16501 for cell in 0..h_mi {
16502 if lmi.0 + cell < neighbours.mi_rows {
16503 neighbours.left[lmi.0 + cell][0] = state;
16504 }
16505 }
16506 for cell in 0..w_mi {
16507 if lmi.1 + cell < neighbours.mi_cols {
16508 neighbours.above[lmi.1 + cell][0] = state;
16509 }
16510 }
16511 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16512 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
16513 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
16514 if has_chroma {
16515 last_uv = chroma;
16516 }
16517 }
16518 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16519 let (cpx, cpy) = (gpx / 2, gpy / 2);
16520 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
16521 let (uv_mode, angle_delta_uv, alpha) =
16522 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
16523 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16524 neighbours.above_uv_mode[c] = uv_predict_mode;
16525 neighbours.left_uv_mode[r] = uv_predict_mode;
16526 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16527 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] {
16528 // A skipped chroma block still gets its CfL contribution: libaom's
16529 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16530 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16531 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16532 // added -- `skip_txfm` only drops the residual, never the alpha.
16533 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16534 // merge keeps one fix and feeds both lanes' counters so neither of
16535 // their gates goes vacuous.
16536 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16537 if alpha.is_some() {
16538 hit!(CHROMA_SKIP_CFL_HITS);
16539 hit!(SKIP_CFL_HITS);
16540 }
16541 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);
16542 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);
16543 (Grid::Zero(16), Grid::Zero(16))
16544 } else {
16545 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16546 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16547 let ug = read_plane(
16548 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16549 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16550 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16551 )?;
16552 let vg = read_plane(
16553 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16554 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16555 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16556 )?;
16557 (ug, vg)
16558 };
16559 // `update_partition_context` at the 8x8 level writes
16560 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
16561 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
16562 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
16563 // `partition_ctx_mi` reads back off these side values.
16564 for cell in 0..2 {
16565 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
16566 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
16567 }
16568 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16569 let bound_h = round_up_even(neighbours.mi_rows);
16570 let bound_w = round_up_even(neighbours.mi_cols);
16571 let u_state = neighbour_state(&u_grid);
16572 let v_state = neighbour_state(&v_grid);
16573 for cell in 0..2usize {
16574 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
16575 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16576 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16577 }
16578 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
16579 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16580 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16581 }
16582 }
16583 // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette`
16584 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
16585 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
16586 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
16587 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
16588 // block above a 4x4 group left its size/colours standing in the mi-granular
16589 // bands: the block below the group read `palette_y_mode` off CDF row 1
16590 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
16591 // palette libaom never coded, and then skipped the `use_filter_intra`
16592 // symbol that a palette block has none of -- one symbol short, tile
16593 // desynced. Publishing the group's own zeros is the clear.
16594 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16595 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16596 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
16597 // bottom one (the second under HORZ, the left one under VERT), the one a
16598 // neighbour to the right sees is the top-right (the second under VERT).
16599 Ok(if vert {
16600 (leaf_modes[0], leaf_modes[1])
16601 } else {
16602 (leaf_modes[1], leaf_modes[0])
16603 })
16604}
16605
16606/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
16607/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
16608/// (mod 8) reuse the same table.
16609const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
16610 [(-1, 1), (-2, 2)],
16611 [(0, 1), (-1, 2)],
16612 [(0, 1), (0, 2)],
16613 [(0, 1), (1, 2)],
16614 [(1, 1), (2, 2)],
16615 [(1, 0), (2, 1)],
16616 [(1, 0), (2, 0)],
16617 [(1, 0), (2, -1)],
16618];
16619/// A neighbour tap outside the frame's true extent -- `constrain` reads this
16620/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
16621const CDEF_VERY_LARGE: i32 = 0x4000;
16622const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
16623const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
16624
16625fn cdef_msb(x: i32) -> i32 {
16626 31 - x.leading_zeros() as i32
16627}
16628
16629/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
16630/// centre sample a filter tap is allowed to contribute.
16631#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16632fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
16633 if threshold == 0 {
16634 return 0;
16635 }
16636 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
16637}
16638
16639/// `constrain`'s damping shift: a function of the block's threshold and
16640/// damping alone, so the filter loop computes it once per block instead of
16641/// the `leading_zeros` + branch it used to do twice per tap read.
16642fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
16643 (damping - cdef_msb(threshold)).max(0)
16644}
16645
16646/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
16647/// non-zero on every call (the caller only filters when its strength is).
16648fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
16649 let a = diff.abs();
16650 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
16651}
16652
16653/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
16654/// lies inside its own samples grown by this much.
16655const CDEF_BORDER: usize = 2;
16656
16657/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
16658/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
16659/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
16660/// index a small contiguous window instead of re-deriving the frame-bounds
16661/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
16662/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
16663fn cdef_gather(
16664 src: &[u16],
16665 stride: usize,
16666 true_w: usize,
16667 true_h: usize,
16668 ox: usize,
16669 oy: usize,
16670 bw: usize,
16671 bh: usize,
16672 buf: &mut [i16],
16673) {
16674 let bstride = bw + 2 * CDEF_BORDER;
16675 let rows = bh + 2 * CDEF_BORDER;
16676 if oy >= CDEF_BORDER
16677 && ox >= CDEF_BORDER
16678 && oy + bh + CDEF_BORDER <= true_h
16679 && ox + bw + CDEF_BORDER <= true_w
16680 {
16681 // Interior block: every tap is inside the frame, so the whole window
16682 // is `rows` contiguous runs.
16683 for r in 0..rows {
16684 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
16685 let src_row = &src[s0..s0 + bstride];
16686 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
16687 for (d, &v) in dst_row.iter_mut().zip(src_row) {
16688 *d = v as i16;
16689 }
16690 }
16691 return;
16692 }
16693 for r in 0..rows {
16694 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
16695 for c in 0..bstride {
16696 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
16697 buf[r * bstride + c] =
16698 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
16699 CDEF_VERY_LARGE as i16
16700 } else {
16701 src[ny as usize * stride + nx as usize] as i16
16702 };
16703 }
16704 }
16705}
16706
16707/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
16708/// array takes the row, its reverse, its pairwise sums or its total added
16709/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
16710/// per-sample form did become a handful of lane-wide adds per row. i32 is
16711/// exact here: every partial is a sum of at most eight values in -128..127,
16712/// and slot 15 exists only so an eight-lane store at offset 7 fits.
16713fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
16714 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
16715 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
16716 *d += x;
16717 }
16718 }
16719 let mut partial = [[0i32; 16]; 8];
16720 for i in 0..8usize {
16721 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16722 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
16723 // accumulating, same as `constrain`'s threshold shift.
16724 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
16725 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
16726 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
16727 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
16728 let (p, rest) = partial.split_at_mut(1);
16729 add_at(&mut p[0], i, &row); // partial[0][i + j]
16730 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
16731 rest[1][i] = row.iter().sum(); // partial[2][i]
16732 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
16733 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
16734 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
16735 add_at(&mut rest[5], 0, &row); // partial[6][j]
16736 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
16737 }
16738 partial
16739}
16740
16741/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
16742/// direction of an 8x8 luma window and the variance gap between it and its
16743/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
16744/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
16745fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
16746 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
16747 #[cfg(target_arch = "x86_64")]
16748 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16749 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16750 // the same eight rows of eight samples the scalar form does.
16751 #[allow(unsafe_code)]
16752 unsafe {
16753 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
16754 }
16755 } else {
16756 cdef_find_dir_partials(win, bstride, coeff_shift)
16757 };
16758 #[cfg(not(target_arch = "x86_64"))]
16759 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
16760 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
16761 let mut cost = [0i64; 8];
16762 for i in 0..8usize {
16763 cost[2] += sq(partial[2][i]);
16764 cost[6] += sq(partial[6][i]);
16765 }
16766 cost[2] *= DIV_TABLE[8];
16767 cost[6] *= DIV_TABLE[8];
16768 for i in 0..7usize {
16769 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
16770 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
16771 }
16772 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
16773 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
16774 for i in (1..8).step_by(2) {
16775 for j in 0..5usize {
16776 cost[i] += sq(partial[i][3 + j]);
16777 }
16778 cost[i] *= DIV_TABLE[8];
16779 for j in 0..3usize {
16780 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
16781 }
16782 }
16783 let mut best_cost = 0i64;
16784 let mut best_dir = 0usize;
16785 for (i, &c) in cost.iter().enumerate() {
16786 if c > best_cost {
16787 best_cost = c;
16788 best_dir = i;
16789 }
16790 }
16791 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
16792 (best_dir, var as i32)
16793}
16794
16795/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
16796/// (high variance gap) gets more deringing than a flat or non-directional
16797/// one, only ever applied to the luma primary strength.
16798fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
16799 if var == 0 {
16800 return 0;
16801 }
16802 let i = if var >> 6 != 0 {
16803 cdef_msb(var >> 6).min(12)
16804 } else {
16805 0
16806 };
16807 (strength * (4 + i) + 8) >> 4
16808}
16809
16810/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
16811/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
16812/// previously-filtered neighbour must never feed this block's own sum).
16813#[allow(clippy::too_many_arguments)]
16814#[allow(unsafe_code)]
16815fn cdef_filter_block(
16816 src: &[i16],
16817 dst: &mut PlaneBuf<'static>,
16818 ox: usize,
16819 oy: usize,
16820 bw: usize,
16821 bh: usize,
16822 pri_strength: i32,
16823 sec_strength: i32,
16824 dir: usize,
16825 pri_damping: i32,
16826 sec_damping: i32,
16827 enable_primary: bool,
16828 enable_secondary: bool,
16829 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
16830) {
16831 let (stride, smax) = (dst.width, sample_max(fctx));
16832 #[cfg(target_arch = "x86_64")]
16833 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
16834 {
16835 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16836 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
16837 // `bh` runs of `bw` samples the scalar form writes.
16838 unsafe {
16839 cdef_simd::filter_block_avx2(
16840 src,
16841 dst.data.to_mut(),
16842 stride,
16843 ox,
16844 oy,
16845 bw,
16846 bh,
16847 pri_strength,
16848 sec_strength,
16849 dir,
16850 pri_damping,
16851 sec_damping,
16852 enable_primary,
16853 enable_secondary,
16854 coeff_shift,
16855 smax,
16856 )
16857 };
16858 return;
16859 }
16860 cdef_filter_block_scalar(
16861 src,
16862 dst.data.to_mut(),
16863 stride,
16864 ox,
16865 oy,
16866 bw,
16867 bh,
16868 pri_strength,
16869 sec_strength,
16870 dir,
16871 pri_damping,
16872 sec_damping,
16873 enable_primary,
16874 enable_secondary,
16875 coeff_shift,
16876 smax,
16877 );
16878}
16879
16880/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
16881/// the form every non-AVX2 build decodes through and the one
16882/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
16883#[allow(clippy::too_many_arguments)]
16884fn cdef_filter_block_scalar(
16885 src: &[i16],
16886 dst: &mut [u16],
16887 stride: usize,
16888 ox: usize,
16889 oy: usize,
16890 bw: usize,
16891 bh: usize,
16892 pri_strength: i32,
16893 sec_strength: i32,
16894 dir: usize,
16895 pri_damping: i32,
16896 sec_damping: i32,
16897 enable_primary: bool,
16898 enable_secondary: bool,
16899 coeff_shift: i32,
16900 smax: i32,
16901) {
16902 let clipping_required = enable_primary && enable_secondary;
16903 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
16904 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
16905 // derivative) carries the bit-depth shift, so the tap-set parity bit
16906 // must be read back above that shift, not off the raw low bit.
16907 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16908 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
16909 // `constrain`), so they are resolved here rather than per tap read.
16910 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
16911 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
16912 let bstride = bw + 2 * CDEF_BORDER;
16913 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
16914 // reaching +-CDEF_BORDER, so every index below is in range by construction.
16915 let at = |i: i32, j: i32| -> i32 {
16916 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
16917 };
16918 let (pri_dir, sec_dir0, sec_dir1) =
16919 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16920 for i in 0..bh {
16921 for j in 0..bw {
16922 let (i32i, i32j) = (i as i32, j as i32);
16923 let x = at(i32i, i32j);
16924 let mut sum = 0i32;
16925 let mut max = x;
16926 let mut min = x;
16927 for k in 0..2usize {
16928 if enable_primary {
16929 let (tr, tc) = pri_dir[k];
16930 let p0 = at(i32i + tr, i32j + tc);
16931 let p1 = at(i32i - tr, i32j - tc);
16932 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
16933 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
16934 if clipping_required {
16935 if p0 != CDEF_VERY_LARGE {
16936 max = max.max(p0);
16937 }
16938 if p1 != CDEF_VERY_LARGE {
16939 max = max.max(p1);
16940 }
16941 min = min.min(p0).min(p1);
16942 }
16943 }
16944 if enable_secondary {
16945 let (tr0, tc0) = sec_dir0[k];
16946 let (tr1, tc1) = sec_dir1[k];
16947 let s0 = at(i32i + tr0, i32j + tc0);
16948 let s1 = at(i32i - tr0, i32j - tc0);
16949 let s2 = at(i32i + tr1, i32j + tc1);
16950 let s3 = at(i32i - tr1, i32j - tc1);
16951 if clipping_required {
16952 for s in [s0, s1, s2, s3] {
16953 if s != CDEF_VERY_LARGE {
16954 max = max.max(s);
16955 }
16956 }
16957 min = min.min(s0).min(s1).min(s2).min(s3);
16958 }
16959 sum += CDEF_SEC_TAPS[k]
16960 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
16961 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
16962 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
16963 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
16964 }
16965 }
16966 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
16967 if clipping_required {
16968 y = y.clamp(min, max);
16969 }
16970 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
16971 }
16972 }
16973}
16974
16975/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
16976/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
16977/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
16978/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
16979/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
16980/// a time in 16-bit lanes.
16981///
16982/// 16-bit lanes are exact for every value this filter sees: window samples
16983/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
16984/// `i16`, a `constrain` result is bounded by the threshold (at most
16985/// `15 << 4`), and the tap-weighted sum by `24 *` that.
16986#[cfg(target_arch = "x86_64")]
16987#[allow(unsafe_code)]
16988#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16989mod cdef_simd {
16990 use super::{
16991 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
16992 CDEF_VERY_LARGE,
16993 };
16994 use std::arch::x86_64::*;
16995
16996 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
16997 /// register (low half = row `i`).
16998 ///
16999 /// # Safety
17000 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
17001 #[target_feature(enable = "avx2")]
17002 #[inline]
17003 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
17004 let lo = _mm_loadu_si128(w.offset(off).cast());
17005 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
17006 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
17007 }
17008
17009 /// Spec 7.15.3's `constrain`, lane-parallel:
17010 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
17011 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
17012 /// clamped magnitude is already 0 where `diff` is).
17013 ///
17014 /// # Safety
17015 /// Requires AVX2.
17016 #[target_feature(enable = "avx2")]
17017 #[inline]
17018 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
17019 let diff = _mm256_sub_epi16(p, x);
17020 let a = _mm256_abs_epi16(diff);
17021 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
17022 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
17023 _mm256_sign_epi16(t, diff)
17024 }
17025
17026 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
17027 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
17028 /// four the auto-vectorised scalar form gets without the feature.
17029 ///
17030 /// # Safety
17031 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
17032 /// grown by `CDEF_BORDER` at row stride `bstride`.
17033 #[target_feature(enable = "avx2")]
17034 pub unsafe fn find_dir_partials_avx2(
17035 win: &[i16],
17036 bstride: usize,
17037 coeff_shift: i32,
17038 ) -> [[i32; 16]; 8] {
17039 #[target_feature(enable = "avx2")]
17040 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
17041 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
17042 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
17043 }
17044 #[target_feature(enable = "avx2")]
17045 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
17046 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
17047 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
17048 }
17049 let mut partial = [[0i32; 16]; 8];
17050 let shift = _mm_cvtsi32_si128(coeff_shift);
17051 let c128 = _mm256_set1_epi32(128);
17052 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
17053 let mut p6 = _mm256_setzero_si256();
17054 for i in 0..8usize {
17055 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
17056 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
17057 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
17058 let rev = _mm256_permutevar8x32_epi32(row, revidx);
17059 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
17060 // four pairwise sums are the two lanes' low halves joined.
17061 let h = _mm256_hadd_epi32(row, row);
17062 let pair =
17063 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
17064 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
17065 let hs = _mm_hadd_epi32(pair, pair);
17066 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
17067 add8(&mut partial[0], i, row);
17068 add4(&mut partial[1], i, pair);
17069 partial[2][i] = total;
17070 add4(&mut partial[3], i, rpair);
17071 add8(&mut partial[4], i, rev);
17072 add8(&mut partial[5], 3 - i / 2, row);
17073 p6 = _mm256_add_epi32(p6, row);
17074 add8(&mut partial[7], i / 2, row);
17075 }
17076 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
17077 partial
17078 }
17079
17080 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
17081 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
17082 /// `bw == 4` the upper four lanes of each half are window samples read
17083 /// past the row (never past the buffer -- `w` is padded to 256 entries),
17084 /// computed and then dropped by the 64-bit store.
17085 ///
17086 /// # Safety
17087 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
17088 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
17089 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
17090 /// of `bw` samples at `(ox, oy)`.
17091 #[target_feature(enable = "avx2")]
17092 #[allow(clippy::too_many_arguments)]
17093 pub unsafe fn filter_block_avx2(
17094 src: &[i16],
17095 dst: &mut [u16],
17096 stride: usize,
17097 ox: usize,
17098 oy: usize,
17099 bw: usize,
17100 bh: usize,
17101 pri_strength: i32,
17102 sec_strength: i32,
17103 dir: usize,
17104 pri_damping: i32,
17105 sec_damping: i32,
17106 enable_primary: bool,
17107 enable_secondary: bool,
17108 coeff_shift: i32,
17109 smax: i32,
17110 ) {
17111 let bstride = bw + 2 * CDEF_BORDER;
17112 // The caller's window is already `i16` and 256 entries long, so the
17113 // kernel taps it in place: the largest two-row load is
17114 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
17115 // 4x4 chroma one, both inside the buffer's zeroed tail.
17116 let w = src;
17117 let clipping_required = enable_primary && enable_secondary;
17118 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
17119 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
17120 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
17121 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
17122 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
17123 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
17124 let zero = _mm256_setzero_si256();
17125 let eight = _mm256_set1_epi16(8);
17126 let smaxv = _mm256_set1_epi16(smax as i16);
17127 let (pri_dir, sec_dir0, sec_dir1) =
17128 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
17129 let wp = w.as_ptr();
17130 let bs = bstride as isize;
17131 let dp = dst.as_mut_ptr();
17132 let mut i = 0usize;
17133 while i < bh {
17134 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
17135 let x = ld2(wp, base, bs);
17136 let mut sum = zero;
17137 let mut max = x;
17138 let mut min = x;
17139 for k in 0..2usize {
17140 if enable_primary {
17141 let (tr, tc) = pri_dir[k];
17142 let off = tr as isize * bs + tc as isize;
17143 let p0 = ld2(wp, base + off, bs);
17144 let p1 = ld2(wp, base - off, bs);
17145 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
17146 sum = _mm256_add_epi16(
17147 sum,
17148 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
17149 );
17150 sum = _mm256_add_epi16(
17151 sum,
17152 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
17153 );
17154 if clipping_required {
17155 // The sentinel is excluded from the max exactly as the
17156 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
17157 // 0 cannot win a max whose seed `x` is non-negative.
17158 max = _mm256_max_epi16(
17159 max,
17160 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
17161 );
17162 max = _mm256_max_epi16(
17163 max,
17164 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
17165 );
17166 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
17167 }
17168 }
17169 if enable_secondary {
17170 let (tr0, tc0) = sec_dir0[k];
17171 let (tr1, tc1) = sec_dir1[k];
17172 let off0 = tr0 as isize * bs + tc0 as isize;
17173 let off1 = tr1 as isize * bs + tc1 as isize;
17174 let s0 = ld2(wp, base + off0, bs);
17175 let s1 = ld2(wp, base - off0, bs);
17176 let s2 = ld2(wp, base + off1, bs);
17177 let s3 = ld2(wp, base - off1, bs);
17178 if clipping_required {
17179 for s in [s0, s1, s2, s3] {
17180 max = _mm256_max_epi16(
17181 max,
17182 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
17183 );
17184 }
17185 min = _mm256_min_epi16(
17186 min,
17187 _mm256_min_epi16(
17188 _mm256_min_epi16(s0, s1),
17189 _mm256_min_epi16(s2, s3),
17190 ),
17191 );
17192 }
17193 let c = _mm256_add_epi16(
17194 _mm256_add_epi16(
17195 constrain(s0, x, sec_thr, sec_shift),
17196 constrain(s1, x, sec_thr, sec_shift),
17197 ),
17198 _mm256_add_epi16(
17199 constrain(s2, x, sec_thr, sec_shift),
17200 constrain(s3, x, sec_thr, sec_shift),
17201 ),
17202 );
17203 sum = _mm256_add_epi16(
17204 sum,
17205 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
17206 );
17207 }
17208 }
17209 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
17210 let neg = _mm256_cmpgt_epi16(zero, sum);
17211 let mut y = _mm256_add_epi16(
17212 x,
17213 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
17214 );
17215 if clipping_required {
17216 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
17217 }
17218 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
17219 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
17220 let o0 = ((oy + i) * stride + ox) as isize;
17221 let o1 = o0 + stride as isize;
17222 if bw == 8 {
17223 _mm_storeu_si128(dp.offset(o0).cast(), lo);
17224 _mm_storeu_si128(dp.offset(o1).cast(), hi);
17225 } else {
17226 _mm_storel_epi64(dp.offset(o0).cast(), lo);
17227 _mm_storel_epi64(dp.offset(o1).cast(), hi);
17228 }
17229 i += 2;
17230 }
17231 }
17232}
17233
17234/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
17235/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
17236/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
17237/// every block's level comes from [`LoopFilterParams::level`] plus the
17238/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
17239/// `get_filter_level`, precomputed per-block here rather than cached in a
17240/// table the way libaom's `av1_loop_filter_frame_init` does).
17241///
17242/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
17243/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
17244fn apply_deblock(
17245 y: &mut PlaneBuf<'static>,
17246 u: &mut PlaneBuf<'static>,
17247 v: &mut PlaneBuf<'static>,
17248 lf: &LoopFilterParams,
17249 n: &Neighbours,
17250 frame_width: usize,
17251 frame_height: usize, fctx: &crate::decode::FrameCtx,
17252) {
17253 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
17254 // mismatch between the raw reconstruction and post-filter output.
17255 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
17256 return;
17257 }
17258 if lf.level[0] != 0 || lf.level[1] != 0 {
17259 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
17260 }
17261 if lf.level[2] != 0 {
17262 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
17263 }
17264 if lf.level[3] != 0 {
17265 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
17266 }
17267}
17268
17269/// [`apply_deblock`] for ONE pass over ONE band of luma rows
17270/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
17271/// planes' vertical passes and then their three horizontal ones is the same
17272/// output as `apply_deblock`'s plane-at-a-time order: the planes are
17273/// separate buffers and neither pass reads another plane.
17274#[allow(clippy::too_many_arguments)]
17275fn deblock_span(
17276 y: &mut PlaneBuf<'static>,
17277 u: &mut PlaneBuf<'static>,
17278 v: &mut PlaneBuf<'static>,
17279 lf: &LoopFilterParams,
17280 n: &Neighbours,
17281 frame_width: usize,
17282 frame_height: usize,
17283 y_lo: usize,
17284 y_hi: usize,
17285 horz: bool,
17286 fctx: &crate::decode::FrameCtx,
17287) {
17288 if lf.level[0] != 0 || lf.level[1] != 0 {
17289 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
17290 }
17291 if lf.level[2] != 0 {
17292 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
17293 }
17294 if lf.level[3] != 0 {
17295 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
17296 }
17297}
17298
17299/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
17300/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
17301/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
17302/// mi unit under this decoder's assumed 4:2:0 subsampling).
17303///
17304/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
17305/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
17306/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
17307/// prediction mode is obtained from the bottom/right mi structure of the
17308/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
17309/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
17310/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
17311/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
17312/// the group is split into 4x4 luma blocks (class
17313/// `context-read-from-one-cell`).
17314fn plane_to_mi(chroma: bool, coord: usize) -> usize {
17315 if chroma { (coord / 2) | 1 } else { coord / 4 }
17316}
17317
17318/// This plane's own transform width in pixels at the covering block, spec
17319/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
17320/// width directly; chroma halves it (this decoder's UV transform is always
17321/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
17322/// under 4:2:0 and a block that never splits its own transform).
17323fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17324 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
17325 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17326}
17327
17328/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
17329/// edges step and gate by transform height, which differs from width only
17330/// on rect partition strips.
17331fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17332 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
17333 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17334}
17335
17336/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
17337/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
17338/// present only when its neighbour exists inside the true frame -- whether
17339/// the block immediately above (at this block's own leftmost mi column) or
17340/// to the left (at its own topmost mi row) coded a transform at least as wide
17341/// as `own_side`.
17342fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
17343 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
17344 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
17345 usize::from(above) + usize::from(left)
17346}
17347
17348/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
17349/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
17350/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
17351/// inter path maintains), except that an *inter* neighbour contributes its
17352/// own BLOCK size rather than its transform size -- the two differ the moment
17353/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
17354/// approximation coincides with this only while every neighbour codes one
17355/// whole-block transform, which is exactly what `TxMode::Select` ends.
17356/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
17357/// r1): `get_tx_size_context` compares the neighbour ABOVE against
17358/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
17359/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
17360/// strip are two different numbers. The intra strip inside an inter frame read
17361/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
17362/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
17363/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
17364fn tx_size_context_txfm_rect(
17365 n: &Neighbours,
17366 (mi_r, mi_c): (usize, usize),
17367 own_w: usize,
17368 own_h: usize, fctx: &crate::decode::FrameCtx,
17369) -> usize {
17370 hit!(INTRA_IN_INTER_TXCTX_HITS);
17371 let has_above = mi_r > n.tile_row0_mi;
17372 let has_left = mi_c > n.tile_col0_mi;
17373 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
17374 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
17375 if has_above && n.above_inter[mi_c] {
17376 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
17377 }
17378 if has_left && n.left_inter[mi_r] {
17379 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
17380 }
17381 if crate::envflags::env_flag!("EC_TXCTX") {
17382 eprintln!(
17383 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
17384 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17385 above={above} left={left}",
17386 n.above_txfm[mi_c],
17387 n.left_txfm[mi_r],
17388 n.above_inter[mi_c],
17389 n.left_inter[mi_r],
17390 n.above_side_mi[mi_c],
17391 n.left_side_mi[mi_r],
17392 );
17393 }
17394 let ctx = match (has_above, has_left) {
17395 (true, true) => usize::from(above) + usize::from(left),
17396 (true, false) => usize::from(above),
17397 (false, true) => usize::from(left),
17398 (false, false) => 0,
17399 };
17400 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
17401 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
17402 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
17403 // intra in an inter frame" tally is green on the buggy code too (class
17404 // gate-blind-to-feature).
17405 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
17406 let (cw, ch) = (own_w.min(64), own_h.min(64));
17407 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
17408 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
17409 if ctx != stale {
17410 hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS);
17411 }
17412 }
17413 ctx
17414}
17415
17416/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
17417/// are written and read everywhere else with a raw mi index); the SUB-cell
17418/// division this pair used read a cell four blocks away, so the inter-neighbour
17419/// override above fired on the wrong neighbour -- the first divergence of the
17420/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
17421/// at the intra block right of an inter one).
17422fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
17423 let has_above = mi_r > n.tile_row0_mi;
17424 let has_left = mi_c > n.tile_col0_mi;
17425 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
17426 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
17427 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
17428 // `above_inter`/`left_inter` bands are written per MI unit
17429 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
17430 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
17431 // block whenever the neighbour column/row is not the cell's first. A
17432 // 16x16 intra block whose left neighbour is an inter block at mi row 4
17433 // then missed libaom's "an inter neighbour contributes its BLOCK size"
17434 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
17435 if has_above && n.above_inter[mi_c] {
17436 above = usize::from(n.above_side_mi[mi_c]) >= side;
17437 }
17438 if has_left && n.left_inter[mi_r] {
17439 left = usize::from(n.left_side_mi[mi_r]) >= side;
17440 }
17441 if crate::envflags::env_flag!("EC_TXCTX") {
17442 eprintln!(
17443 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
17444 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17445 above={above} left={left}",
17446 n.above_txfm[mi_c],
17447 n.left_txfm[mi_r],
17448 n.above_inter[mi_c],
17449 n.left_inter[mi_r],
17450 n.above_side_mi[mi_c],
17451 n.left_side_mi[mi_r],
17452 );
17453 }
17454 match (has_above, has_left) {
17455 (true, true) => usize::from(above) + usize::from(left),
17456 (true, false) => usize::from(above),
17457 (false, true) => usize::from(left),
17458 (false, false) => 0,
17459 }
17460}
17461
17462/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
17463/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
17464/// the transform's own side in pixels (`side >> depth`) -- this decoder's
17465/// four square categories (8/16/32/64) each halve at most twice, matching
17466/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
17467fn read_tx_size(
17468 dec: &mut SymbolDecoder,
17469 cdfs: &mut Cdfs,
17470 n: &Neighbours,
17471 at_mi: (usize, usize),
17472 side: usize,
17473 // lane-txselect: `get_tx_size_context`'s real context, for the callers
17474 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
17475 // key-frame path's own deblock-grid approximation.
17476 ctx_override: Option<usize>,
17477) -> usize {
17478 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
17479 // `get_tx_size_context`): a block wider than 64 still tops out at
17480 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
17481 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
17482 // never against its own 128 side (lane-sb128b r1).
17483 let max_tx = side.min(64);
17484 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
17485 let depth = match max_tx {
17486 8 => {
17487 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
17488 }
17489 16 => {
17490 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
17491 }
17492 32 => {
17493 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
17494 }
17495 64 => {
17496 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
17497 }
17498 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
17499 };
17500 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17501 let (rng, _) = dec.debug_state();
17502 let (mi_r, mi_c) = at_mi;
17503 eprintln!(
17504 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
17505 );
17506 }
17507 if depth != 0 {
17508 hit!(TX_DEPTH_HITS);
17509 }
17510 max_tx >> depth
17511}
17512
17513/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
17514/// `txfm_split` context -- a category from the block's own largest square
17515/// transform and whether this unit already sits below it, times three, plus
17516/// the two neighbour terms (whether the transform last written above/left of
17517/// this unit is narrower/shorter than the unit itself).
17518#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17519fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
17520 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
17521}
17522
17523/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
17524/// libaom's `txfm_partition_context` compares the above context against
17525/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
17526/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
17527/// side for a square transform, which is why the square form above is a
17528/// special case of this one.
17529pub(crate) fn txfm_partition_ctx_rect(
17530 above_px: u8,
17531 left_px: u8,
17532 blk_max_px: usize,
17533 tx_w: usize,
17534 tx_h: usize,
17535) -> usize {
17536 let above = usize::from(usize::from(above_px) < tx_w);
17537 let left = usize::from(usize::from(left_px) < tx_h);
17538 let tx_px = tx_w.max(tx_h);
17539 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
17540 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
17541 // `log2(px) - 2`.
17542 let max_tx = blk_max_px.min(64);
17543 let max_idx = max_tx.trailing_zeros() as usize - 2;
17544 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
17545 category * 3 + above + left
17546}
17547
17548/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
17549/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
17550/// resolved transform's own size.
17551#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17552fn txfm_partition_update(
17553 n: &mut Neighbours,
17554 at_mi: (usize, usize),
17555 tx_px: usize,
17556 txb_px: usize,
17557) {
17558 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
17559}
17560
17561/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
17562/// the left column records `tx_size_high` over the parent's own height and
17563/// the above row records `tx_size_wide` over its width.
17564/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
17565/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
17566/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
17567/// key frame writes neither (its readers use the deblock grid), so the
17568/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
17569/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
17570/// at the call site (the transform size comes back to them); the 1:4 arms
17571/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
17572/// so they call this where their own depth resolves. A no-op on a key frame
17573/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
17574///
17575/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
17576/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
17577/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
17578/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
17579/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
17580/// / early-return-skips-tail).
17581fn publish_txfm_bands_if_in_inter(
17582 n: &mut Neighbours,
17583 at_mi: (usize, usize),
17584 (tx_w, tx_h): (usize, usize),
17585 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
17586) {
17587 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
17588 return;
17589 }
17590 let (mi_r, mi_c) = at_mi;
17591 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17592 for i in 0..bw / MI {
17593 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17594 *cell = tx_w as u8;
17595 }
17596 }
17597 for i in 0..bh / MI {
17598 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17599 *cell = tx_h as u8;
17600 }
17601 }
17602}
17603
17604fn txfm_partition_update_rect(
17605 n: &mut Neighbours,
17606 (mi_r, mi_c): (usize, usize),
17607 (tx_w, tx_h): (usize, usize),
17608 (txb_w, txb_h): (usize, usize),
17609) {
17610 if crate::envflags::env_flag!("EC_TXUPD") {
17611 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
17612 }
17613 for i in 0..txb_h / MI {
17614 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17615 *cell = tx_h as u8;
17616 }
17617 }
17618 for i in 0..txb_w / MI {
17619 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17620 *cell = tx_w as u8;
17621 }
17622 }
17623}
17624
17625/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
17626/// same contexts -- a skipped *inter* block records its own block size rather
17627/// than its transform size.
17628fn set_txfm_ctxs(
17629 n: &mut Neighbours,
17630 (mi_r, mi_c): (usize, usize),
17631 tx_px: usize,
17632 w_mi: usize,
17633 h_mi: usize,
17634 skip_inter: bool,
17635) {
17636 if crate::envflags::env_flag!("EC_TXUPD") {
17637 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
17638 }
17639 let bw = if skip_inter { w_mi * MI } else { tx_px };
17640 let bh = if skip_inter { h_mi * MI } else { tx_px };
17641 for i in 0..w_mi {
17642 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17643 *cell = bw as u8;
17644 }
17645 }
17646 for i in 0..h_mi {
17647 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17648 *cell = bh as u8;
17649 }
17650 }
17651}
17652
17653/// The value libaom initialises both transform contexts to -- NOT zero:
17654/// `av1_zero_above_context` memsets the txfm row to
17655/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
17656/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17657/// pixels, so an unwritten neighbour reads as the *widest* possible
17658/// transform, not the narrowest.
17659pub(crate) const TXFM_CTX_INIT: u8 = 64;
17660
17661/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17662/// twice below its own largest transform.
17663const MAX_VARTX_DEPTH: usize = 2;
17664
17665/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
17666/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
17667/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
17668/// small ones, square everywhere else.
17669fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
17670 match (tx_w, tx_h) {
17671 (4, 4) => (4, 4),
17672 (8, 8) => (4, 4),
17673 (16, 16) => (8, 8),
17674 (32, 32) => (16, 16),
17675 (64, 64) => (32, 32),
17676 (4, 8) | (8, 4) => (4, 4),
17677 (8, 16) | (16, 8) => (8, 8),
17678 (16, 32) | (32, 16) => (16, 16),
17679 (32, 64) | (64, 32) => (32, 32),
17680 (4, 16) => (4, 8),
17681 (16, 4) => (8, 4),
17682 (8, 32) => (8, 16),
17683 (32, 8) => (16, 8),
17684 (16, 64) => (16, 32),
17685 (64, 16) => (32, 16),
17686 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
17687 }
17688}
17689
17690#[test]
17691fn sub_tx_size_map_matches_libaom() {
17692 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
17693 const TABLE: [((usize, usize), (usize, usize)); 19] = [
17694 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
17695 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
17696 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
17697 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
17698 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
17699 ];
17700 for (tx, want) in TABLE {
17701 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
17702 }
17703}
17704
17705/// The domain of var-tx leaf sizes, enumerated against the two refusals that
17706/// name a leaf "larger than 32x32" / "larger than 64x64".
17707///
17708/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
17709/// either the unit it was entered with or a `sub_tx_size_map` step below it:
17710/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
17711/// return. So the leaf set reachable from an entry unit is that unit plus the
17712/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
17713/// which this test enumerates, and over which no leaf is ever larger than the
17714/// entry.
17715///
17716/// That closes both refusals:
17717///
17718/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
17719/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
17720/// 64x64" names a leaf the tree cannot produce;
17721/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
17722/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
17723/// reached only when `side == 64`, and then the block is ONE unit whose only
17724/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
17725/// case the refusal is guarded by.
17726#[test]
17727fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
17728 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
17729 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
17730 out.push((depth, entry.0, entry.1));
17731 if depth == MAX_VARTX_DEPTH {
17732 return;
17733 }
17734 let sub = sub_tx_size_map(entry.0, entry.1);
17735 if sub == (4, 4) {
17736 out.push((depth + 1, 4, 4));
17737 return;
17738 }
17739 reachable(sub, depth + 1, out);
17740 }
17741
17742 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
17743 let mut leaves = Vec::new();
17744 reachable(entry, 0, &mut leaves);
17745 for (depth, w, h) in &leaves {
17746 assert!(
17747 w.max(h) <= &entry.0.max(entry.1),
17748 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
17749 entry.0,
17750 entry.1
17751 );
17752 }
17753 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
17754 if entry == (64, 64) {
17755 let above: Vec<&(usize, usize, usize)> =
17756 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
17757 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
17758 }
17759 }
17760
17761 // The entry size and ceiling each caller uses, over the block sides that
17762 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
17763 // enters at a fixed 64).
17764 for side in [8usize, 16, 32, 64, 128] {
17765 let max_tx = side.min(64);
17766 let ceiling = if side > 64 { 64 } else { 32 };
17767 let units = (side / max_tx) * (side / max_tx);
17768 if max_tx <= ceiling {
17769 continue;
17770 }
17771 assert_eq!(
17772 (side, units),
17773 (64, 1),
17774 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
17775 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
17776 );
17777 }
17778}
17779
17780/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
17781/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
17782/// max-transform-sized unit of an inter block, collecting the resolved leaf
17783/// transform units into `out` as `(row offset, col offset, side)` in mi units
17784/// -- exactly the order `decode_reconstruct_tx` later reads their
17785/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
17786/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
17787/// `max_block_high`).
17788#[allow(clippy::too_many_arguments)]
17789fn read_var_tx_size(
17790 dec: &mut SymbolDecoder,
17791 cdfs: &mut Cdfs,
17792 n: &mut Neighbours,
17793 at_mi: (usize, usize),
17794 blk_max_px: usize,
17795 (max_w_mi, max_h_mi): (usize, usize),
17796 (tx_w, tx_h): (usize, usize),
17797 depth: usize,
17798 blk_row: usize,
17799 blk_col: usize,
17800 out: &mut Vec<(usize, usize, usize, usize)>,
17801) {
17802 if blk_row >= max_h_mi || blk_col >= max_w_mi {
17803 return;
17804 }
17805 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
17806 if depth == MAX_VARTX_DEPTH {
17807 out.push((blk_row, blk_col, tx_w, tx_h));
17808 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17809 return;
17810 }
17811 let ctx = txfm_partition_ctx_rect(
17812 n.above_txfm[unit.1],
17813 n.left_txfm[unit.0],
17814 blk_max_px,
17815 tx_w,
17816 tx_h,
17817 );
17818 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17819 hit!(TXFM_SPLIT_READS);
17820 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17821 let (rng, _) = dec.debug_state();
17822 eprintln!(
17823 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
17824 unit.0,
17825 unit.1,
17826 u8::from(split)
17827 );
17828 }
17829 if !split {
17830 out.push((blk_row, blk_col, tx_w, tx_h));
17831 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17832 return;
17833 }
17834 hit!(TXFM_SPLIT_HITS);
17835 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17836 if (sub_w, sub_h) == (4, 4) {
17837 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
17838 // unit is marked 4x4 (raster order) without recursing.
17839 for row in 0..tx_h / MI {
17840 for col in 0..tx_w / MI {
17841 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
17842 out.push((blk_row + row, blk_col + col, 4, 4));
17843 }
17844 }
17845 }
17846 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
17847 return;
17848 }
17849 for row in (0..tx_h / MI).step_by(sub_h / MI) {
17850 for col in (0..tx_w / MI).step_by(sub_w / MI) {
17851 read_var_tx_size(
17852 dec,
17853 cdfs,
17854 n,
17855 at_mi,
17856 blk_max_px,
17857 (max_w_mi, max_h_mi),
17858 (sub_w, sub_h),
17859 depth + 1,
17860 blk_row + row,
17861 blk_col + col,
17862 out,
17863 );
17864 }
17865 }
17866}
17867
17868/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
17869/// branch): every block of a `TxMode::Select` inter frame codes its transform
17870/// size right after its own mode info -- an inter non-skip block through the
17871/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
17872/// every other block through the intra `tx_depth` symbol (a skipped inter
17873/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
17874/// block's own resolved transform side and the leaf list, the latter only
17875/// when the tree resolved to more than one transform unit.
17876#[allow(clippy::too_many_arguments)]
17877fn read_block_tx_size(
17878 dec: &mut SymbolDecoder,
17879 cdfs: &mut Cdfs,
17880 n: &mut Neighbours,
17881 at_mi: (usize, usize),
17882 side: usize,
17883 (mi_cols, mi_rows): (usize, usize),
17884 is_inter: bool,
17885 skip: bool, fctx: &crate::decode::FrameCtx,
17886) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17887 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
17888 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
17889 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
17890 if lossless(fctx) {
17891 let mut leaves = Vec::new();
17892 for row in 0..side / MI {
17893 for col in 0..side / MI {
17894 leaves.push((row, col, 4, 4));
17895 }
17896 }
17897 return Ok((4, Some(leaves)));
17898 }
17899 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17900 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
17901 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
17902 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
17903 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
17904 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
17905 if side > 64 {
17906 let step = 64 / MI;
17907 let mut leaves = Vec::new();
17908 for row in (0..side / MI).step_by(step) {
17909 for col in (0..side / MI).step_by(step) {
17910 leaves.push((row, col, 64, 64));
17911 }
17912 }
17913 return Ok((64, Some(leaves)));
17914 }
17915 return Ok((side, None));
17916 }
17917 let side_mi = side / MI;
17918 if is_inter && !skip {
17919 let max_tx = side.min(64);
17920 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
17921 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
17922 let mut leaves = Vec::new();
17923 let step = max_tx / MI;
17924 for row in (0..side_mi).step_by(step) {
17925 for col in (0..side_mi).step_by(step) {
17926 read_var_tx_size(
17927 dec,
17928 cdfs,
17929 n,
17930 at_mi,
17931 side,
17932 (max_w_mi, max_h_mi),
17933 (max_tx, max_tx),
17934 0,
17935 row,
17936 col,
17937 &mut leaves,
17938 );
17939 }
17940 }
17941 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
17942 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
17943 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
17944 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
17945 // which the mu-chunk reader above codes as their 32x32 coded corner.
17946 let leaf_ceiling = if side > 64 { 64 } else { 32 };
17947 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
17948 // Only a block wider than a superblock's own 64x64 max transform
17949 // reaches here; this crate has no 64-point *inter* coefficient
17950 // table set ([`inter_txbset_for`] stops at 32).
17951 return Err(unsupported(
17952 "an inter var-tx tree with a leaf transform larger than 32x32",
17953 ));
17954 }
17955 let resolved = leaves.last().map_or(side, |l| l.2);
17956 return Ok((resolved, (!single).then_some(leaves)));
17957 }
17958 let tx = if is_inter {
17959 side.min(64)
17960 } else {
17961 read_tx_size(
17962 dec,
17963 cdfs,
17964 n,
17965 at_mi,
17966 side,
17967 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
17968 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
17969 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
17970 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
17971 )
17972 };
17973 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
17974 if !is_inter && tx != side {
17975 // lane-intrainter r1: an intra block inside an inter frame whose
17976 // `tx_depth` split its luma transform codes exactly the key-frame
17977 // split path's transform units (`decode_block`'s multi-TU loop),
17978 // raster order over the block. Handed back in the same leaf shape the
17979 // inter var-tx tree uses, so the caller's per-TU luma loop, the
17980 // `record_split_luma` neighbour write-back and the per-TU deblock
17981 // edges are the ones it already runs for a var-tx inter block. A
17982 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
17983 // seeing `Some` here.
17984 let step = tx / MI;
17985 let mut leaves = Vec::new();
17986 for row in (0..side_mi).step_by(step) {
17987 for col in (0..side_mi).step_by(step) {
17988 leaves.push((row, col, tx, tx));
17989 }
17990 }
17991 hit_do! {
17992 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
17993 let mut h = c.get();
17994 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
17995 c.set(h);
17996 });
17997 }
17998 return Ok((tx, Some(leaves)));
17999 }
18000 Ok((tx, None))
18001}
18002
18003/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
18004/// decoder codes -- a 2:1 strip whose own max rect transform
18005/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
18006/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
18007/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
18008/// 64-point rect transform, and 16x8/8x16 needs
18009/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
18010/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
18011/// rect transform), neither of which exists yet -- both stay refused by name.
18012pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
18013 matches!(
18014 (w, h),
18015 // 2:1 strips whose transform is coded in full (lane-inter4).
18016 (32, 16) | (16, 32) | (16, 8) | (8, 16)
18017 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
18018 // codes all 64 of its positions, and its chroma pair is an 8x4 /
18019 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
18020 | (16, 4) | (4, 16)
18021 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
18022 // only the low 32 coefficients of a 64-length axis, so these read
18023 // exactly the truncated corner the INTRA superblock-strip path
18024 // already reads (`read_intra_mode_rect`), through
18025 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
18026 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
18027 // `tx_type` symbol is coded at all.
18028 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
18029 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
18030 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
18031 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
18032 // refused earlier ("an inter partition below 8x8").
18033 | (8, 4) | (4, 8)
18034 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
18035 // one rectangular transform -- `max_txsize_rect_lookup
18036 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
18037 // TX_64X64 units read through the mu-chunk loop, same as the
18038 // 128x128 NONE block's four.
18039 | (128, 64) | (64, 128)
18040 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
18041 // 10-bit film cuts and every measured 1080p offset stop on
18042 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
18043 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
18044 // positions, and its chroma pair is a 16x4 / 4x16 unit
18045 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
18046 | (32, 8) | (8, 32)
18047 )
18048}
18049
18050// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
18051// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
18052// the "rectangular ... has no ... here" refusals. `side` is the square context
18053// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
18054// `inter_piece!` derives `reject_residual` from exactly that inequality, so
18055// these triples are what decides whether those refusals can fire at all. Bit
18056// 31 is "a triple this table does not list", which is what makes the gate a
18057// census rather than a restatement of its own table.
18058pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
18059 (16, 16, 16),
18060 (32, 32, 32),
18061 (32, 16, 32),
18062 (32, 32, 16),
18063 (16, 8, 16),
18064 (16, 16, 8),
18065 (32, 8, 32),
18066 (64, 64, 64),
18067 (32, 32, 8),
18068 (64, 16, 64),
18069 (128, 128, 128),
18070 (64, 32, 64),
18071 (64, 64, 32),
18072 (16, 4, 16),
18073 (64, 64, 16),
18074 (16, 16, 4),
18075 (128, 128, 64),
18076 (128, 64, 128),
18077];
18078
18079/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
18080/// outside [`INTER_BLOCK_SHAPES`].
18081pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
18082
18083thread_local! {
18084 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
18085}
18086
18087/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
18088/// gate reading it sees only the streams it decoded itself).
18089pub fn inter_block_shape_mask() -> u32 {
18090 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
18091}
18092
18093/// Records one block's shape. The table is ordered by measured frequency over
18094/// the three witnesses the census gate decodes, so the common square shapes
18095/// leave the scan on their first comparison.
18096fn census_inter_block_shape(side: usize, w: usize, h: usize) {
18097 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
18098 Some(i) => 1u32 << i,
18099 None => INTER_BLOCK_SHAPE_UNLISTED,
18100 };
18101 let seen = inter_block_shape_mask();
18102 if seen & bit == 0 {
18103 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
18104 }
18105}
18106
18107/// The luma coefficient/`tx_type` table set of a whole-block rectangular
18108/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
18109/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
18110/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
18111/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
18112/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
18113/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
18114/// row (`txsize_sqr_map`), never the 16x16 one.
18115fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
18116 Ok(match (w, h) {
18117 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
18118 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
18119 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
18120 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
18121 // ALL16 otherwise -- both at the TX_4X4 row.
18122 (8, 4) | (4, 8) => {
18123 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
18124 TxbSet::LumaRect8x4Inter
18125 } else {
18126 TxbSet::LumaRect8x4InterSet1
18127 }
18128 }
18129 (16, 4) | (4, 16) => {
18130 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
18131 TxbSet::LumaRect16x4Inter
18132 } else {
18133 TxbSet::LumaRect16x4Inter1
18134 }
18135 }
18136 (16, 8) | (8, 16) => {
18137 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
18138 TxbSet::LumaRect16x8Inter
18139 } else {
18140 TxbSet::LumaRect16x8InterSet1
18141 }
18142 }
18143 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
18144 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
18145 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
18146 // adjusted size, so the existing sets are bit-exact. Neither carries a
18147 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
18148 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
18149 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
18150 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
18151 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
18152 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
18153 (64, 32) | (32, 64) => TxbSet::Luma64,
18154 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
18155 _ => {
18156 return Err(unsupported(
18157 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
18158 ));
18159 }
18160 })
18161}
18162
18163/// The chroma table set of the same block's single rectangular chroma unit
18164/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
18165/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
18166/// the luma unit's.
18167fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
18168 Ok(match (w, h) {
18169 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
18170 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
18171 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
18172 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
18173 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
18174 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
18175 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
18176 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
18177 (32, 8) | (8, 32) => TxbSet::Chroma16,
18178 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
18179 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
18180 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
18181 (16, 4) | (4, 16) => TxbSet::Chroma8,
18182 _ => {
18183 return Err(unsupported(
18184 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
18185 ));
18186 }
18187 })
18188}
18189
18190/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
18191/// inter path reaches, from the block's TRUE footprint rather than the
18192/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
18193/// everything 32 and above -> 3.
18194fn size_group_wh(w: usize, h: usize) -> usize {
18195 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
18196 // `common_data.h:60`) is 0 for every block with a 4-px side
18197 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
18198 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
18199 match w.min(h) {
18200 0..=4 => 0,
18201 8 => 1,
18202 16 => 2,
18203 _ => 3,
18204 }
18205}
18206
18207#[test]
18208fn size_group_wh_matches_libaom_size_group_lookup() {
18209 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
18210 // transcribed values (common_data.h:60-62).
18211 const TABLE: [((usize, usize), usize); 22] = [
18212 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
18213 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
18214 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
18215 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
18216 ];
18217 for ((w, h), want) in TABLE {
18218 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
18219 }
18220}
18221
18222/// The default (2D) coefficient scan of a rectangular transform.
18223fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
18224 Ok(match (w, h) {
18225 (32, 16) => &SCAN_32X16,
18226 (16, 32) => &SCAN_16X32,
18227 (16, 8) => &SCAN_16X8,
18228 (8, 16) => &SCAN_8X16,
18229 (16, 4) => &SCAN_16X4,
18230 (4, 16) => &SCAN_4X16,
18231 (8, 4) => &SCAN_8X4,
18232 (4, 8) => &SCAN_4X8,
18233 (32, 8) => &SCAN_32X8,
18234 (8, 32) => &SCAN_8X32,
18235 _ => {
18236 return Err(unsupported(
18237 "a rectangular transform unit whose shape has no coefficient scan table here",
18238 ));
18239 }
18240 })
18241}
18242
18243/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
18244/// transform unit whose shape has no coefficient table set here" / "a
18245/// rectangular transform unit whose shape has no coefficient scan table here"
18246/// arms, enumerated against the MEASURED domain of the inter block path
18247/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
18248/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
18249///
18250/// What each helper is actually handed:
18251///
18252/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
18253/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
18254/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
18255/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
18256/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
18257/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
18258/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
18259/// unit, and only when that corner is not 32x32 (a square corner goes
18260/// through the square reader with `rect_shape = Some((w, h))`).
18261///
18262/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
18263/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
18264/// loop, which is why they are skipped below.
18265#[test]
18266fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
18267 let fctx = &crate::decode::FrameCtx::new();
18268 let corner_scan = |w: usize, h: usize| {
18269 let (cw, ch) = (w.min(32), h.min(32));
18270 if (cw, ch) == (32, 32) {
18271 return; // the square coefficient reader, not `rect_scan`
18272 }
18273 assert!(
18274 rect_scan(cw, ch).is_ok(),
18275 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
18276 );
18277 };
18278 let mut checked = 0;
18279 for &(side, w, h) in &INTER_BLOCK_SHAPES {
18280 if (w, h) == (side, side) || w.max(h) > 64 {
18281 continue;
18282 }
18283 assert!(
18284 rect_inter_luma_set(w, h, fctx).is_ok(),
18285 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
18286 );
18287 corner_scan(w, h);
18288 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
18289 // footprint for every other shape.
18290 let (cw, ch) = match (w, h) {
18291 (16, 4) => (8, 4),
18292 (4, 16) => (4, 8),
18293 _ => (w / 2, h / 2),
18294 };
18295 assert!(
18296 rect_inter_chroma_set(cw, ch).is_ok(),
18297 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
18298 );
18299 corner_scan(cw, ch);
18300 checked += 1;
18301 }
18302 assert_eq!(
18303 checked, 12,
18304 "the block-shape census changed: {checked} rect shapes reach the rect transform \
18305 tables, not the 12 this claim was measured over"
18306 );
18307 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
18308 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
18309 for (w, h) in [(8usize, 4usize), (4, 8)] {
18310 assert!(
18311 rect_inter_luma_set(w, h, fctx).is_ok(),
18312 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
18313 );
18314 corner_scan(w, h);
18315 }
18316}
18317
18318/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
18319/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
18320/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
18321/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
18322/// own width/height; a `0` leaves one whole-block rect transform unit
18323/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
18324/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
18325/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
18326/// every leaf of a split rect block is square and the existing square leaf
18327/// loop reconstructs it unchanged.
18328#[allow(clippy::too_many_arguments)]
18329fn read_block_tx_size_rect(
18330 dec: &mut SymbolDecoder,
18331 cdfs: &mut Cdfs,
18332 n: &mut Neighbours,
18333 at_mi: (usize, usize),
18334 (bw, bh): (usize, usize),
18335 (mi_cols, mi_rows): (usize, usize),
18336 skip: bool, fctx: &crate::decode::FrameCtx,
18337) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
18338 if lossless(fctx) {
18339 let mut leaves = Vec::new();
18340 for row in 0..bh / MI {
18341 for col in 0..bw / MI {
18342 leaves.push((row, col, 4, 4));
18343 }
18344 }
18345 return Ok(Some(leaves));
18346 }
18347 if skip {
18348 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
18349 // its own BLOCK size -- width above, height left -- not a transform.
18350 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
18351 return Ok(None);
18352 }
18353 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
18354 // `rect_inter_residual_supported` has already excluded everything above 32.
18355 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
18356 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
18357 // is TWO square top-level transform units side by side and a 64x128 one is
18358 // two stacked -- exactly what libaom `read_block_tx_size`
18359 // (decodeframe.c:1140) codes with its `idy/idx` loop over
18360 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
18361 // own `txfm_partition` symbol at depth 0.
18362 if bw.max(bh) > 64 {
18363 let tx = 64usize;
18364 let (max_w_mi, max_h_mi) = (
18365 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
18366 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
18367 );
18368 let mut leaves = Vec::new();
18369 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18370 for row in (0..bh / MI).step_by(tx / MI) {
18371 for col in (0..bw / MI).step_by(tx / MI) {
18372 leaves.push((row, col, tx, tx));
18373 }
18374 }
18375 for &(row, col, tw, th) in &leaves {
18376 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
18377 }
18378 return Ok(Some(leaves));
18379 }
18380 for row in (0..bh / MI).step_by(tx / MI) {
18381 for col in (0..bw / MI).step_by(tx / MI) {
18382 read_var_tx_size(
18383 dec,
18384 cdfs,
18385 n,
18386 at_mi,
18387 bw.max(bh),
18388 (max_w_mi, max_h_mi),
18389 (tx, tx),
18390 0,
18391 row,
18392 col,
18393 &mut leaves,
18394 );
18395 }
18396 }
18397 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
18398 return Err(unsupported(
18399 "an inter var-tx tree with a leaf transform larger than 64x64",
18400 ));
18401 }
18402 return Ok(Some(leaves));
18403 }
18404 let (tx_w, tx_h) = (bw, bh);
18405 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18406 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
18407 // transform, and `set_txfm_ctxs` records exactly what
18408 // `txfm_partition_update` would for that same unit.
18409 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18410 hit!(RECT_INTER_TU_HITS);
18411 return Ok(None);
18412 }
18413 let ctx = txfm_partition_ctx_rect(
18414 n.above_txfm[at_mi.1],
18415 n.left_txfm[at_mi.0],
18416 bw.max(bh),
18417 tx_w,
18418 tx_h,
18419 );
18420 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
18421 hit!(TXFM_SPLIT_READS);
18422 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18423 let (rng, _) = dec.debug_state();
18424 eprintln!(
18425 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
18426 at_mi.0,
18427 at_mi.1,
18428 u8::from(split)
18429 );
18430 }
18431 if !split {
18432 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18433 hit!(RECT_INTER_TU_HITS);
18434 return Ok(None);
18435 }
18436 hit!(TXFM_SPLIT_HITS);
18437 hit!(RECT_INTER_TXSPLIT_HITS);
18438 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
18439 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
18440 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
18441 // rect one and its leaves carry their own width and height.
18442 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
18443 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
18444 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
18445 let mut leaves = Vec::new();
18446 for row in (0..bh / MI).step_by(sub_h / MI) {
18447 for col in (0..bw / MI).step_by(sub_w / MI) {
18448 read_var_tx_size(
18449 dec,
18450 cdfs,
18451 n,
18452 at_mi,
18453 bw.max(bh),
18454 (max_w_mi, max_h_mi),
18455 (sub_w, sub_h),
18456 1,
18457 row,
18458 col,
18459 &mut leaves,
18460 );
18461 }
18462 }
18463 Ok(Some(leaves))
18464}
18465
18466/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
18467/// the coefficients are read with the rect coefficient machinery
18468/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
18469/// types), inverted with the rect inverse transform
18470/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
18471/// and added onto the top-left `w x h` of the block's own square-strided
18472/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
18473/// and the coded `tx_type`.
18474///
18475/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
18476/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
18477#[allow(clippy::too_many_arguments)]
18478fn read_inter_plane_rect(
18479 dec: &mut SymbolDecoder,
18480 cdfs: &mut Cdfs,
18481 set: TxbSet,
18482 (w, h): (usize, usize),
18483 stride: usize,
18484 plane_idx: usize,
18485 around: (bool, bool, i32),
18486 tx_mode: usize,
18487 // lane-wave1 step (i): unread -- this reader records its write
18488 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
18489 // stays in the signature so every call site still proves the plane is
18490 // exclusively held while its coefficients are parsed.
18491 _plane: &mut PlaneBuf<'static>,
18492 x: usize,
18493 y: usize,
18494 prediction: Pred<'_>,
18495 inherited_luma_tx_type: Option<TxType>,
18496 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
18497) -> Result<(Grid, TxType)> {
18498 let skip_ctx = if plane_idx == 0 {
18499 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
18500 // block; a var-tx leaf passes its own neighbour-table context.
18501 luma_skip_ctx.unwrap_or(0)
18502 } else {
18503 usize::from(around.0) + usize::from(around.1)
18504 };
18505 let mut coding = cdfs.txb(set, tx_mode);
18506 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
18507 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
18508 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
18509 // plane of a lossless block (the residual then goes through the WHT, so
18510 // the type only picks the scan, which is the default one).
18511 if lossless(fctx) {
18512 coding.tx_type = None;
18513 }
18514 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
18515 // the *longer* side of this rect transform.
18516 let default_tx_type = match inherited_luma_tx_type {
18517 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
18518 None => TxType::DctDct,
18519 };
18520 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
18521 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
18522 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
18523 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
18524 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
18525 // corner, zero-extended into the true `w x h` grid before the inverse
18526 // transform -- exactly what the intra superblock-strip path does. A
18527 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
18528 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
18529 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
18530 // rectangular shape (lane-sbpart r8).
18531 let (cw, ch) = (w.min(32), h.min(32));
18532 if plane_idx == 0 && w.max(h) == 64 {
18533 hit!(RECT64_INTER_TU_HITS);
18534 }
18535 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
18536 hit_do! {
18537 RECT32X8_INTER_TU_HITS.with(|c| {
18538 let mut v = c.get();
18539 v[usize::from(w == 8)] += 1;
18540 c.set(v);
18541 });
18542 }
18543 }
18544 let (corner, tx_type) = if (cw, ch) == (32, 32) {
18545 let scan32 = default_scan(TX32);
18546 read_coeffs(
18547 dec,
18548 &mut coding,
18549 &scan32,
18550 skip_ctx,
18551 dc_sign_ctx(around.2),
18552 default_tx_type,
18553 Some((w, h)),
18554 )?
18555 } else {
18556 read_coeffs_rect(
18557 dec,
18558 &mut coding,
18559 rect_scan(cw, ch)?,
18560 cw,
18561 ch,
18562 skip_ctx,
18563 dc_sign_ctx(around.2),
18564 default_tx_type,
18565 )?
18566 };
18567 let grid = extend_corner(corner, cw, ch, w, h);
18568 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
18569 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
18570 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
18571 }
18572 // `reconstruct_mc_rect` reads both buffers at the square prediction
18573 // stride, so the dense `w x h` residual is re-laid at that stride
18574 // (`TxParams::stride`) after the inverse transform.
18575 let tx = TxParams {
18576 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18577 stride, lossless: lossless(fctx),
18578 };
18579 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
18580 Ok((grid, tx_type))
18581}
18582
18583/// The coded `cw x ch` corner of a transform zero-extended into its true
18584/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
18585/// corner that coded nothing stays the shared zero grid -- no allocation
18586/// (lane-coefgrid).
18587fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
18588 if (cw, ch) == (w, h) {
18589 return corner;
18590 }
18591 if let Grid::Zero(_) = corner {
18592 return Grid::Zero(w * h);
18593 }
18594 let mut full = vec![0i32; w * h];
18595 for row in 0..ch {
18596 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
18597 }
18598 Grid::Own(full)
18599}
18600
18601/// A rect coefficient grid re-laid into the square `stride x stride` grid the
18602/// neighbour/deblock stamps downstream of the residual expect.
18603fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
18604 let mut full = vec![0i32; stride * stride];
18605 for row in 0..h {
18606 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
18607 }
18608 full
18609}
18610
18611/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
18612/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
18613/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
18614/// raster order, each reading its own coefficient context off the units
18615/// already decoded before it. Returns the block's luma grid (all-zero in the
18616/// split case, whose reconstruction has already happened unit by unit) and
18617/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
18618/// which for a split block lands on the top-left unit.
18619#[allow(clippy::too_many_arguments)]
18620fn read_inter_luma8(
18621 dec: &mut SymbolDecoder,
18622 cdfs: &mut Cdfs,
18623 neighbours: &mut Neighbours,
18624 leaf_mi: (usize, usize),
18625 y: &mut PlaneBuf<'static>,
18626 px: usize,
18627 py: usize,
18628 pred_y: Pred<'_>,
18629 mode_for_tx: usize,
18630 base_q_idx: u8,
18631 scan8: &[u16],
18632 scan4: &[u16],
18633 reduced_tx_set: bool,
18634 split: bool, fctx: &crate::decode::FrameCtx,
18635) -> Result<(Grid, TxType)> {
18636 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
18637 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
18638 let split = split || lossless(fctx);
18639 if !split {
18640 return read_inter_plane(
18641 dec,
18642 cdfs,
18643 if reduced_tx_set {
18644 TxbSet::Luma8Inter
18645 } else {
18646 TxbSet::Luma8InterSet1
18647 },
18648 scan8,
18649 0,
18650 neighbours.around_mi(leaf_mi, 8)[0],
18651 mode_for_tx,
18652 y,
18653 px,
18654 py,
18655 8,
18656 base_q_idx,
18657 pred_y,
18658 None,
18659 None, fctx,
18660 );
18661 }
18662 let mut first = TxType::DctDct;
18663 for tu_row in 0..2 {
18664 for tu_col in 0..2 {
18665 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18666 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
18667 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18668 let (tu_grid, tu_tx_type) = read_inter_plane(
18669 dec,
18670 cdfs,
18671 if reduced_tx_set {
18672 TxbSet::Luma4Inter
18673 } else {
18674 TxbSet::Luma4InterSet1
18675 },
18676 scan4,
18677 0,
18678 neighbours.around_mi(tu_mi, 4)[0],
18679 mode_for_tx,
18680 y,
18681 px + tu_col * 4,
18682 py + tu_row * 4,
18683 4,
18684 base_q_idx,
18685 tu_pred,
18686 None,
18687 Some(tu_skip_ctx), fctx,
18688 )?;
18689 if tu_row == 0 && tu_col == 0 {
18690 first = tu_tx_type;
18691 }
18692 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18693 }
18694 }
18695 Ok((Grid::Zero(64), first))
18696}
18697
18698/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
18699/// coefficient tables from -- the inter counterpart of [`txbset_for`].
18700/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
18701/// an inter block's chroma transform inherits the *colocated luma* unit's
18702/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
18703/// of the extended set the CHROMA transform size selects
18704/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
18705/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
18706/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
18707/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
18708/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
18709/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
18710/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
18711/// sync and only corrupted the inverse transform (one 64x64 superblock of
18712/// high-frequency chroma noise, luma bit-exact).
18713pub(crate) fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
18714 reduce_inherited_chroma_tx_type_flagged(t, w, h, fctx.reduced_tx_set_inter.with(std::cell::Cell::get))
18715}
18716
18717/// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set`
18718/// bit (lane-intertx): the WRITER calls this with the frame's own header bit
18719/// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter
18720/// block's chroma transform is coded with, the same derivation its reader
18721/// makes -- it has no `FrameCtx` in reach and must not silently read one
18722/// whose value can lag the frame being written (class `stale-context-bit`).
18723pub(crate) fn reduce_inherited_chroma_tx_type_flagged(t: TxType, w: usize, h: usize, reduced: bool) -> TxType {
18724 use TxType::*;
18725 let sqr_up = w.max(h);
18726 let sqr = w.min(h);
18727 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
18728 let allowed: &[TxType] = if sqr_up > 32 {
18729 // EXT_TX_SET_DCTONLY
18730 &[DctDct]
18731 } else if sqr_up == 32 || reduced {
18732 // EXT_TX_SET_DCT_IDTX
18733 &[DctDct, Idtx]
18734 } else if sqr == 16 {
18735 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
18736 // the four 1D ADST/FLIPADST types.
18737 &[
18738 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
18739 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
18740 ]
18741 } else {
18742 // EXT_TX_SET_ALL16
18743 return t;
18744 };
18745 if allowed.contains(&t) { t } else { DctDct }
18746}
18747
18748fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18749 match tx_px {
18750 // lane-sb128c r1: a 128x128 inter block's own luma unit
18751 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
18752 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
18753 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
18754 // coincide -- exactly the set the whole-64x64 inter block already uses.
18755 64 => TxbSet::Luma64,
18756 32 => TxbSet::Luma32Inter,
18757 16 if reduced_tx_set => TxbSet::Luma16Inter,
18758 16 => TxbSet::Luma16InterSet1,
18759 8 if reduced_tx_set => TxbSet::Luma8Inter,
18760 8 => TxbSet::Luma8InterSet1,
18761 4 if reduced_tx_set => TxbSet::Luma4Inter,
18762 4 => TxbSet::Luma4InterSet1,
18763 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
18764 }
18765}
18766
18767/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
18768/// the only four sizes a `TxMode::Select` block's coded coefficient grid
18769/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
18770fn scan_for<'a>(
18771 tx_px: usize,
18772 scan32: &'a [u16],
18773 scan16: &'a [u16],
18774 scan8: &'a [u16],
18775 scan4: &'a [u16],
18776) -> &'a [u16] {
18777 match tx_px {
18778 32 => scan32,
18779 16 => scan16,
18780 8 => scan8,
18781 4 => scan4,
18782 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
18783 }
18784}
18785
18786/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
18787/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
18788/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
18789/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
18790/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
18791/// regardless of the flag (`av1_get_ext_tx_set_type`'s
18792/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
18793/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
18794/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
18795/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
18796/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
18797/// inter `ext_tx` sets, never the mode-indexed intra ones.
18798fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18799 match tx_px {
18800 64 => TxbSet::Luma64,
18801 32 => TxbSet::Luma32Inter,
18802 16 if reduced_tx_set => TxbSet::Luma16Inter,
18803 16 => TxbSet::Luma16InterSet1,
18804 8 if reduced_tx_set => TxbSet::Luma8Inter,
18805 8 => TxbSet::Luma8InterSet1,
18806 _ => TxbSet::Luma64,
18807 }
18808}
18809
18810fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18811 match tx_px {
18812 64 => TxbSet::Luma64,
18813 32 => TxbSet::Luma32,
18814 16 => TxbSet::Luma16,
18815 8 if reduced_tx_set => TxbSet::Luma8,
18816 8 => TxbSet::Luma8Set1,
18817 4 if reduced_tx_set => TxbSet::Luma4,
18818 4 => TxbSet::Luma4Set1,
18819 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
18820 }
18821}
18822
18823/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
18824/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
18825fn unit_log2(px: u32) -> i32 {
18826 if px == 0 {
18827 0
18828 } else {
18829 px.trailing_zeros() as i32 - 2
18830 }
18831}
18832
18833/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
18834/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
18835/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
18836/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
18837/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
18838/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
18839/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
18840/// block anywhere aborted the whole stream's decode before comparison).
18841fn lf_level(
18842 lf: &LoopFilterParams,
18843 plane_idx: usize,
18844 dir: usize,
18845 ref_frame: i8,
18846 delta_lf: i32,
18847 segment_id: u8, fctx: &crate::decode::FrameCtx,
18848) -> i32 {
18849 let base = i32::from(if plane_idx == 0 {
18850 lf.level[dir]
18851 } else if plane_idx == 1 {
18852 lf.level[2]
18853 } else {
18854 lf.level[3]
18855 });
18856 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
18857 // ref/mode delta scaling below, and regardless of `delta_enabled`
18858 // (that flag only gates `ref_deltas`/`mode_deltas`).
18859 let base = (base + delta_lf).clamp(0, 63);
18860 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
18861 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
18862 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
18863 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
18864 // for chroma.
18865 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18866 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
18867 // when the frame codes no segmentation (`seg_lf_active`), which is what
18868 // spares the deblock loop two thread-local reads per 4x4 edge.
18869 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
18870 Some(data) => (base + data).clamp(0, 63),
18871 None => base,
18872 };
18873 if !lf.delta_enabled {
18874 return base;
18875 }
18876 let scale = 1i32 << (base >> 5);
18877 let is_inter = ref_frame != 0;
18878 let is_globalmv = ref_frame < 0;
18879 let ref_idx = ref_frame.unsigned_abs() as usize;
18880 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
18881 if is_inter {
18882 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
18883 }
18884 lvl.clamp(0, 63)
18885}
18886
18887thread_local! {
18888 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
18889 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
18890 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
18891 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
18892 /// build per plane and pass serves the whole frame. The pipeline builds
18893 /// an `EdgeCtx` per superblock-row band rather than per frame, which
18894 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
18895 static LVL_CACHE: std::cell::RefCell<
18896 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
18897 > = const { std::cell::RefCell::new(Vec::new()) };
18898}
18899
18900/// `lf_level` over the whole `(base level, ref frame)` domain -- see
18901/// [`LVL_CACHE`]. `lf_level`'s own first step is
18902/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
18903/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
18904fn lvl_table(
18905 lf: &LoopFilterParams,
18906 plane_idx: usize,
18907 dir: usize,
18908 base0: i32,
18909 fctx: &crate::decode::FrameCtx,
18910) -> [[u8; 15]; 64] {
18911 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18912 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
18913 if let Some(t) = LVL_CACHE.with(|c| {
18914 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
18915 }) {
18916 return t;
18917 }
18918 let mut lvl = [[0u8; 15]; 64];
18919 for (b, row) in lvl.iter_mut().enumerate() {
18920 for (r, cell) in row.iter_mut().enumerate() {
18921 *cell =
18922 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
18923 }
18924 }
18925 LVL_CACHE.with(|c| {
18926 let mut c = c.borrow_mut();
18927 if c.len() >= 8 {
18928 c.remove(0);
18929 }
18930 c.push((key, lvl));
18931 });
18932 lvl
18933}
18934
18935/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18936/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18937/// that a coded block's transform is always its own full size -- so a TU
18938/// edge is always also a PU edge, and the "both sides skipped, not a PU
18939/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18940/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18941/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18942/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
18943/// seven values that used to be re-passed per 4-pixel edge group -- half of
18944/// them on the stack, into an `inline(never)` body -- plus libaom's
18945/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
18946/// filter level for every `(base level, ref frame)` pair once per frame
18947/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
18948struct EdgeCtx<'a> {
18949 lf: &'a LoopFilterParams,
18950 n: &'a Neighbours,
18951 fctx: &'a crate::decode::FrameCtx,
18952 plane_idx: usize,
18953 dir: usize,
18954 chroma: bool,
18955 seg_lf_active: bool,
18956 /// `delta_lf_grid`'s column for this plane and direction.
18957 delta_idx: usize,
18958 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
18959 /// chroma.
18960 step: usize,
18961 /// This pass's own `lf.level[..]`, the LUT's base.
18962 base0: i32,
18963 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
18964 /// override -- the whole domain, since a level is `0..=63` and a ref
18965 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
18966 /// entries and is indexed by the ref frame's magnitude).
18967 lvl: [[u8; 15]; 64],
18968}
18969
18970impl<'a> EdgeCtx<'a> {
18971 fn new(
18972 lf: &'a LoopFilterParams,
18973 n: &'a Neighbours,
18974 plane_idx: usize,
18975 dir: usize,
18976 chroma: bool,
18977 seg_lf_active: bool,
18978 fctx: &'a crate::decode::FrameCtx,
18979 ) -> Self {
18980 let base0 = i32::from(if plane_idx == 0 {
18981 lf.level[dir]
18982 } else if plane_idx == 1 {
18983 lf.level[2]
18984 } else {
18985 lf.level[3]
18986 });
18987 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
18988 Self {
18989 lf,
18990 n,
18991 fctx,
18992 plane_idx,
18993 dir,
18994 chroma,
18995 seg_lf_active,
18996 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
18997 step: if chroma { 2 } else { 1 },
18998 base0,
18999 lvl,
19000 }
19001 }
19002
19003 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
19004 /// override it (which is every frame that codes no segmentation).
19005 #[inline(always)]
19006 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
19007 if self.seg_lf_active {
19008 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
19009 }
19010 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
19011 debug_assert!((-7..=7).contains(&ref_frame));
19012 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
19013 i32::from(self.lvl[b][r])
19014 }
19015}
19016
19017/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
19018/// no-segmentation, no-delta-LF path and to this decoder's own invariant
19019/// that a coded block's transform is always its own full size -- so a TU
19020/// edge is always also a PU edge, and the "both sides skipped, not a PU
19021/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
19022/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
19023/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
19024#[inline(always)]
19025fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
19026 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
19027 let cur_tx = if c.dir == 0 {
19028 tx_px_at(c.n, c.chroma, mi_r, mi_c)
19029 } else {
19030 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
19031 };
19032 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
19033 // test is a mask, not the hardware `divl` this used to emit (10.7% of
19034 // `edge_params`' own samples sat on that divide's result test).
19035 //
19036 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
19037 // the covering transform does not start at), so this head is inlined
19038 // into the deblock loops and only survivors pay the call and the
19039 // register-spilling prologue of the body below.
19040 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
19041 return None;
19042 }
19043 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
19044}
19045
19046/// [`edge_params`] past its transform-alignment gate.
19047#[inline(never)]
19048fn edge_params_body(
19049 c: &EdgeCtx,
19050 x0: usize,
19051 y0: usize,
19052 mi_r: usize,
19053 mi_c: usize,
19054 cur_tx: u32,
19055) -> Option<(u8, i32)> {
19056 let n = c.n;
19057 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
19058 // The previous cell must keep the odd parity `plane_to_mi` just
19059 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
19060 // not the other half of this one.
19061 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
19062 (mi_r, mi_c - c.step)
19063 } else {
19064 (mi_r - c.step, mi_c)
19065 };
19066 let pv_tx = if c.dir == 0 {
19067 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
19068 } else {
19069 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
19070 };
19071 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
19072 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
19073 let pv_delta_lf =
19074 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
19075
19076 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
19077 // SKIPPED INTER blocks is filtered only when it is also a prediction
19078 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
19079 // omission of this term (on the stale invariant "a coded block's transform
19080 // is always its own full size", which var-tx broke) had us filtering an
19081 // interior 8-px lattice the reference never touches: on the pinned 192x68
19082 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
19083 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
19084 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
19085 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
19086 // edge of a sub-8x8 group is a prediction edge, even though the group's
19087 // bottom/right mi does not start there. Comparing mi origins instead is
19088 // the same test only while the block's own origin is aligned to its
19089 // size, which a 4x4 luma block read at the `| 1` mi is not.
19090 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
19091 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
19092 let (org_px, dim_mi) = if c.dir == 0 {
19093 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
19094 } else {
19095 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
19096 };
19097 let pu_edge = if c.chroma {
19098 let plane_dim = (dim_mi * MI / 2).max(4);
19099 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
19100 } else {
19101 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
19102 };
19103 if !pu_edge
19104 && cur_ref != 0
19105 && pv_ref != 0
19106 && n.skip_at(mi_r, mi_c)
19107 && n.skip_at(pv_mi_r, pv_mi_c)
19108 {
19109 return None;
19110 }
19111 let (cur_seg, pv_seg) = if c.seg_lf_active {
19112 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
19113 } else {
19114 (0, 0)
19115 };
19116 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
19117 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
19118 if cur_level == 0 && pv_level == 0 {
19119 return None;
19120 }
19121 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
19122 let len: u8 = if c.chroma {
19123 if dim == 0 { 4 } else { 6 }
19124 } else {
19125 [4, 8, 14, 14, 14][dim]
19126 };
19127 let level = if cur_level != 0 { cur_level } else { pv_level };
19128 hit!(DEBLOCK_HITS);
19129 Some((len, level))
19130}
19131
19132/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
19133fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
19134 let sharpness = i32::from(sharpness);
19135 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
19136 let mut lim = level >> shift;
19137 if sharpness > 0 {
19138 lim = lim.min(9 - sharpness);
19139 }
19140 lim = lim.max(1);
19141 (2 * (level + 2) + lim, lim, level >> 4)
19142}
19143
19144#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19145fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
19146 // libaom's `signed_char_clamp_high`: the clamp range scales with
19147 // `128 << (bit_depth - 8)` alongside the centering constant below.
19148 let scale = 1i32 << (bit_depth(fctx) - 8);
19149 v.clamp(-128 * scale, 128 * scale - 1)
19150}
19151
19152fn round_pow2(v: i32, n: u32) -> i32 {
19153 (v + (1 << (n - 1))) >> n
19154}
19155
19156/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
19157/// fallback.
19158fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
19159 if !mask {
19160 return [p1, p0, q0, q1];
19161 }
19162 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
19163 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
19164 // this kernel's eight clamps, and this kernel runs per deblocked sample.
19165 // Same bound, resolved once.
19166 let scale = 1i32 << (bit_depth(fctx) - 8);
19167 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
19168 let centre = 128i32 * scale;
19169 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
19170 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
19171 let filter = sclamp(outer + 3 * (qs0 - ps0));
19172 let filter1 = sclamp(filter + 4) >> 3;
19173 let filter2 = sclamp(filter + 3) >> 3;
19174 let oq0 = sclamp(qs0 - filter1) + centre;
19175 let op0 = sclamp(ps0 + filter2) + centre;
19176 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
19177 let oq1 = sclamp(qs1 - tap) + centre;
19178 let op1 = sclamp(ps1 + tap) + centre;
19179 [op1, op0, oq0, oq1]
19180}
19181
19182/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
19183/// `filter4`'s narrow taps.
19184#[allow(clippy::too_many_arguments)]
19185fn filter6(
19186 mask: bool,
19187 thresh: i32,
19188 flat: bool,
19189 p2: i32,
19190 p1: i32,
19191 p0: i32,
19192 q0: i32,
19193 q1: i32,
19194 q2: i32, fctx: &crate::decode::FrameCtx,
19195) -> [i32; 4] {
19196 if flat && mask {
19197 [
19198 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
19199 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
19200 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
19201 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
19202 ]
19203 } else {
19204 filter4(mask, thresh, p1, p0, q0, q1, fctx)
19205 }
19206}
19207
19208/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
19209#[allow(clippy::too_many_arguments)]
19210fn filter8(
19211 mask: bool,
19212 thresh: i32,
19213 flat: bool,
19214 p3: i32,
19215 p2: i32,
19216 p1: i32,
19217 p0: i32,
19218 q0: i32,
19219 q1: i32,
19220 q2: i32,
19221 q3: i32, fctx: &crate::decode::FrameCtx,
19222) -> [i32; 6] {
19223 if flat && mask {
19224 [
19225 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
19226 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
19227 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
19228 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
19229 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
19230 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
19231 ]
19232 } else {
19233 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
19234 [p2, op1, op0, oq0, oq1, q2]
19235 }
19236}
19237
19238/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
19239/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
19240/// way -- they are only ever taps here, never written).
19241#[allow(clippy::too_many_arguments)]
19242fn filter14(
19243 mask: bool,
19244 thresh: i32,
19245 flat: bool,
19246 flat2: bool,
19247 p6: i32,
19248 p5: i32,
19249 p4: i32,
19250 p3: i32,
19251 p2: i32,
19252 p1: i32,
19253 p0: i32,
19254 q0: i32,
19255 q1: i32,
19256 q2: i32,
19257 q3: i32,
19258 q4: i32,
19259 q5: i32,
19260 q6: i32, fctx: &crate::decode::FrameCtx,
19261) -> [i32; 12] {
19262 if flat2 && flat && mask {
19263 [
19264 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
19265 round_pow2(
19266 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
19267 4,
19268 ),
19269 round_pow2(
19270 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
19271 4,
19272 ),
19273 round_pow2(
19274 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
19275 4,
19276 ),
19277 round_pow2(
19278 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
19279 4,
19280 ),
19281 round_pow2(
19282 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
19283 4,
19284 ),
19285 round_pow2(
19286 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
19287 4,
19288 ),
19289 round_pow2(
19290 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
19291 4,
19292 ),
19293 round_pow2(
19294 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
19295 4,
19296 ),
19297 round_pow2(
19298 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
19299 4,
19300 ),
19301 round_pow2(
19302 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
19303 4,
19304 ),
19305 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
19306 ]
19307 } else {
19308 let [op2, op1, op0, oq0, oq1, oq2] =
19309 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
19310 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
19311 }
19312}
19313
19314/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
19315/// the first (`q0`) sample past the edge, `outer_stride` advances to the
19316/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
19317/// the next along the edge's own filtering direction.
19318#[allow(clippy::too_many_arguments)]
19319fn filter_edge(
19320 data: &mut [u16],
19321 base: usize,
19322 outer_stride: isize,
19323 tap_stride: isize,
19324 len: u8,
19325 level: i32,
19326 sharpness: u8, fctx: &crate::decode::FrameCtx,
19327) {
19328 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19329 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
19330 // every 8-bit threshold (including the flat masks' fixed `1`) is
19331 // compared against a raw pixel difference on the stream's own bit-depth
19332 // scale, so each is shifted left by `bit_depth - 8` before use.
19333 let shift = bit_depth(fctx) - 8;
19334 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
19335 let flat_thresh = 1i32 << shift;
19336 let smax = sample_max(fctx);
19337 for i in 0..4isize {
19338 let center = (base as isize + i * outer_stride) as usize;
19339 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
19340 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
19341 match len {
19342 4 => {
19343 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
19344 let mask = (p1 - p0).abs() <= limit
19345 && (q1 - q0).abs() <= limit
19346 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19347 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
19348 data[idx(-2)] = op1.clamp(0, smax) as u16;
19349 data[idx(-1)] = op0.clamp(0, smax) as u16;
19350 data[idx(0)] = oq0.clamp(0, smax) as u16;
19351 data[idx(1)] = oq1.clamp(0, smax) as u16;
19352 }
19353 6 => {
19354 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
19355 let mask = (p2 - p1).abs() <= limit
19356 && (p1 - p0).abs() <= limit
19357 && (q1 - q0).abs() <= limit
19358 && (q2 - q1).abs() <= limit
19359 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19360 let flat = (p1 - p0).abs() <= flat_thresh
19361 && (q1 - q0).abs() <= flat_thresh
19362 && (p2 - p0).abs() <= flat_thresh
19363 && (q2 - q0).abs() <= flat_thresh;
19364 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
19365 data[idx(-2)] = op1.clamp(0, smax) as u16;
19366 data[idx(-1)] = op0.clamp(0, smax) as u16;
19367 data[idx(0)] = oq0.clamp(0, smax) as u16;
19368 data[idx(1)] = oq1.clamp(0, smax) as u16;
19369 }
19370 8 => {
19371 let (p3, p2, p1, p0, q0, q1, q2, q3) =
19372 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
19373 let mask = (p3 - p2).abs() <= limit
19374 && (p2 - p1).abs() <= limit
19375 && (p1 - p0).abs() <= limit
19376 && (q1 - q0).abs() <= limit
19377 && (q2 - q1).abs() <= limit
19378 && (q3 - q2).abs() <= limit
19379 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19380 let flat = (p1 - p0).abs() <= flat_thresh
19381 && (q1 - q0).abs() <= flat_thresh
19382 && (p2 - p0).abs() <= flat_thresh
19383 && (q2 - q0).abs() <= flat_thresh
19384 && (p3 - p0).abs() <= flat_thresh
19385 && (q3 - q0).abs() <= flat_thresh;
19386 let [op2, op1, op0, oq0, oq1, oq2] =
19387 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
19388 data[idx(-3)] = op2.clamp(0, smax) as u16;
19389 data[idx(-2)] = op1.clamp(0, smax) as u16;
19390 data[idx(-1)] = op0.clamp(0, smax) as u16;
19391 data[idx(0)] = oq0.clamp(0, smax) as u16;
19392 data[idx(1)] = oq1.clamp(0, smax) as u16;
19393 data[idx(2)] = oq2.clamp(0, smax) as u16;
19394 }
19395 _ => {
19396 let (p6, p5, p4, p3, p2, p1, p0) =
19397 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
19398 let (q0, q1, q2, q3, q4, q5, q6) =
19399 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
19400 let mask = (p3 - p2).abs() <= limit
19401 && (p2 - p1).abs() <= limit
19402 && (p1 - p0).abs() <= limit
19403 && (q1 - q0).abs() <= limit
19404 && (q2 - q1).abs() <= limit
19405 && (q3 - q2).abs() <= limit
19406 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19407 let flat = (p1 - p0).abs() <= flat_thresh
19408 && (q1 - q0).abs() <= flat_thresh
19409 && (p2 - p0).abs() <= flat_thresh
19410 && (q2 - q0).abs() <= flat_thresh
19411 && (p3 - p0).abs() <= flat_thresh
19412 && (q3 - q0).abs() <= flat_thresh;
19413 let flat2 = (p4 - p0).abs() <= flat_thresh
19414 && (q4 - q0).abs() <= flat_thresh
19415 && (p5 - p0).abs() <= flat_thresh
19416 && (q5 - q0).abs() <= flat_thresh
19417 && (p6 - p0).abs() <= flat_thresh
19418 && (q6 - q0).abs() <= flat_thresh;
19419 let out = filter14(
19420 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
19421 q6, fctx,
19422 );
19423 for (k, v) in (-6..=5isize).zip(out) {
19424 data[idx(k)] = v.clamp(0, smax) as u16;
19425 }
19426 }
19427 }
19428 }
19429}
19430
19431/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
19432/// 4K decode's self time, spent almost entirely on the per-tap strided
19433/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
19434/// arithmetic). Nothing here is spec logic: the same masks, the same
19435/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
19436/// rounding, done for 16 edge lines at once.
19437///
19438/// 16-bit lanes are exact for every value these filters see. Samples are in
19439/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
19440/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
19441/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
19442/// wide kernels' weights each total 8 or 16, so their sums (at most
19443/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
19444/// rounding shift, which is the unsigned shift the scalar's non-negative sum
19445/// takes.
19446#[cfg(target_arch = "x86_64")]
19447#[allow(unsafe_code)]
19448#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
19449mod deblock_simd {
19450 use std::arch::x86_64::*;
19451
19452 /// `a <= b` lane-wise, as a full-width mask.
19453 ///
19454 /// # Safety
19455 /// Requires AVX2.
19456 #[target_feature(enable = "avx2")]
19457 #[inline]
19458 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
19459 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
19460 }
19461
19462 /// `|a - b|` lane-wise.
19463 ///
19464 /// # Safety
19465 /// Requires AVX2.
19466 #[target_feature(enable = "avx2")]
19467 #[inline]
19468 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
19469 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
19470 }
19471
19472 /// `signed_char_clamp_high`, lane-wise.
19473 ///
19474 /// # Safety
19475 /// Requires AVX2.
19476 #[target_feature(enable = "avx2")]
19477 #[inline]
19478 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
19479 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
19480 }
19481
19482 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
19483 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
19484 ///
19485 /// # Safety
19486 /// Requires AVX2.
19487 #[target_feature(enable = "avx2")]
19488 unsafe fn transpose16(t: &mut [__m256i; 16]) {
19489 let mut a = [_mm256_setzero_si256(); 16];
19490 for k in 0..8 {
19491 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
19492 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
19493 }
19494 let mut b = [_mm256_setzero_si256(); 16];
19495 for g in 0..4 {
19496 let s = 4 * g;
19497 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
19498 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
19499 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
19500 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
19501 }
19502 let mut c = [_mm256_setzero_si256(); 16];
19503 for g in 0..2 {
19504 let s = 8 * g;
19505 for j in 0..4 {
19506 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
19507 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
19508 }
19509 }
19510 for i in 0..8 {
19511 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
19512 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
19513 }
19514 }
19515
19516 /// The wide kernels' tap weights, in tap order and with the spec's
19517 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
19518 /// over `p3..q3`, `filter14` over `p6..q6`.
19519 const W6: [[i16; 6]; 4] = [
19520 [3, 2, 2, 1, 0, 0],
19521 [1, 2, 2, 2, 1, 0],
19522 [0, 1, 2, 2, 2, 1],
19523 [0, 0, 1, 2, 2, 3],
19524 ];
19525 const W8: [[i16; 8]; 6] = [
19526 [3, 2, 1, 1, 1, 0, 0, 0],
19527 [2, 1, 2, 1, 1, 1, 0, 0],
19528 [1, 1, 1, 2, 1, 1, 1, 0],
19529 [0, 1, 1, 1, 2, 1, 1, 1],
19530 [0, 0, 1, 1, 1, 2, 1, 2],
19531 [0, 0, 0, 1, 1, 1, 2, 3],
19532 ];
19533 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
19534 const W14: [[i16; 14]; 12] = [
19535 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
19536 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
19537 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
19538 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
19539 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
19540 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
19541 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
19542 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
19543 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
19544 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
19545 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
19546 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
19547 ];
19548
19549 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
19550 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
19551 /// below `1 << 16`, so the logical shift is the arithmetic one.
19552 ///
19553 /// # Safety
19554 /// Requires AVX2.
19555 ///
19556 /// lane-deblock: the tap count, the weights and the shift are all const
19557 /// here (they were slice parameters, which left the weight `match` as a
19558 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
19559 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
19560 #[target_feature(enable = "avx2")]
19561 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
19562 unsafe fn wsum<const N: usize, const SHIFT: i32>(
19563 taps: &[__m256i; N],
19564 w: &[i16; N],
19565 ) -> __m256i {
19566 let mut s = _mm256_setzero_si256();
19567 for i in 0..N {
19568 match w[i] {
19569 0 => {}
19570 1 => s = _mm256_add_epi16(s, taps[i]),
19571 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
19572 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
19573 }
19574 }
19575 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
19576 if SHIFT == 3 {
19577 _mm256_srli_epi16(s, 3)
19578 } else {
19579 _mm256_srli_epi16(s, 4)
19580 }
19581 }
19582
19583 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
19584 /// `t[8]`; the filtered taps are written back in place. Returns `false`
19585 /// when the filter mask is empty on every one of the 16 lines -- nothing
19586 /// was written and the caller can skip the whole write-back.
19587 ///
19588 /// # Safety
19589 /// Requires AVX2.
19590 ///
19591 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
19592 /// its own kernel holding only its own taps, and every wide row is
19593 /// clamped straight into `t` instead of into a shared twelve-entry
19594 /// result array (which the register allocator spilled -- 35% of this
19595 /// kernel's samples were `vmovdqa` to the stack).
19596 #[target_feature(enable = "avx2")]
19597 #[allow(clippy::too_many_arguments)]
19598 unsafe fn filter16<const LEN: u8>(
19599 t: &mut [__m256i; 16],
19600 blimit: i32,
19601 limit: i32,
19602 hev_thr: i32,
19603 flat_thresh: i32,
19604 scale: i32,
19605 smax: i32,
19606 ) -> bool {
19607 let lim = _mm256_set1_epi16(limit as i16);
19608 let blim = _mm256_set1_epi16(blimit as i16);
19609 let hthr = _mm256_set1_epi16(hev_thr as i16);
19610 let fthr = _mm256_set1_epi16(flat_thresh as i16);
19611 let zero = _mm256_setzero_si256();
19612 let smaxv = _mm256_set1_epi16(smax as i16);
19613 macro_rules! put {
19614 ($i:expr, $v:expr) => {
19615 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
19616 };
19617 }
19618 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
19619 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
19620
19621 // `highbd_filter_mask`: the neighbour steps this kernel's length
19622 // reaches, plus the shared `blimit` term.
19623 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
19624 let mut md = d1;
19625 if LEN >= 6 {
19626 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
19627 }
19628 if LEN >= 8 {
19629 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
19630 }
19631 let bl = _mm256_add_epi16(
19632 _mm256_slli_epi16(ad(p0, q0), 1),
19633 _mm256_srli_epi16(ad(p1, q1), 1),
19634 );
19635 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
19636 // lane-deblock2: an empty mask leaves every tap at its loaded value
19637 // (the flat masks are `& mask`, so they are empty too, and the final
19638 // clamp is the identity on samples that came out of the plane), so
19639 // the whole write-back -- including the vertical edge's second
19640 // transpose -- is dead.
19641 if _mm256_testz_si256(mask, mask) != 0 {
19642 return false;
19643 }
19644 let hev = _mm256_cmpgt_epi16(d1, hthr);
19645
19646 // `filter4`, in the centred domain.
19647 let centre = _mm256_set1_epi16((128 * scale) as i16);
19648 let lo = _mm256_set1_epi16((-128 * scale) as i16);
19649 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
19650 let ps1 = _mm256_sub_epi16(p1, centre);
19651 let ps0 = _mm256_sub_epi16(p0, centre);
19652 let qs0 = _mm256_sub_epi16(q0, centre);
19653 let qs1 = _mm256_sub_epi16(q1, centre);
19654 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
19655 let f = sclamp(
19656 _mm256_add_epi16(
19657 outer,
19658 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
19659 ),
19660 lo,
19661 hi,
19662 );
19663 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
19664 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
19665 let tap = _mm256_andnot_si256(
19666 hev,
19667 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
19668 );
19669 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
19670 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
19671 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
19672 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
19673 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
19674 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
19675 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
19676 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
19677 if LEN == 4 {
19678 put!(6, b_p1);
19679 put!(7, b_p0);
19680 put!(8, b_q0);
19681 put!(9, b_q1);
19682 return true;
19683 }
19684
19685 // `highbd_flat_mask4`, over the same reach as this length's mask.
19686 let mut fl = _mm256_max_epi16(
19687 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
19688 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
19689 );
19690 if LEN >= 8 {
19691 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
19692 }
19693 let flat = _mm256_and_si256(le(fl, fthr), mask);
19694 let any_flat = _mm256_testz_si256(flat, flat) == 0;
19695 if LEN == 6 {
19696 if any_flat {
19697 let taps = [p2, p1, p0, q0, q1, q2];
19698 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
19699 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
19700 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
19701 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
19702 } else {
19703 put!(6, b_p1);
19704 put!(7, b_p0);
19705 put!(8, b_q0);
19706 put!(9, b_q1);
19707 }
19708 return true;
19709 }
19710
19711 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
19712 let (o0, o1, o2, o3, o4, o5) = if any_flat {
19713 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
19714 (
19715 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
19716 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
19717 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
19718 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
19719 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
19720 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
19721 )
19722 } else {
19723 (p2, b_p1, b_p0, b_q0, b_q1, q2)
19724 };
19725 macro_rules! put8 {
19726 () => {
19727 put!(5, o0);
19728 put!(6, o1);
19729 put!(7, o2);
19730 put!(8, o3);
19731 put!(9, o4);
19732 put!(10, o5);
19733 };
19734 }
19735 if LEN == 8 {
19736 put8!();
19737 return true;
19738 }
19739
19740 let fl2 = _mm256_max_epi16(
19741 _mm256_max_epi16(
19742 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
19743 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
19744 ),
19745 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
19746 );
19747 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
19748 if _mm256_testz_si256(flat2, flat2) != 0 {
19749 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
19750 // taps they were loaded with, exactly as the blend would.
19751 put8!();
19752 return true;
19753 }
19754 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
19755 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
19756 // j is a constant vector with two negative and two positive
19757 // entries), so each output costs one add, one sub and the rounding
19758 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
19759 // become 44. Exact: every partial sum is taken mod 2^16 by
19760 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
19761 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
19762 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
19763 // it against `filter_edge` at 8/10/12-bit.
19764 let mut s = _mm256_add_epi16(
19765 _mm256_add_epi16(
19766 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
19767 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
19768 ),
19769 _mm256_add_epi16(
19770 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
19771 q0,
19772 ),
19773 );
19774 let add2 = |a, b| _mm256_add_epi16(a, b);
19775 macro_rules! row14 {
19776 ($idx:literal, $base:expr) => {
19777 put!(
19778 $idx,
19779 _mm256_blendv_epi8(
19780 $base,
19781 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
19782 flat2,
19783 )
19784 );
19785 };
19786 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
19787 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
19788 row14!($idx, $base);
19789 };
19790 }
19791 row14!(2, p5);
19792 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
19793 row14!(4, p3, add2(p2, q2), add2(p6, p5));
19794 row14!(5, o0, add2(p1, q3), add2(p6, p4));
19795 row14!(6, o1, add2(p0, q4), add2(p6, p3));
19796 row14!(7, o2, add2(q0, q5), add2(p6, p2));
19797 row14!(8, o3, add2(q1, q6), add2(p6, p1));
19798 row14!(9, o4, add2(q2, q6), add2(p5, p0));
19799 row14!(10, o5, add2(q3, q6), add2(p4, q0));
19800 row14!(11, q3, add2(q4, q6), add2(p3, q1));
19801 row14!(12, q4, add2(q5, q6), add2(p2, q2));
19802 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
19803 true
19804 }
19805
19806 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
19807 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
19808 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
19809 /// consecutive columns with each tap a whole row segment.
19810 ///
19811 /// # Safety
19812 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
19813 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
19814 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
19815 /// must be inside it.
19816 #[target_feature(enable = "avx2")]
19817 #[allow(clippy::too_many_arguments)]
19818 pub unsafe fn edge16(
19819 data: &mut [u16],
19820 base: usize,
19821 stride: usize,
19822 vertical: bool,
19823 len: u8,
19824 blimit: i32,
19825 limit: i32,
19826 hev_thr: i32,
19827 flat_thresh: i32,
19828 scale: i32,
19829 smax: i32,
19830 ) {
19831 let p = data.as_mut_ptr();
19832 let mut t = [_mm256_setzero_si256(); 16];
19833 // The taps this length reads, as `t` indices.
19834 let (lo, hi) = match len {
19835 4 => (6, 10),
19836 6 => (5, 11),
19837 8 => (4, 12),
19838 _ => (1, 15),
19839 };
19840 if vertical {
19841 for j in 0..16 {
19842 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
19843 }
19844 transpose16(&mut t);
19845 } else {
19846 let top = base - 8 * stride;
19847 for i in lo..hi {
19848 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
19849 }
19850 }
19851 // lane-deblock2: one monomorphised kernel per edge length, and an
19852 // empty filter mask returns without any write-back at all.
19853 let modified = match len {
19854 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19855 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19856 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19857 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19858 };
19859 if !modified {
19860 return;
19861 }
19862 if vertical {
19863 transpose16(&mut t);
19864 for j in 0..16 {
19865 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
19866 }
19867 } else {
19868 let top = base - 8 * stride;
19869 let (a, b) = match len {
19870 4 | 6 => (6, 10),
19871 8 => (5, 11),
19872 _ => (2, 14),
19873 };
19874 for i in a..b {
19875 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
19876 }
19877 }
19878 }
19879}
19880
19881/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
19882/// output. Returns `false` when this build or CPU has no kernel, leaving the
19883/// caller on the scalar path.
19884#[allow(unused_variables)]
19885fn filter_edge16(
19886 data: &mut [u16],
19887 base: usize,
19888 stride: usize,
19889 vertical: bool,
19890 len: u8,
19891 level: i32,
19892 sharpness: u8, fctx: &crate::decode::FrameCtx,
19893) -> bool {
19894 #[cfg(target_arch = "x86_64")]
19895 {
19896 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
19897 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19898 let shift = bit_depth(fctx) - 8;
19899 // SAFETY: the avx2 arm is reached only when the CPU reports it,
19900 // and `deblock_plane` checks the kernel's edge bounds.
19901 #[allow(unsafe_code)]
19902 unsafe {
19903 deblock_simd::edge16(
19904 data,
19905 base,
19906 stride,
19907 vertical,
19908 len,
19909 blimit << shift,
19910 limit << shift,
19911 hev_thr << shift,
19912 1 << shift,
19913 1 << shift,
19914 sample_max(fctx),
19915 )
19916 };
19917 return true;
19918 }
19919 }
19920 false
19921}
19922
19923/// One plane's worth of spec 7.14: every vertical edge across the plane,
19924/// then every horizontal edge (the order the spec and libaom both use).
19925fn deblock_plane(
19926 plane: &mut PlaneBuf<'static>,
19927 plane_idx: usize,
19928 lf: &LoopFilterParams,
19929 n: &Neighbours,
19930 frame_width: usize,
19931 frame_height: usize, fctx: &crate::decode::FrameCtx,
19932) {
19933 // spec 7.14's order: this plane's whole vertical pass, then its whole
19934 // horizontal one. lane-pipefilt split the two into one row-ranged
19935 // function so the per-superblock-row pipeline can run them a band at a
19936 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
19937 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
19938 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
19939}
19940
19941/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
19942/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
19943///
19944/// A row span is a legal cut of either pass because a band boundary is a
19945/// multiple of 16 rows and every edge's kernel stays inside its own
19946/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
19947/// what keep the two passes in spec order across bands.
19948#[allow(clippy::too_many_arguments)]
19949fn deblock_plane_span(
19950 plane: &mut PlaneBuf<'static>,
19951 plane_idx: usize,
19952 lf: &LoopFilterParams,
19953 n: &Neighbours,
19954 frame_width: usize,
19955 frame_height: usize,
19956 span_lo: usize,
19957 span_hi: usize,
19958 horz: bool,
19959 fctx: &crate::decode::FrameCtx,
19960) {
19961 let chroma = plane_idx != 0;
19962 // r7: libaom clips the deblock loop to the CODED frame's own
19963 // width/height, not the mi-aligned `true_width`/`true_height` margin
19964 // (the padding up to the next 8-pixel/superblock boundary that
19965 // reconstruction still fills in but the loop filter never visits).
19966 // Confirmed against the superres gate: with the margin included, the
19967 // last coded mi column's horizontal edges were filtered when libaom's
19968 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
19969 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
19970 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
19971 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
19972 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
19973 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
19974 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
19975 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
19976 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
19977 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
19978 // all in columns 64..67; frame 0 survived because that edge carried no
19979 // filter level there). r7's superres measurement is preserved: its frame
19980 // was already 8-aligned, so this bound equals `frame_width` there and
19981 // still excludes the superblock padding up to `true_width`.
19982 let (cw, ch) = if chroma {
19983 (frame_width.div_ceil(2), frame_height.div_ceil(2))
19984 } else {
19985 (frame_width, frame_height)
19986 };
19987 let (tw, th, stride) = (
19988 plane.true_width.min(cw),
19989 plane.true_height.min(ch),
19990 plane.width,
19991 );
19992 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
19993 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
19994 }
19995 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
19996 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
19997 // kernel. The swap is order-preserving: a filtered group overlaps only
19998 // groups along the edge it sits on -- the vertical pass's writes at
19999 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
20000 // dependence is on ascending `x0` within a row, which stays the outer
20001 // loop's order, and rows remain independent (horizontal pass mirrored).
20002 let rows = plane.data.len() / stride.max(1);
20003 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
20004 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
20005 // bands along the axis whose writes are disjoint. A vertical edge's
20006 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
20007 // row bands never touch each other; a horizontal edge's groups write rows
20008 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
20009 // read the mode-info grids immutably. The grouping a band starts with is
20010 // free: every 4-row (4-column) group's output is a pure function of that
20011 // group, whether it goes through `filter_edge16` with three neighbours or
20012 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
20013 // group ever straddles one.
20014 // lane-perf10 merge: the output plane is owned (perf10 made mutable
20015 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
20016 // the bands below never clone it concurrently.
20017 plane.data.to_mut();
20018 let threads = crate::par::filter_threads();
20019 let sp = crate::par::Shared::new(plane);
20020 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
20021 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
20022 Vec::new()
20023 } else {
20024 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
20025 .into_iter()
20026 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
20027 .collect()
20028 };
20029 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
20030 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
20031 // no other band touches (see `Shared`'s own corner-cut note).
20032 #[allow(unsafe_code)]
20033 let plane = unsafe { sp.get() };
20034 // lane-deblock2: this band's own level table and pass constants,
20035 // built once per band instead of re-derived per 4-pixel edge.
20036 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
20037 let mut x0 = 4usize;
20038 while x0 < tw {
20039 let mut y0 = y_lo;
20040 while y0 < y_hi {
20041 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
20042 let ps: [Option<(u8, i32)>; 4] =
20043 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
20044 if let Some((len, level)) = ps[0] {
20045 if ps.iter().all(|p| *p == ps[0])
20046 && filter_edge16(
20047 plane.data.to_mut(),
20048 y0 * stride + x0,
20049 stride,
20050 true,
20051 len,
20052 level,
20053 lf.sharpness, fctx,
20054 )
20055 {
20056 y0 += 16;
20057 continue;
20058 }
20059 }
20060 for (k, p) in ps.iter().enumerate() {
20061 if let Some((len, level)) = *p {
20062 filter_edge(
20063 plane.data.to_mut(),
20064 (y0 + 4 * k) * stride + x0,
20065 stride as isize,
20066 1,
20067 len,
20068 level,
20069 lf.sharpness, fctx,
20070 );
20071 }
20072 }
20073 y0 += 16;
20074 continue;
20075 }
20076 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
20077 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
20078 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
20079 }
20080 filter_edge(
20081 plane.data.to_mut(),
20082 y0 * stride + x0,
20083 stride as isize,
20084 1,
20085 len,
20086 level,
20087 lf.sharpness, fctx,
20088 );
20089 }
20090 y0 += 4;
20091 }
20092 x0 += 4;
20093 }
20094 });
20095 // The horizontal pass runs only after the WHOLE vertical pass of this
20096 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
20097 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
20098 Vec::new()
20099 } else {
20100 crate::par::bands(tw.div_ceil(16), threads)
20101 .into_iter()
20102 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
20103 .collect()
20104 };
20105 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
20106 // SAFETY: this band writes only columns `x_lo..x_hi`.
20107 #[allow(unsafe_code)]
20108 let plane = unsafe { sp.get() };
20109 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
20110 let mut y0 = sp_lo.max(4);
20111 while y0 < sp_hi {
20112 let mut x0 = x_lo;
20113 while x0 < x_hi {
20114 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
20115 let ps: [Option<(u8, i32)>; 4] =
20116 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
20117 if let Some((len, level)) = ps[0] {
20118 if ps.iter().all(|p| *p == ps[0])
20119 && filter_edge16(
20120 plane.data.to_mut(),
20121 y0 * stride + x0,
20122 stride,
20123 false,
20124 len,
20125 level,
20126 lf.sharpness, fctx,
20127 )
20128 {
20129 x0 += 16;
20130 continue;
20131 }
20132 }
20133 for (k, p) in ps.iter().enumerate() {
20134 if let Some((len, level)) = *p {
20135 filter_edge(
20136 plane.data.to_mut(),
20137 y0 * stride + x0 + 4 * k,
20138 1,
20139 stride as isize,
20140 len,
20141 level,
20142 lf.sharpness, fctx,
20143 );
20144 }
20145 }
20146 x0 += 16;
20147 continue;
20148 }
20149 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
20150 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
20151 && plane_idx == 0
20152 && x0 == 44
20153 {
20154 eprintln!(
20155 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
20156 lf.sharpness
20157 );
20158 }
20159 filter_edge(
20160 plane.data.to_mut(),
20161 y0 * stride + x0,
20162 1,
20163 stride as isize,
20164 len,
20165 level,
20166 lf.sharpness, fctx,
20167 );
20168 }
20169 x0 += 4;
20170 }
20171 y0 += 4;
20172 } });
20173}
20174
20175/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
20176/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
20177/// restoration is active, and a fresh LR destination per plane -- freshly
20178/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
20179/// sample written also takes a first-touch page fault. The buffers are handed
20180/// back here instead and refilled in place.
20181///
20182/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
20183/// stay on one thread: the frame thread allocates the snapshots and a filter
20184/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
20185/// into the pool from whichever worker ran it), so a per-thread pool leaked
20186/// whole-plane buffers into every worker it touched -- 19 MB a set, times
20187/// every pool thread the decode ever created. One shared pool with a hard
20188/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
20189/// many threads cycle through it; anything over the cap is freed.
20190static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
20191
20192/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
20193/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
20194/// flight cycle through far fewer.
20195const SCRATCH_CAP: usize = 32;
20196
20197/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
20198/// CAPACITY so a chroma-sized request does not permanently promote a
20199/// luma-sized allocation (every pooled buffer would drift to the largest
20200/// size otherwise). `None` when the pool is empty.
20201fn scratch_take(n: usize) -> Option<Vec<u16>> {
20202 let mut p = PLANE_SCRATCH.lock().unwrap();
20203 if p.is_empty() {
20204 return None;
20205 }
20206 let fit = p
20207 .iter()
20208 .enumerate()
20209 .filter(|(_, v)| v.capacity() >= n)
20210 .min_by_key(|(_, v)| v.capacity())
20211 .map(|(i, _)| i);
20212 let i = match fit {
20213 Some(i) => i,
20214 // Nothing big enough: grow the largest rather than a small one.
20215 None => p
20216 .iter()
20217 .enumerate()
20218 .max_by_key(|(_, v)| v.capacity())
20219 .map(|(i, _)| i)
20220 .expect("the pool is not empty"),
20221 };
20222 Some(p.swap_remove(i))
20223}
20224
20225/// A pooled buffer holding a copy of `src`.
20226fn scratch_from(src: &[u16]) -> Vec<u16> {
20227 let mut v = scratch_take(src.len()).unwrap_or_default();
20228 v.clear();
20229 v.extend_from_slice(src);
20230 v
20231}
20232
20233/// An empty pooled buffer, for a caller that fills it itself.
20234fn scratch_empty() -> Vec<u16> {
20235 let mut v = scratch_take(0).unwrap_or_default();
20236 v.clear();
20237 v
20238}
20239
20240/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
20241/// for a caller that writes every element it later reads (lane-copy: the
20242/// post-deblock snapshot writes 4 rows in 64 and reads no other).
20243fn scratch_sized(n: usize) -> Vec<u16> {
20244 let mut v = scratch_take(n).unwrap_or_default();
20245 if v.len() > n {
20246 v.truncate(n);
20247 } else if v.len() < n {
20248 v.resize(n, 0);
20249 }
20250 v
20251}
20252
20253/// A plane's post-deblock snapshot, its samples taken from the pool (every
20254/// other field is `usize`).
20255///
20256/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
20257/// boundary substitution reads the post-deblock plane at just four rows
20258/// around each interior stripe boundary (`row` outside
20259/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
20260/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
20261/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
20262/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
20263/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
20264/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
20265/// the pooled buffer keeps whatever a previous frame left there -- an
20266/// initialised value that no reader ever reaches.
20267fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
20268 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
20269}
20270
20271fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
20272 let mut data = scratch_sized(p.data.len());
20273 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
20274 let stripe_h = 64usize >> ss_y;
20275 let offset = 8usize >> ss_y;
20276 let mut b = stripe_h - offset;
20277 while b < rows {
20278 let (lo, hi) = (b - 2, (b + 2).min(rows));
20279 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
20280 b += stripe_h;
20281 }
20282 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
20283}
20284
20285/// The pre-filter reconstruction of one coded frame, plus the per-block state
20286/// the loop filters read.
20287///
20288/// The encoder's filter search ([`crate::filter_search::pick_filters`])
20289/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
20290/// sets to score each one, and the entropy decode and reconstruction it
20291/// repeats are identical every time -- both filters run after it, on the
20292/// finished planes. That re-parse was 24% of the encoder's profile. A caller
20293/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
20294/// alone through [`replay_filters`]; the result is the same picture the full
20295/// decode would have returned, because it is the same two calls on a copy of
20296/// the same planes.
20297pub(crate) struct FilterReplay {
20298 y: PlaneBuf<'static>,
20299 u: PlaneBuf<'static>,
20300 v: PlaneBuf<'static>,
20301 neighbours: Neighbours,
20302 frame_width: usize,
20303 frame_height: usize,
20304 width: usize,
20305 height: usize,
20306 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
20307 /// stash the cropped return path leaves behind.
20308 true_width: usize,
20309 true_height: usize,
20310 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
20311 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
20312 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
20313 /// 1080p frame's wall in allocation, not in filtering. Recycled here
20314 /// instead; the pool holds at most the six planes one candidate has live.
20315 scratch: Vec<Vec<u16>>,
20316 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
20317 /// post-deblock rows loop restoration substitutes at its stripe
20318 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
20319 /// rows) -- what [`replay_restoration`] filters, instead of decoding
20320 /// the re-coded tile a second time.
20321 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
20322 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
20323 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
20324 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
20325 /// no deblocking level, so every candidate of it used to copy the three
20326 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
20327 /// destinations are kept and only the units the last candidate touched
20328 /// are restored -- the same bytes, since a unit nobody wrote still holds
20329 /// the deblocked sample it was copied from.
20330 work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20331 wrote: Vec<u8>,
20332 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
20333 /// new candidate can only write MORE units than the old one needs no
20334 /// restore at all, since every unit CDEF writes it writes from the
20335 /// post-deblock source alone.
20336 work_cdef: Option<CdefParams>,
20337 /// The last deblocked planes and the levels that produced them.
20338 /// Deblocking depends on nothing else the search moves, and the search
20339 /// fixes the levels before it walks the CDEF strengths, so every
20340 /// candidate after the first of a level pair replays CDEF alone.
20341 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20342}
20343
20344thread_local! {
20345 /// Set by [`arm_filter_replay`] for the span of one decode.
20346 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20347 /// What that decode captured, until [`clear_filter_replay`].
20348 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
20349 const { std::cell::RefCell::new(None) };
20350}
20351
20352/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
20353pub(crate) fn arm_filter_replay() {
20354 REPLAY_ARMED.set(true);
20355}
20356
20357/// Test-only: force every filter candidate through a full decode, so a gate
20358/// can hold the replay against the decode it stands in for
20359/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
20360#[cfg(test)]
20361static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
20362
20363#[cfg(test)]
20364pub(crate) fn set_filter_replay_disabled(off: bool) {
20365 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
20366}
20367
20368// Test-only: run the capture decode `replay_final` replaced as well, and
20369// hold its picture and its `FilterStages` against the replay's
20370// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
20371// Thread-local, not a global: the filter stage runs on the frame thread the
20372// test itself drives, and a process-wide flag would put every test encoding
20373// in parallel with this one through the extra decode too.
20374#[cfg(test)]
20375thread_local! {
20376 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20377}
20378
20379#[cfg(test)]
20380pub(crate) fn set_verify_final_replay(on: bool) {
20381 VERIFY_FINAL.set(on);
20382}
20383
20384#[cfg(test)]
20385pub(crate) fn verify_final_replay() -> bool {
20386 VERIFY_FINAL.get()
20387}
20388
20389/// Drop the armed flag and anything captured: the tile it belongs to is done.
20390pub(crate) fn clear_filter_replay() {
20391 REPLAY_ARMED.set(false);
20392 REPLAY.with_borrow_mut(|r| *r = None);
20393}
20394
20395/// The capture itself, called from the decoder's own pre-filter point. Owns
20396/// copies of the planes, since the caller filters them in place.
20397fn capture_filter_replay(
20398 y: &PlaneBuf<'_>,
20399 u: &PlaneBuf<'_>,
20400 v: &PlaneBuf<'_>,
20401 neighbours: &Neighbours,
20402 frame_width: usize,
20403 frame_height: usize,
20404 width: usize,
20405 height: usize,
20406 true_width: usize,
20407 true_height: usize,
20408) {
20409 if !REPLAY_ARMED.replace(false) {
20410 return;
20411 }
20412 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
20413 REPLAY.with_borrow_mut(|slot| {
20414 *slot = Some(FilterReplay {
20415 y: own(y),
20416 u: own(u),
20417 v: own(v),
20418 neighbours: neighbours.clone(),
20419 frame_width,
20420 frame_height,
20421 width,
20422 height,
20423 true_width,
20424 true_height,
20425 scratch: Vec::new(),
20426 work: None,
20427 wrote: Vec::new(),
20428 work_cdef: None,
20429 final_luma: None,
20430 deblocked: None,
20431 });
20432 });
20433}
20434
20435/// Restores, from the post-deblock cache, every sample the previous CDEF
20436/// candidate may have written: for each unit row, the column span between
20437/// its first and last written unit (a superset of the written units, which
20438/// is what makes the copy contiguous -- and never more than the whole-plane
20439/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
20440/// 4 for 4:2:0 chroma.
20441fn restore_written(
20442 dst: &mut PlaneBuf<'static>,
20443 src: &PlaneBuf<'_>,
20444 wrote: &[u8],
20445 mask: u8,
20446 unit_cols: usize,
20447 unit: usize,
20448) {
20449 let w = dst.width;
20450 if w == 0 || unit_cols == 0 || wrote.is_empty() {
20451 return;
20452 }
20453 let rows = dst.data.len() / w;
20454 let s: &[u16] = &src.data;
20455 let d = dst.data.to_mut();
20456 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
20457 for (i, row) in wr.chunks(unit_cols).enumerate() {
20458 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
20459 continue;
20460 };
20461 let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
20462 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
20463 let ur = ur0 + i;
20464 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
20465 for r in y0..y1 {
20466 let off = (r - ur0 * unit) * w;
20467 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
20468 }
20469 }
20470 };
20471 let urows = wrote.len() / unit_cols;
20472 let threads = crate::par::filter_threads().min(urows.max(1));
20473 if threads <= 1 {
20474 band(d, wrote, 0);
20475 return;
20476 }
20477 let per = urows.div_ceil(threads);
20478 let batch = crate::par::Batch::new("ec-av1-filter");
20479 for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
20480 {
20481 let band = &band;
20482 batch.submit(move || band(dc, wr, i * per));
20483 }
20484}
20485
20486/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
20487/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
20488/// allocator and the page fault handler out of the filter search.
20489fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
20490 let mut buf = scratch.pop().unwrap_or_default();
20491 let src: &[u16] = &p.data;
20492 let threads = crate::par::filter_threads();
20493 if buf.len() != src.len() || threads <= 1 {
20494 buf.clear();
20495 buf.extend_from_slice(src);
20496 } else {
20497 // A recycled buffer is already the right length, so the copy is a
20498 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
20499 // candidate is memory bandwidth, not arithmetic, and the halves are
20500 // disjoint `&mut` slices (no `par::Shared` needed).
20501 let per = src.len().div_ceil(threads);
20502 let batch = crate::par::Batch::new("ec-av1-filter");
20503 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
20504 batch.submit(move || dst.copy_from_slice(src));
20505 }
20506 }
20507 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
20508}
20509
20510/// The filter half of a captured decode, under new parameters: exactly the
20511/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
20512/// copy of the captured planes. `None` when nothing is captured (the caller
20513/// then decodes for real).
20514pub(crate) fn replay_filters(
20515 loop_filter: &LoopFilterParams,
20516 cdef: &CdefParams,
20517 fctx: &FrameCtx,
20518) -> Option<Picture> {
20519 #[cfg(test)]
20520 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20521 return None;
20522 }
20523 replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture)
20524}
20525
20526/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters,
20527/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage
20528/// used to reach this picture by decoding that re-coded tile a second time
20529/// (10% of a 4K frame's encode), only because the loop-restoration search
20530/// needs the decoder's own post-CDEF plane
20531/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls
20532/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter
20533/// planes in the same order, so it is the same bytes -- pinned by
20534/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which
20535/// runs the decode as well and holds picture and stages against it.
20536///
20537/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that
20538/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF
20539/// snapshot and handed the post-CDEF plane over for both stages.
20540pub(crate) fn replay_final(
20541 loop_filter: &LoopFilterParams,
20542 cdef: &CdefParams,
20543 idx_grid: &[u8],
20544 want_stages: bool,
20545 fctx: &FrameCtx,
20546) -> Option<(Picture, Option<FilterStages>)> {
20547 #[cfg(test)]
20548 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20549 return None;
20550 }
20551 replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx)
20552}
20553
20554fn replay_inner(
20555 loop_filter: &LoopFilterParams,
20556 cdef: &CdefParams,
20557 // `Some((cdef_idx grid, capture the filter stages))` for the final
20558 // replay; `None` for a scoring candidate, which always codes `bits == 0`.
20559 final_pass: Option<(&[u8], bool)>,
20560 fctx: &FrameCtx,
20561) -> Option<(Picture, Option<FilterStages>)> {
20562 REPLAY.with_borrow_mut(|slot| {
20563 let r = slot.as_mut()?;
20564 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
20565 // Set when the working planes ARE the deblocked planes (see below):
20566 // they go into the cache at the end, and the picture is cropped out
20567 // of them rather than taking their buffers.
20568 let mut share = false;
20569 let cpt = crate::par::timer(crate::par::S_COPY);
20570 let unit_cols = r.neighbours.mi_cols.div_ceil(2);
20571 let unit_rows = r.neighbours.mi_rows.div_ceil(2);
20572 let (mut y, mut u, mut v) = if hit {
20573 let work = r.work.take();
20574 let wrote = std::mem::take(&mut r.wrote);
20575 // `cdef_adjust_strength` is monotone in the strength it is given,
20576 // so a candidate whose primary strength is no lower and whose
20577 // secondary is zero only if the last one's was writes every unit
20578 // the last one wrote -- and writes it from the same post-deblock
20579 // source, so the samples under it need not be put back first.
20580 // Only while both candidates carry ONE strength pair (`bits ==
20581 // 0`, every scoring candidate) and read the same `cdef_idx` grid.
20582 let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
20583 let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
20584 (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
20585 superset(
20586 (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
20587 (old.y_pri_strength[0], old.y_sec_strength[0]),
20588 ),
20589 superset(
20590 (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
20591 (old.uv_pri_strength[0], old.uv_sec_strength[0]),
20592 ),
20593 ),
20594 _ => (false, false),
20595 };
20596 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
20597 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
20598 match work {
20599 Some((mut wy, mut wu, mut wv)) => {
20600 if !skip_y {
20601 restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
20602 }
20603 if !skip_uv {
20604 restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
20605 restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
20606 }
20607 (wy, wu, wv)
20608 }
20609 None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
20610 }
20611 } else {
20612 // The levels moved, so the cached deblocked planes are dead:
20613 // their buffers are this candidate's working copies.
20614 for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
20615 r.scratch.push(plane.data.into_owned());
20616 }
20617 r.work_cdef = None;
20618 if let Some((_, dy, du, dv)) = r.deblocked.take() {
20619 r.scratch.push(dy.data.into_owned());
20620 r.scratch.push(du.data.into_owned());
20621 r.scratch.push(dv.data.into_owned());
20622 }
20623 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
20624 let (mut y, mut u, mut v) =
20625 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
20626 let _t = crate::par::timer(crate::par::S_DEBLOCK);
20627 apply_deblock(
20628 &mut y,
20629 &mut u,
20630 &mut v,
20631 loop_filter,
20632 &r.neighbours,
20633 r.frame_width,
20634 r.frame_height,
20635 fctx,
20636 );
20637 // lane-av1cap2: an all-zero-strength CDEF writes no sample at
20638 // all ([`cdef_all_zero`]'s own early return), so THESE planes
20639 // are already this candidate's output -- they become the
20640 // deblock cache at the end instead of being copied into it
20641 // here, which is three ~6 MB copies less per candidate that
20642 // moves the levels (the whole deblocking half of the search:
20643 // its CDEF strengths are still (0,0)).
20644 share = cdef_all_zero(cdef);
20645 if !share {
20646 let scratch = &mut r.scratch;
20647 r.deblocked = Some((
20648 *loop_filter,
20649 pooled(&y, scratch),
20650 pooled(&u, scratch),
20651 pooled(&v, scratch),
20652 ));
20653 }
20654 (y, u, v)
20655 };
20656 drop(cpt);
20657 // The winner's `cdef_idx` literals live in the re-coded tile, which
20658 // nothing parses on this path -- hand the grid the encoder already
20659 // chose straight to the filter (`bits == 0` leaves the grid the last
20660 // parse sized, which is what every scoring candidate reads).
20661 if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) {
20662 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
20663 }
20664 let ct = crate::par::timer(crate::par::S_CDEF);
20665 let mut wrote = std::mem::take(&mut r.wrote);
20666 wrote.clear();
20667 wrote.resize(unit_cols * unit_rows, 0);
20668 r.work_cdef = Some(*cdef);
20669 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
20670 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
20671 });
20672 apply_cdef(
20673 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
20674 pre,
20675 Some(&mut wrote),
20676 );
20677 drop(ct);
20678 if final_pass.is_some_and(|(_, want)| want) {
20679 // The loop-restoration search runs on the stages above (where
20680 // post-CDEF stands in for post-deblock, as the capture decode
20681 // had it); the FILTER this frame ends up applying reads the
20682 // real post-deblock rows, which is what the decoder does.
20683 let snapshot = if share {
20684 // Nothing filtered these planes after the deblock, so they
20685 // are the post-deblock picture themselves.
20686 Some(plane_snapshot(&y, 0))
20687 } else {
20688 r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0))
20689 };
20690 let scratch = &mut r.scratch;
20691 r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d));
20692 }
20693 let stages = final_pass.and_then(|(_, want)| {
20694 want.then(|| FilterStages {
20695 deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20696 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20697 stride: [y.width, u.width, v.width],
20698 })
20699 });
20700 // The capture only happens on the shape whose tail is the two
20701 // filter calls and the crop (no superres, no loop restoration), so
20702 // what is left is that crop -- byte for byte the cropped return path
20703 // of the decode this replaces, wide-margin stash included.
20704 //
20705 // lane-av1fpar: the crop is why this arm exists at all. The capture
20706 // used to demand `frame == plane` dimensions, which no editor size
20707 // meets (1080 and 1608 both pad to a superblock row), so every
20708 // candidate of every frame at those sizes fell through to a full
20709 // re-decode -- 57% of a 1080p frame's wall.
20710 let (fw, fh) = (r.frame_width, r.frame_height);
20711 if fw == r.width && fh == r.height {
20712 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20713 r.wrote = Vec::new();
20714 r.work_cdef = None;
20715 if share {
20716 let picture = Picture {
20717 width: r.width,
20718 height: r.height,
20719 y: y.data.to_vec(),
20720 u: u.data.to_vec(),
20721 v: v.data.to_vec(),
20722 };
20723 r.deblocked = Some((*loop_filter, y, u, v));
20724 return Some((picture, stages));
20725 }
20726 return Some((
20727 Picture {
20728 width: r.width,
20729 height: r.height,
20730 y: y.data.into_owned(),
20731 u: u.data.into_owned(),
20732 v: v.data.into_owned(),
20733 },
20734 stages,
20735 ));
20736 }
20737 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
20738 let mut out = Vec::with_capacity(w * h);
20739 for row in 0..h {
20740 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20741 }
20742 out
20743 };
20744 let (tw, th) = (r.true_width, r.true_height);
20745 fctx.last_frame_wide_margin.with(|m| {
20746 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
20747 width: tw,
20748 height: th,
20749 y: crop(&y, tw, th),
20750 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
20751 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
20752 });
20753 });
20754 let out = Picture {
20755 width: fw,
20756 height: fh,
20757 y: crop(&y, fw, fh),
20758 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20759 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20760 };
20761 // The working planes outlive the crop: either they ARE the
20762 // deblocked planes this candidate's successors reuse, or they go
20763 // back to the pool.
20764 if share {
20765 r.wrote = Vec::new();
20766 r.work_cdef = None;
20767 r.deblocked = Some((*loop_filter, y, u, v));
20768 } else {
20769 // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20770 // next candidate, together with the map of what CDEF wrote.
20771 r.wrote = wrote;
20772 r.work = Some((y, u, v));
20773 }
20774 Some((out, stages))
20775 })
20776}
20777
20778/// lane-av1cap2: the loop-restoration half of the final replay. Once the
20779/// units are chosen the tile is coded a second time to carry them, and that
20780/// re-coded tile used to be DECODED to reach the restored reference frame
20781/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that
20782/// tile but the per-unit filters the encoder just picked: it is the
20783/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on
20784/// the post-CDEF plane the final replay produced, with the TRUE
20785/// post-deblock stripe-border rows -- the same call the decoder's
20786/// `apply_loop_restoration` makes, on the same input. Only luma moves: the
20787/// encoder never writes a chroma restoration type other than
20788/// `RESTORE_NONE`, whose kernel hands its input straight back.
20789///
20790/// Returns the cropped luma plane and refreshes the wide-margin stash's own
20791/// luma (restoration writes strictly inside `frame_width x frame_height`,
20792/// so the margin columns past it stand). `None` when nothing was captured
20793/// -- the caller then decodes for real.
20794pub(crate) fn replay_restoration(
20795 lr: &LoopRestorationParams,
20796 units: &[Option<crate::restoration::WienerInfo>],
20797 fctx: &FrameCtx,
20798) -> Option<Vec<u16>> {
20799 #[cfg(test)]
20800 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20801 return None;
20802 }
20803 REPLAY.with_borrow_mut(|slot| {
20804 let r = slot.as_mut()?;
20805 let (cdefed, deblocked) = r.final_luma.as_ref()?;
20806 let (fw, fh) = (r.frame_width, r.frame_height);
20807 let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
20808 let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]);
20809 if horz == 0 || units.len() != horz * vert {
20810 return None;
20811 }
20812 for (i, filter) in units.iter().enumerate() {
20813 if let Some(info) = filter {
20814 grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info));
20815 }
20816 }
20817 let stride = cdefed.width;
20818 let mut out = scratch_empty();
20819 crate::restoration::apply_loop_restoration_plane(
20820 &cdefed.data,
20821 &deblocked.data,
20822 stride,
20823 fw,
20824 fh,
20825 0,
20826 lr.frame_restoration_type[0],
20827 lr.loop_restoration_size[0],
20828 &grid,
20829 0,
20830 &mut out,
20831 None,
20832 fctx,
20833 );
20834 fctx.last_frame_wide_margin.with(|m| {
20835 if let Some(p) = m.borrow_mut().as_mut() {
20836 let tw = p.width;
20837 for row in 0..p.height.min(fh) {
20838 let n = tw.min(fw);
20839 p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]);
20840 }
20841 }
20842 });
20843 let mut y = Vec::with_capacity(fw * fh);
20844 for row in 0..fh {
20845 y.extend(out[row * stride..][..fw].iter().copied());
20846 }
20847 scratch_return(out);
20848 Some(y)
20849 })
20850}
20851
20852/// The output crop, taking the plane by value: a frame whose width is
20853/// already superblock-aligned (only its height is padded) has a padded
20854/// buffer whose stride equals the visible width, so the crop is a pure
20855/// truncation of the buffer we already own -- no full-plane copy at all
20856/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
20857/// serial tail). Any other shape falls back to the row-by-row copy.
20858fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
20859 let stride = plane.width;
20860 let mut data = plane.data.into_owned();
20861 if stride == w {
20862 data.truncate(w * h);
20863 return data;
20864 }
20865 let mut out = Vec::with_capacity(w * h);
20866 for row in 0..h {
20867 out.extend(data[row * stride..][..w].iter().copied());
20868 }
20869 out
20870}
20871
20872/// Hands a buffer back to the pool; the capacity is what is worth keeping.
20873/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
20874/// what keeps a pool shared by every thread from being an unbounded stash.
20875fn scratch_return(v: Vec<u16>) {
20876 let mut p = PLANE_SCRATCH.lock().unwrap();
20877 if p.len() < SCRATCH_CAP {
20878 p.push(v);
20879 }
20880}
20881
20882/// One CDEF mi-row band, as a real function rather than the body of the
20883/// `run_bands` closure: inside the closure the destination planes are
20884/// `&mut` references derived from a `par::Shared` raw pointer in the same
20885/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
20886/// re-loads through them on every tap. Reference parameters restore `noalias`
20887/// (lane-perf11 (a): -x% instructions at one filter thread).
20888#[allow(clippy::too_many_arguments)]
20889fn cdef_band(
20890 r_lo: usize,
20891 r_hi: usize,
20892 y: &mut PlaneBuf<'static>,
20893 u: &mut PlaneBuf<'static>,
20894 v: &mut PlaneBuf<'static>,
20895 src_y: &[u16],
20896 src_u: &[u16],
20897 src_v: &[u16],
20898 cdef: &CdefParams,
20899 skip_grid: &Neighbours,
20900 idx_grid: &[u8],
20901 sb_cols: usize,
20902 coeff_shift: i32,
20903 damping: i32,
20904 damping_uv: i32,
20905 (frame_w, frame_h): (usize, usize),
20906 fctx: &crate::decode::FrameCtx,
20907 // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
20908 // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
20909 // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
20910 // `cdef_adjust_strength` zeroes a unit's primary strength off its own
20911 // variance, so which units a candidate writes is not a function of its
20912 // strengths alone -- the encoder's filter replay reuses one destination
20913 // plane across candidates and needs the map to restore it.
20914 mut wrote: Option<&mut [u8]>,
20915) {
20916 let unit_cols = skip_grid.mi_cols.div_ceil(2);
20917 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
20918 if sb_cols == 0 {
20919 return 0;
20920 }
20921 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
20922 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
20923 };
20924 // One scratch window per plane kind, reused by every unit (8x8 luma and
20925 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
20926 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
20927 // AVX2 kernel taps the window in place with two-row loads that reach
20928 // past the last sample, and the tail stays zero for every unit.
20929 let mut win_y = [0i16; 256];
20930 let mut win_uv = [0i16; 256];
20931 let mut mi_r = r_lo;
20932 while mi_r < r_hi {
20933 let mut mi_c = 0usize;
20934 while mi_c < skip_grid.mi_cols {
20935 if skip_grid.is_skip_txfm(mi_r, mi_c) {
20936 hit!(CDEF_SKIPPED_UNITS);
20937 }
20938 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
20939 let sidx = strength_idx(mi_r, mi_c);
20940 let (ox, oy) = (mi_c * 4, mi_r * 4);
20941 // Nothing to do for this unit at all: the direction search is
20942 // only ever consumed through a strength, so a unit whose four
20943 // strengths are zero never needs its 8x8 window gathered.
20944 if cdef.y_pri_strength[sidx] == 0
20945 && cdef.y_sec_strength[sidx] == 0
20946 && cdef.uv_pri_strength[sidx] == 0
20947 && cdef.uv_sec_strength[sidx] == 0
20948 {
20949 mi_c += 2;
20950 continue;
20951 }
20952 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
20953 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
20954 // lane-cdef r1: the direction search reads the SAME padded
20955 // block the taps do -- libaom runs `cdef_find_dir` on the
20956 // prepared filter block (`cdef_block.c:296-320` over
20957 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
20958 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
20959 // Clamping to the last real sample instead made every straddling
20960 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
20961 // a different `adjust_strength`, hence a +-1 band at the crop edge.
20962 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
20963
20964 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
20965 // -- each plane zeroes the shared direction when *its own*
20966 // frame-level primary strength is 0, independent of the
20967 // per-block adjusted `t` and of the other plane's strength.
20968 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
20969 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
20970 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
20971 let t = cdef_adjust_strength(y_pri_strength, var);
20972 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
20973 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
20974 eprintln!(
20975 "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}"
20976 );
20977 }
20978 let enable_primary = t != 0;
20979 let enable_secondary = y_sec_strength != 0;
20980 if (ox + 8 > frame_w || oy + 8 > frame_h)
20981 && (enable_primary
20982 || enable_secondary
20983 || cdef.uv_pri_strength[sidx] != 0
20984 || cdef.uv_sec_strength[sidx] != 0)
20985 {
20986 hit!(CDEF_STRADDLE_UNITS);
20987 }
20988 if enable_primary || enable_secondary {
20989 cdef_filter_block(
20990 &win_y,
20991 y,
20992 ox,
20993 oy,
20994 8,
20995 8,
20996 t,
20997 y_sec_strength,
20998 y_dir,
20999 damping,
21000 damping,
21001 enable_primary,
21002 enable_secondary,
21003 coeff_shift, fctx,
21004 );
21005 }
21006
21007 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
21008 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
21009 let uv_dir = if t_uv != 0 { dir } else { 0 };
21010 let enable_primary_uv = t_uv != 0;
21011 let enable_secondary_uv = uv_sec_strength != 0;
21012 if let Some(w) = wrote.as_deref_mut() {
21013 let mark = u8::from(enable_primary || enable_secondary)
21014 | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
21015 w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
21016 }
21017 if enable_primary_uv || enable_secondary_uv {
21018 let (cox, coy) = (ox / 2, oy / 2);
21019 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
21020 let (tw, th) = (plane.true_width, plane.true_height);
21021 let stride = plane.width;
21022 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
21023 cdef_filter_block(
21024 &win_uv,
21025 plane,
21026 cox,
21027 coy,
21028 4,
21029 4,
21030 t_uv,
21031 uv_sec_strength,
21032 uv_dir,
21033 damping_uv,
21034 damping_uv,
21035 enable_primary_uv,
21036 enable_secondary_uv,
21037 coeff_shift, fctx,
21038 );
21039 }
21040 }
21041 }
21042 mi_c += 2;
21043 }
21044 mi_r += 2;
21045 }
21046}
21047
21048
21049// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
21050//
21051// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
21052// every plane's vertical deblock edges, then every plane's horizontal ones,
21053// then CDEF, then -- unpipelined -- superres and loop restoration).
21054// A band is 64 luma rows, one superblock row (a 128 superblock is two).
21055//
21056// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
21057// band r, so no filter may touch band r before band r+1 is reconstructed.
21058// Hence V(r) waits for `ready >= r + 2`.
21059// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
21060// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
21061// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
21062// side of the band boundary, so H(r-1)'s last edge reaches into band r,
21063// which the whole-frame order has already vertical-filtered -- V(r)
21064// before H(r-1) reproduces exactly that.
21065// * post-deblock finality: band j's own bottom rows are still rewritten by
21066// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
21067// only be taken after H(j+1).
21068// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
21069// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
21070//
21071// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
21072// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
21073// superres upscale, which is a whole-frame refusal for this path) stay in the
21074// frame thread's tail; the snapshot the pipeline built is what LR reads.
21075struct PipeQ {
21076 /// Bands whose reconstruction the frame thread has released.
21077 ready: usize,
21078 abort: bool,
21079}
21080
21081pub(crate) struct PipeSync {
21082 m: std::sync::Mutex<PipeQ>,
21083 cv: std::sync::Condvar,
21084}
21085
21086impl PipeSync {
21087 fn new() -> Self {
21088 Self {
21089 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
21090 cv: std::sync::Condvar::new(),
21091 }
21092 }
21093 fn note(&self, ready: usize) {
21094 let mut q = self.m.lock().unwrap();
21095 if ready > q.ready {
21096 q.ready = ready;
21097 self.cv.notify_all();
21098 }
21099 }
21100 /// Releases every remaining band (`abort` = the tile decoder is bailing
21101 /// out, so the worker returns instead of finishing the frame).
21102 fn close(&self, all: usize, abort: bool) {
21103 let mut q = self.m.lock().unwrap();
21104 q.ready = q.ready.max(all);
21105 q.abort |= abort;
21106 self.cv.notify_all();
21107 }
21108 /// `false` when the frame was aborted.
21109 fn wait_for(&self, want: usize) -> bool {
21110 let mut q = self.m.lock().unwrap();
21111 while q.ready < want && !q.abort {
21112 q = self.cv.wait(q).unwrap();
21113 }
21114 !q.abort
21115 }
21116}
21117
21118/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
21119/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
21120/// otherwise only the four rows around each stripe boundary that loop
21121/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
21122fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
21123 let w = src.width;
21124 if w == 0 {
21125 return;
21126 }
21127 let rows = src.data.len() / w;
21128 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
21129 if lo >= hi {
21130 return;
21131 }
21132 if full {
21133 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
21134 return;
21135 }
21136 let stripe_h = 64usize >> ss_y;
21137 let offset = 8usize >> ss_y;
21138 let mut b = stripe_h - offset;
21139 while b < rows {
21140 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
21141 if a < e {
21142 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
21143 }
21144 b += stripe_h;
21145 }
21146}
21147
21148/// Everything the pipeline worker needs that is not a plane or a grid.
21149struct PipeCfg<'a> {
21150 lf: &'a LoopFilterParams,
21151 cdef: &'a CdefParams,
21152 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
21153 /// entries of the superblock rows the pipeline has not reached; the Vec
21154 /// itself is sized once per frame, so the pointer stays valid.
21155 idx_grid: (*const u8, usize),
21156 sb_cols: usize,
21157 frame_w: usize,
21158 frame_h: usize,
21159 nbands: usize,
21160 cdef_on: bool,
21161 snap_on: bool,
21162}
21163
21164// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
21165// per frame and only ever written at indices the pipeline is three bands
21166// behind (see this module's dependency note).
21167#[allow(unsafe_code)]
21168unsafe impl Send for PipeCfg<'_> {}
21169
21170#[allow(unsafe_code)]
21171#[allow(clippy::too_many_arguments)]
21172fn pipe_run(
21173 sync: &PipeSync,
21174 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
21175 su: crate::par::Shared<'_, PlaneBuf<'static>>,
21176 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
21177 sn: crate::par::Shared<'_, Neighbours>,
21178 cfg: PipeCfg<'_>,
21179 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21180 lr_sync: Option<&PipeSync>,
21181 fctx: &crate::decode::FrameCtx,
21182) {
21183 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
21184 // is at least two behind, and the two ranges never meet -- see the
21185 // dependency note above and `Shared`'s own corner-cut.
21186 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21187 let n: &Neighbours = unsafe { sn.get() };
21188 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
21189 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21190 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
21191 let damping_uv = (damping - 1).max(0);
21192 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
21193 let nb = cfg.nbands;
21194 for k in 0..nb + 3 {
21195 if !sync.wait_for((k + 2).min(nb)) {
21196 if let Some(ls) = lr_sync {
21197 ls.close(nb, true);
21198 }
21199 return;
21200 }
21201 if k < nb {
21202 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
21203 }
21204 if k >= 1 && k - 1 < nb {
21205 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
21206 }
21207 if cfg.snap_on && k >= 2 && k - 2 < nb {
21208 let j = k - 2;
21209 if let Some((sy2, su2, sv2)) = snap.as_mut() {
21210 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
21211 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
21212 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
21213 }
21214 }
21215 if cfg.cdef_on && k >= 3 && k - 3 < nb {
21216 let j = k - 3;
21217 if let Some((sy2, su2, sv2)) = snap.as_ref() {
21218 cdef_rows(
21219 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
21220 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
21221 None,
21222 );
21223 }
21224 }
21225 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
21226 // them to the loop restoration worker.
21227 if let Some(ls) = lr_sync {
21228 ls.note(k.saturating_sub(2));
21229 }
21230 }
21231 if let Some(ls) = lr_sync {
21232 ls.close(nb, false);
21233 }
21234}
21235
21236/// The pipeline's loop restoration worker, a second task alongside
21237/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
21238/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
21239/// post-deblock snapshot at most two rows past `v_end` (see
21240/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
21241/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
21242/// iteration `band + 3` and the snapshot band one iteration earlier, so the
21243/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
21244/// indices being at most one band apart. Running it as its own worker (not
21245/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
21246/// critical path: serialised into that loop it measured ~1% slower than the
21247/// whole-frame form, which at least ran its RU rows across the filter pool.
21248#[allow(unsafe_code)]
21249fn pipe_run_lr(
21250 sync: &PipeSync,
21251 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
21252 su: crate::par::Shared<'_, PlaneBuf<'static>>,
21253 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
21254 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
21255 cfg: LrCfg<'_>,
21256 fctx: &crate::decode::FrameCtx,
21257) {
21258 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
21259 // and writes its own `out` buffers; the final swap happens after the
21260 // last CDEF band, which is `pipe_run`'s last plane write.
21261 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21262 let snap = unsafe { snap.get() };
21263 let grid = unsafe { &*cfg.lr_grid };
21264 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
21265 let dims = [
21266 (fw, fh, 0u32, y.width, y.data.len()),
21267 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
21268 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
21269 ];
21270 let mut planes: Vec<LrPlane> = Vec::new();
21271 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
21272 let rows = crate::restoration::lr_unit_rows(
21273 ph,
21274 cfg.lr.loop_restoration_size[p],
21275 ss,
21276 cfg.lr.frame_restoration_type[p],
21277 );
21278 if rows.is_empty() {
21279 continue;
21280 }
21281 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
21282 }
21283 for band in 0..cfg.nbands {
21284 if !sync.wait_for(band + 1) {
21285 return;
21286 }
21287 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
21288 for lp in &mut planes {
21289 let stripe = 64usize >> lp.ss;
21290 let r_lo = lp.next;
21291 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
21292 lp.next += 1;
21293 }
21294 if lp.next == r_lo {
21295 continue;
21296 }
21297 let (src, deb) = match lp.p {
21298 0 => (&y.data, &sy2.data),
21299 1 => (&u.data, &su2.data),
21300 _ => (&v.data, &sv2.data),
21301 };
21302 crate::restoration::apply_loop_restoration_plane(
21303 src,
21304 deb,
21305 lp.stride,
21306 lp.pw,
21307 lp.ph,
21308 lp.ss,
21309 cfg.lr.frame_restoration_type[lp.p],
21310 cfg.lr.loop_restoration_size[lp.p],
21311 grid,
21312 lp.p,
21313 &mut lp.out,
21314 Some((r_lo, lp.next)),
21315 fctx,
21316 );
21317 }
21318 }
21319 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
21320 // untouched by restoration and copied here, then the restored plane
21321 // takes the picture's place (the whole-frame path's own final swap).
21322 for mut lp in planes {
21323 let buf: &mut PlaneBuf<'static> = match lp.p {
21324 0 => &mut *y,
21325 1 => &mut *u,
21326 _ => &mut *v,
21327 };
21328 let tail = lp.ph * lp.stride;
21329 if tail < buf.data.len() {
21330 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
21331 }
21332 scratch_return(
21333 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
21334 );
21335 }
21336}
21337
21338/// Everything [`pipe_run_lr`] needs beyond the planes.
21339struct LrCfg<'a> {
21340 lr: &'a LoopRestorationParams,
21341 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
21342 /// many bands ahead of every unit this worker reads.
21343 lr_grid: *const crate::restoration::RestorationGrid,
21344 frame_w: usize,
21345 frame_h: usize,
21346 nbands: usize,
21347}
21348
21349// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
21350#[allow(unsafe_code)]
21351unsafe impl Send for LrCfg<'_> {}
21352
21353/// One plane's pipelined loop restoration state (see [`pipe_run`]).
21354struct LrPlane {
21355 p: usize,
21356 /// The restored plane, built band by band and swapped in at the end.
21357 out: Vec<u16>,
21358 rows: Vec<(u32, u32)>,
21359 /// The first RU row not yet restored.
21360 next: usize,
21361 pw: usize,
21362 ph: usize,
21363 ss: u32,
21364 stride: usize,
21365}
21366
21367/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
21368/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
21369/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
21370/// pointers into the frame's planes, so it may not outlive them).
21371struct PipeGuard<'a> {
21372 sync: std::sync::Arc<PipeSync>,
21373 batch: Option<crate::par::Batch<'a>>,
21374 nbands: usize,
21375 /// The loop restoration worker's own gate, aborted with the first one.
21376 lr_sync: Option<std::sync::Arc<PipeSync>>,
21377}
21378
21379impl PipeGuard<'_> {
21380 fn note(&self, bands: usize) {
21381 self.sync.note(bands);
21382 }
21383 fn finish(&mut self) {
21384 self.sync.close(self.nbands, false);
21385 // Dropping the batch waits the worker out.
21386 self.batch.take();
21387 }
21388}
21389
21390impl Drop for PipeGuard<'_> {
21391 fn drop(&mut self) {
21392 self.sync.close(self.nbands, true);
21393 if let Some(ls) = &self.lr_sync {
21394 ls.close(self.nbands, true);
21395 }
21396 }
21397}
21398
21399/// Leading superblock rows of the live tile's wavefront that are fully
21400/// reconstructed: parsed out to the last column and with every job that
21401/// carried a write finished. 0 when reconstruction is inline (no wavefront),
21402/// where the caller uses the parse position instead.
21403fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
21404 let st = fctx.wave.with(|w| w.borrow().clone());
21405 let Some(st) = st else { return 0 };
21406 let q = st.q.lock().unwrap();
21407 let mut n = 0;
21408 while n < q.rows.len() {
21409 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
21410 break;
21411 }
21412 n += 1;
21413 }
21414 n
21415}
21416
21417/// Frames whose loop filters ran pipelined, and frames that took the
21418/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
21419static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
21420static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
21421
21422/// Whether this frame's filters may run per superblock row. Everything that
21423/// reads the picture out of band order, or the pipeline's own inputs out of
21424/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
21425/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
21426/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
21427/// frame row is only complete after the last tile column's own parse), and
21428/// every pixel-dump / stage-skip debug flag, whose whole point is the
21429/// unpipelined stage boundary. The pipeline also stays off unless some
21430/// threading is on -- at (1, 1) the filters would run on a worker thread for
21431/// nothing and the crate's `thread_local!` gate counters would miss them.
21432fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
21433 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
21434 return false;
21435 }
21436 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
21437 return false;
21438 }
21439 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
21440 return false;
21441 }
21442 if fctx.seg.with(|s| s.borrow().enabled) {
21443 return false;
21444 }
21445 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
21446 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
21447 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
21448 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
21449 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
21450 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
21451 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
21452 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
21453 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
21454 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_LR")
21455 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
21456 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
21457 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
21458}
21459
21460/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
21461/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
21462/// never enters `apply_cdef`, so it calls this itself).
21463fn cdef_scan_counters(skip_grid: &Neighbours) {
21464 let _ = skip_grid;
21465 hit_do! {
21466 let mut r = 0usize;
21467 while r < skip_grid.mi_rows {
21468 let mut c = 0usize;
21469 while c < skip_grid.mi_cols {
21470 if (0..2).any(|rr| {
21471 (0..2).any(|cc| {
21472 !skip_grid
21473 .blk_grid
21474 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21475 .map_or(true, |x| x.written)
21476 })
21477 }) {
21478 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
21479 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
21480 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
21481 }
21482 }
21483 let cell = |rr: usize, cc: usize| {
21484 skip_grid
21485 .blk_grid
21486 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21487 .is_some_and(|x| x.skip)
21488 };
21489 let first = cell(0, 0);
21490 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
21491 hit!(CDEF_MIXED_SKIP_UNITS);
21492 }
21493 c += 2;
21494 }
21495 r += 2;
21496 }
21497 }
21498}
21499
21500/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
21501/// means "no filtering at all" whenever the single (index 0) strength pair
21502/// is all-zero, the fast path every existing gate stream takes.
21503fn cdef_all_zero(cdef: &CdefParams) -> bool {
21504 cdef.bits == 0
21505 && cdef.y_pri_strength[0] == 0
21506 && cdef.y_sec_strength[0] == 0
21507 && cdef.uv_pri_strength[0] == 0
21508 && cdef.uv_sec_strength[0] == 0
21509}
21510
21511/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
21512/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
21513/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
21514/// row range's own pixels.
21515#[allow(clippy::too_many_arguments)]
21516fn cdef_rows(
21517 y: &mut PlaneBuf<'static>,
21518 u: &mut PlaneBuf<'static>,
21519 v: &mut PlaneBuf<'static>,
21520 src_y: &[u16],
21521 src_u: &[u16],
21522 src_v: &[u16],
21523 cdef: &CdefParams,
21524 skip_grid: &Neighbours,
21525 idx_grid: &[u8],
21526 sb_cols: usize,
21527 coeff_shift: i32,
21528 damping: i32,
21529 damping_uv: i32,
21530 (frame_w, frame_h): (usize, usize),
21531 r_lo0: usize,
21532 r_hi0: usize, fctx: &crate::decode::FrameCtx,
21533 // See [`cdef_band`]. Shared because the bands below write disjoint unit
21534 // ROWS of it, exactly as they write disjoint plane rows.
21535 wrote: Option<crate::par::Shared<'_, [u8]>>,
21536) {
21537 let mi_rows = skip_grid.mi_rows;
21538 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
21539 if lo >= hi {
21540 return;
21541 }
21542 let (sy, su, sv) = (
21543 crate::par::Shared::new(y),
21544 crate::par::Shared::new(u),
21545 crate::par::Shared::new(v),
21546 );
21547 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
21548 .into_iter()
21549 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
21550 .collect();
21551 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
21552 // SAFETY: this band writes only the plane rows its own mi rows cover,
21553 // disjoint from every other band's (see `Shared`).
21554 #[allow(unsafe_code)]
21555 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21556 // SAFETY: this band marks only the unit rows its own mi rows cover,
21557 // disjoint from every other band's (see `Shared`).
21558 #[allow(unsafe_code)]
21559 let wr = wrote.as_ref().map(|w| unsafe { w.get() });
21560 cdef_band(
21561 r_lo,
21562 r_hi,
21563 y,
21564 u,
21565 v,
21566 src_y,
21567 src_u,
21568 src_v,
21569 cdef,
21570 skip_grid,
21571 idx_grid,
21572 sb_cols,
21573 coeff_shift,
21574 damping,
21575 damping_uv,
21576 (frame_w, frame_h),
21577 fctx,
21578 wr,
21579 );
21580 });
21581}
21582
21583fn apply_cdef(
21584 y: &mut PlaneBuf<'static>,
21585 u: &mut PlaneBuf<'static>,
21586 v: &mut PlaneBuf<'static>,
21587 cdef: &CdefParams,
21588 skip_grid: &Neighbours,
21589 // This frame header's own CROPPED luma size, for the straddling-unit
21590 // counter only -- CDEF itself walks the mi-rounded plane.
21591 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21592 // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter
21593 // starts by copying all three (~19 MB at 4K). The encoder's filter
21594 // replay already holds an untouched copy of exactly those planes -- its
21595 // post-deblock cache, which is where the working planes were copied FROM
21596 // -- so it hands them straight in and the copy does not happen. `None`
21597 // (every decode) copies as before.
21598 src: Option<(&[u16], &[u16], &[u16])>,
21599 // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
21600 // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
21601 // before the call.
21602 mut wrote: Option<&mut [u8]>,
21603) {
21604 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
21605 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
21606 return;
21607 }
21608 cdef_scan_counters(skip_grid);
21609 // `cdef.bits == 0` still means "no filtering at all" whenever the single
21610 // (index 0) strength pair is all-zero -- the fast path every existing
21611 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
21612 // at every index, but that is rare enough not to special-case; the
21613 // per-superblock lookup below degrades to the same index-0 read anyway
21614 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
21615 if cdef_all_zero(cdef) {
21616 return;
21617 }
21618 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
21619 // One entry per superblock (a few hundred at 4K), so this clone is not
21620 // one of the per-frame copies lane-perf6 pooled below.
21621 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
21622 let owned = src.is_none();
21623 let (src_y, src_u, src_v) = match src {
21624 Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)),
21625 None => (
21626 std::borrow::Cow::Owned(scratch_from(&y.data)),
21627 std::borrow::Cow::Owned(scratch_from(&u.data)),
21628 std::borrow::Cow::Owned(scratch_from(&v.data)),
21629 ),
21630 };
21631 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
21632 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
21633 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21634 let damping = i32::from(cdef.damping) + coeff_shift;
21635 let damping_uv = (damping - 1).max(0);
21636 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
21637 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
21638 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
21639 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
21640 // disjoint row range of all three planes.
21641 cdef_rows(
21642 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
21643 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21644 wrote.as_deref_mut().map(crate::par::Shared::new),
21645 );
21646 if owned {
21647 scratch_return(src_y.into_owned());
21648 scratch_return(src_u.into_owned());
21649 scratch_return(src_v.into_owned());
21650 }
21651}
21652
21653/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
21654/// restoration on both tile paths: hands the encoder's restoration search the
21655/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
21656/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
21657/// a capture is worth three plane copies and nothing else -- and when the
21658/// capture flag is off (every decode but that search) it is worth a bool.
21659fn capture_stages(
21660 y: &PlaneBuf<'_>,
21661 u: &PlaneBuf<'_>,
21662 v: &PlaneBuf<'_>,
21663 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21664 fctx: &FrameCtx,
21665) {
21666 if !fctx.capture_stages.get() {
21667 return;
21668 }
21669 // Without an active restoration type the decoder took no pre-CDEF
21670 // snapshot; the post-CDEF plane then stands in for it, which is exact
21671 // everywhere but LR's own 3-row stripe borders (the encoder's search
21672 // always asks with a type set, so this is the defensive arm).
21673 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
21674 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
21675 None => p.data.to_vec(),
21676 };
21677 *fctx.stages.borrow_mut() = Some(FilterStages {
21678 deblocked: [db(0, y), db(1, u), db(2, v)],
21679 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
21680 stride: [y.width, u.width, v.width],
21681 });
21682}
21683
21684/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
21685/// ordering note: libaom also runs `superres_post_decode` between the two,
21686/// but this decoder never implements super-resolution, so there is nothing
21687/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
21688/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
21689/// restoration's stripe-boundary rows read from it instead of the
21690/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
21691#[allow(clippy::too_many_arguments)]
21692fn apply_loop_restoration(
21693 y: &mut PlaneBuf<'static>,
21694 u: &mut PlaneBuf<'static>,
21695 v: &mut PlaneBuf<'static>,
21696 deblocked_y: &PlaneBuf<'_>,
21697 deblocked_u: &PlaneBuf<'_>,
21698 deblocked_v: &PlaneBuf<'_>,
21699 lr: &LoopRestorationParams,
21700 grid: &crate::restoration::RestorationGrid,
21701 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
21702 // restoration is the ONE post-decode filter that does NOT run over the
21703 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
21704 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
21705 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
21706 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
21707 // -- and asserts it equals the buffer's CROP width
21708 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
21709 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
21710 // that cropped edge before any unit is filtered. Deblock and CDEF DO
21711 // walk the mi grid, which is why passing `true_width`/`true_height`
21712 // here went unnoticed until a frame whose size is not a multiple of 8
21713 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
21714 // read this decoder's own decoded samples at columns 68..71 where
21715 // libaom reads column 67 replicated -- +-1 over the straddling band
21716 // (class av1-truesize-lane: true frame size vs mi-rounded).
21717 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21718) {
21719 // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings.
21720 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_LR") {
21721 return;
21722 }
21723 let mut out = scratch_empty();
21724 crate::restoration::apply_loop_restoration_plane(
21725 &y.data,
21726 &deblocked_y.data,
21727 y.width,
21728 frame_w,
21729 frame_h,
21730 0,
21731 lr.frame_restoration_type[0],
21732 lr.loop_restoration_size[0],
21733 grid,
21734 0,
21735 &mut out, None, fctx,
21736 );
21737 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
21738 let mut out = scratch_empty();
21739 crate::restoration::apply_loop_restoration_plane(
21740 &u.data,
21741 &deblocked_u.data,
21742 u.width,
21743 frame_w.div_ceil(2),
21744 frame_h.div_ceil(2),
21745 1,
21746 lr.frame_restoration_type[1],
21747 lr.loop_restoration_size[1],
21748 grid,
21749 1,
21750 &mut out, None, fctx,
21751 );
21752 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
21753 let mut out = scratch_empty();
21754 crate::restoration::apply_loop_restoration_plane(
21755 &v.data,
21756 &deblocked_v.data,
21757 v.width,
21758 frame_w.div_ceil(2),
21759 frame_h.div_ceil(2),
21760 1,
21761 lr.frame_restoration_type[2],
21762 lr.loop_restoration_size[2],
21763 grid,
21764 2,
21765 &mut out, None, fctx,
21766 );
21767 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
21768}
21769
21770/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
21771/// returning the picture it reconstructs to.
21772///
21773/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
21774/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
21775/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
21776/// `compute_image_size` derives one from the other, but not losslessly: a
21777/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
21778/// what the reconstruction is cropped to on the way out, mirroring
21779/// [`crate::encode::crop_encoded`].
21780///
21781/// # Errors
21782/// Returns an error when a block's partition, mode, skip flag or transform
21783/// type is anything this decoder does not reconstruct (round 2: inter, tx
21784/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
21785/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
21786/// or when the tile payload runs out of the symbols this decode expects (a
21787/// genuinely foreign stream).
21788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21789pub(crate) fn decode_key_frame_tile(
21790 data: &[u8],
21791 mi_cols: u32,
21792 mi_rows: u32,
21793 base_q_idx: u8,
21794 frame_width: u32,
21795 frame_height: u32,
21796 enable_filter_intra: bool,
21797 cdef: &CdefParams,
21798 loop_filter: &LoopFilterParams,
21799 tx_select: bool,
21800 reduced_tx_set: bool,
21801 allow_screen_content_tools: bool,
21802 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
21803) -> Result<Picture> {
21804 decode_key_frame_tile_lr(
21805 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
21806 cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
21807 &LoopRestorationParams::default(), fctx,
21808 )
21809}
21810
21811/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
21812/// 5.9.20) instead of the no-restoration default -- the per-unit filters
21813/// themselves live in the tile payload, so the header is all this needs.
21814#[allow(clippy::too_many_arguments)]
21815pub(crate) fn decode_key_frame_tile_lr(
21816 data: &[u8],
21817 mi_cols: u32,
21818 mi_rows: u32,
21819 base_q_idx: u8,
21820 frame_width: u32,
21821 frame_height: u32,
21822 enable_filter_intra: bool,
21823 cdef: &CdefParams,
21824 loop_filter: &LoopFilterParams,
21825 tx_select: bool,
21826 reduced_tx_set: bool,
21827 allow_screen_content_tools: bool,
21828 allow_intrabc: bool,
21829 lr: &LoopRestorationParams,
21830 fctx: &crate::decode::FrameCtx,
21831) -> Result<Picture> {
21832 let single_tile = TileInfo {
21833 mi_col_starts: vec![0, mi_cols],
21834 mi_row_starts: vec![0, mi_rows],
21835 ..TileInfo::default()
21836 };
21837 decode_key_frame_tiles_lr(
21838 &[data],
21839 &single_tile,
21840 mi_cols,
21841 mi_rows,
21842 base_q_idx,
21843 frame_width,
21844 frame_height,
21845 enable_filter_intra,
21846 cdef,
21847 loop_filter,
21848 tx_select,
21849 reduced_tx_set,
21850 allow_screen_content_tools,
21851 allow_intrabc,
21852 lr,
21853 fctx,
21854 )
21855}
21856
21857/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
21858/// encoder's own filter search hands back one payload per tile plus the
21859/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
21860/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
21861#[allow(clippy::too_many_arguments)]
21862pub(crate) fn decode_key_frame_tiles_lr(
21863 tiles: &[&[u8]],
21864 tile_info: &TileInfo,
21865 mi_cols: u32,
21866 mi_rows: u32,
21867 base_q_idx: u8,
21868 frame_width: u32,
21869 frame_height: u32,
21870 enable_filter_intra: bool,
21871 cdef: &CdefParams,
21872 loop_filter: &LoopFilterParams,
21873 tx_select: bool,
21874 reduced_tx_set: bool,
21875 allow_screen_content_tools: bool,
21876 allow_intrabc: bool,
21877 lr: &LoopRestorationParams,
21878 fctx: &crate::decode::FrameCtx,
21879) -> Result<Picture> {
21880 let delta = DeltaParams::default();
21881 decode_key_frame_tile_with_cdfs(
21882 tiles,
21883 tile_info,
21884 mi_cols,
21885 mi_rows,
21886 base_q_idx,
21887 crate::quant::QuantDeltas::default(),
21888 frame_width,
21889 frame_height,
21890 enable_filter_intra,
21891 false,
21892 cdef,
21893 loop_filter,
21894 lr,
21895 None,
21896 tx_select,
21897 reduced_tx_set,
21898 allow_screen_content_tools,
21899 allow_intrabc,
21900 delta, fctx,
21901 )
21902 .map(|(picture, _)| picture)
21903}
21904
21905 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
21906 /// the mi-aligned `true_width`, set by the most recent
21907 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
21908 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
21909 /// their reconstructed buffer down from the same mi-aligned extent, so
21910 /// they share this one slot. See each function's own comment at its
21911 /// write site. `None` when there was no margin to save.
21912
21913/// The margin the most recent key- or inter-frame tile decode stashed
21914/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
21915/// reads this immediately after the call, before any other frame
21916/// decode can overwrite it.
21917#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21918pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
21919 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
21920}
21921
21922/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
21923/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
21924/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
21925/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
21926/// since a key frame's own header always forces `primary_ref_frame ==
21927/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
21928/// alongside the picture, for the caller to save into whichever reference
21929/// slots this frame's `refresh_frame_flags` names.
21930/// The order the 64x64 superblock quadrants of a tile are decoded in.
21931///
21932/// At `sb_size == 64` this is plain raster order over the tile's own
21933/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
21934/// each 128x128 superblock in raster order and visits its four 64x64
21935/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
21936/// 64-level bodies must run in that nested order. `row_start` marks the first
21937/// item of each *superblock* row (where the left neighbour context resets),
21938/// `sb_start` the first item of each superblock (where the 128 root's own
21939/// loop-restoration units and partition symbol are read).
21940fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
21941 let mut out = Vec::new();
21942 if !sb128 {
21943 for r in r0..r1 {
21944 for c in c0..c1 {
21945 out.push((r, c, c == c0, true));
21946 }
21947 }
21948 return out;
21949 }
21950 let mut r = r0;
21951 while r < r1 {
21952 let mut first_in_row = true;
21953 let mut c = c0;
21954 while c < c1 {
21955 let mut first_in_sb = true;
21956 for qr in 0..2 {
21957 for qc in 0..2 {
21958 let (rr, cc) = (r + qr, c + qc);
21959 if rr >= r1 || cc >= c1 {
21960 continue;
21961 }
21962 out.push((rr, cc, first_in_row, first_in_sb));
21963 first_in_row = false;
21964 first_in_sb = false;
21965 }
21966 }
21967 c += 2;
21968 }
21969 r += 2;
21970 }
21971 out
21972}
21973
21974// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
21975// the inter tile loop. Its loop-restoration units are read once for the whole
21976// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
21977// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
21978// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
21979// decoder codes, the other seven arms refuse by name.
21980thread_local! {
21981 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
21982 /// whole 128x128 block (lane-sb128b r1's gate counter).
21983 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21984 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
21985 /// when the bottom half is out of frame) -- lane-sb128c r7.
21986 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21987 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
21988 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21989 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
21990 /// only shape a 1080p (mi_rows = 270) stream reaches.
21991 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21992 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21993 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
21994 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
21995 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
21996}
21997
21998/// [`PART128_AB_HITS`], for a gate's own before/after delta.
21999pub(crate) fn part128_ab_hits() -> [usize; 4] {
22000 PART128_AB_HITS.with(std::cell::Cell::get)
22001}
22002
22003/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
22004#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
22005pub(crate) fn part128_none_hits() -> usize {
22006 PART128_NONE_HITS.with(std::cell::Cell::get)
22007}
22008
22009/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
22010#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
22011pub(crate) fn part128_horz_hits() -> usize {
22012 PART128_HORZ_HITS.with(std::cell::Cell::get)
22013}
22014
22015/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
22016#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
22017pub(crate) fn part128_vert_hits() -> usize {
22018 PART128_VERT_HITS.with(std::cell::Cell::get)
22019}
22020
22021/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
22022pub(crate) fn part128_edge_horz_hits() -> usize {
22023 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
22024}
22025
22026/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
22027pub(crate) fn part128_edge_vert_hits() -> usize {
22028 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
22029}
22030
22031thread_local! {
22032 /// How many CHROMA transform units were coded inside a block whose uv
22033 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
22034 /// block, four per plane).
22035 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22036}
22037
22038/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
22039#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
22040pub(crate) fn chroma_split_tx_hits() -> usize {
22041 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
22042}
22043
22044fn read_sb128_root(
22045 dec: &mut SymbolDecoder,
22046 cdfs: &mut Cdfs,
22047 neighbours: &Neighbours,
22048 lr: &LoopRestorationParams,
22049 lr_grid: &mut crate::restoration::RestorationGrid,
22050 lr_reference: &mut [(
22051 crate::restoration::WienerInfo,
22052 crate::restoration::SgrprojInfo,
22053 ); 3],
22054 sb_r: u32,
22055 sb_c: u32,
22056 mi_cols: u32,
22057 mi_rows: u32, fctx: &crate::decode::FrameCtx,
22058) -> Result<usize> {
22059 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
22060 crate::restoration::read_lr(
22061 dec,
22062 cdfs,
22063 lr,
22064 lr_grid,
22065 lr_reference,
22066 mi_r128,
22067 mi_c128,
22068 SB_MI * 2, fctx,
22069 );
22070 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
22071 let ctx128 = neighbours.partition_ctx(at128, 128);
22072 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
22073 let part128 = if has_cols128 && has_rows128 {
22074 hit!(PART128_SYMBOLS);
22075 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
22076 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22077 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
22078 }
22079 p
22080 } else {
22081 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
22082 // partition, they are not a forced split -- exactly the discarded-bit
22083 // defect the 64 root carries a comment about at `partition_w64`'s
22084 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
22085 // VERT (cols out of frame), which the refusal below then names
22086 // instead of silently reconstructing a split.
22087 hit!(PART128_GATHERED_SYMBOLS);
22088 match (has_cols128, has_rows128) {
22089 (true, false) => {
22090 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
22091 PARTITION_SPLIT
22092 } else {
22093 hit!(PART128_EDGE_HORZ_HITS);
22094 PARTITION_HORZ
22095 }
22096 }
22097 (false, true) => {
22098 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
22099 PARTITION_SPLIT
22100 } else {
22101 hit!(PART128_EDGE_VERT_HITS);
22102 PARTITION_VERT
22103 }
22104 }
22105 _ => {
22106 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
22107 bump_edge_both_cut(3);
22108 PARTITION_SPLIT
22109 }
22110 }
22111 };
22112 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
22113 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
22114 // four AB shapes) still need the rect/AB machinery at this size.
22115 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
22116 // both tile paths. The four AB shapes (libaom `decode_partition`'s
22117 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
22118 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
22119 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
22120 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
22121 // which stops at VERT_B).
22122 match part128 {
22123 PARTITION_SPLIT => hit!(PART128_SPLIT_HITS),
22124 PARTITION_NONE => hit!(PART128_NONE_HITS),
22125 PARTITION_HORZ => hit!(PART128_HORZ_HITS),
22126 PARTITION_VERT => hit!(PART128_VERT_HITS),
22127 // lane-sb128c r9: the four AB shapes at the 128 root -- one
22128 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
22129 // paths below in libaom `decode_partition`'s own visit order.
22130 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
22131 hit_do! {
22132 PART128_AB_HITS.with(|c| {
22133 let mut h = c.get();
22134 h[p - PARTITION_HORZ_A] += 1;
22135 c.set(h);
22136 });
22137 }
22138 }
22139 _ => {
22140 return Err(unsupported(
22141 "a 128x128 superblock partition value outside the 8-symbol alphabet",
22142 ));
22143 }
22144 }
22145 Ok(part128)
22146}
22147
22148pub(crate) fn decode_key_frame_tile_with_cdfs(
22149 tiles: &[&[u8]],
22150 tile_info: &TileInfo,
22151 mi_cols: u32,
22152 mi_rows: u32,
22153 base_q_idx: u8,
22154 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
22155 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
22156 // tile alongside [`CURRENT_Q_IDX`].
22157 deltas: crate::quant::QuantDeltas,
22158 frame_width: u32,
22159 frame_height: u32,
22160 enable_filter_intra: bool,
22161 enable_edge_filter: bool,
22162 cdef: &CdefParams,
22163 loop_filter: &LoopFilterParams,
22164 lr: &LoopRestorationParams,
22165 initial_cdfs: Option<Cdfs>,
22166 tx_select: bool,
22167 reduced_tx_set: bool,
22168 allow_screen_content_tools: bool,
22169 allow_intrabc: bool,
22170 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
22171 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
22172 // `stream.rs` still refuses a frame with `lf_present` set before this
22173 // function is ever called.
22174 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
22175) -> Result<(Picture, Cdfs)> {
22176 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
22177 // only, so a key frame decoded after an inter frame on this thread would
22178 // otherwise inherit it and read its `tx_depth` context off the inter
22179 // frame's stale `TXFM_CONTEXT` bands.
22180 fctx.tx_select_inter.with(|c| c.set(false));
22181 if mi_cols == 0 || mi_rows == 0 {
22182 return Err(unsupported("a frame with no mode-info grid"));
22183 }
22184 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
22185 let sb128 = sb128(fctx);
22186 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
22187 fctx.intrabc_mi_grid.with(|g| {
22188 *g.borrow_mut() = allow_intrabc.then(|| {
22189 (
22190 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
22191 mi_cols as usize,
22192 mi_rows as usize,
22193 )
22194 });
22195 });
22196 fctx.intrabc_dv.with(|c| c.set(None));
22197 fctx.cdef_bits.with(|c| c.set(cdef.bits));
22198 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
22199 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
22200 fctx.delta_q_present.with(|c| c.set(delta.q_present));
22201 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
22202 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
22203 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
22204 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
22205 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
22206 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
22207 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
22208
22209 let mut y = PlaneBuf {
22210 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
22211 width,
22212 height,
22213 true_width,
22214 true_height,
22215 tile_x0: 0,
22216 tile_y0: 0,
22217 tile_x1: width,
22218 tile_y1: height,
22219 };
22220 let mut u = PlaneBuf {
22221 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
22222 width: width / 2,
22223 height: height / 2,
22224 true_width: true_width / 2,
22225 true_height: true_height / 2,
22226 tile_x0: 0,
22227 tile_y0: 0,
22228 tile_x1: width / 2,
22229 tile_y1: height / 2,
22230 };
22231 let mut v = PlaneBuf {
22232 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
22233 width: width / 2,
22234 height: height / 2,
22235 true_width: true_width / 2,
22236 true_height: true_height / 2,
22237 tile_x0: 0,
22238 tile_y0: 0,
22239 tile_x1: width / 2,
22240 tile_y1: height / 2,
22241 };
22242
22243 let scan32 = default_scan(TX32);
22244 let scan16 = default_scan(TX16);
22245 let scan8 = default_scan(TX8);
22246 let scan4 = default_scan(TX4);
22247
22248 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
22249 let mut result_cdfs = base_cdfs.clone();
22250 let mut neighbours = Neighbours::new(
22251 cols32 as usize * 2,
22252 rows32 as usize * 2,
22253 mi_cols as usize,
22254 mi_rows as usize, fctx,
22255 );
22256 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
22257 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
22258 // loop restoration runs after the superres upscale.
22259 let mut lr_grid = crate::restoration::RestorationGrid::new(
22260 lr,
22261 superres(fctx).map_or(frame_width, |(w, _)| w),
22262 frame_height,
22263 );
22264
22265 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
22266 // own byte range and its own fresh copy of the frame's initial CDFs
22267 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
22268 // `context_update_tile_id` has its end-of-tile adapted table kept as the
22269 // frame's own output (spec `exit_symbol`) -- every other tile's
22270 // adaptation is discarded, matching the refusal this replaces.
22271 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
22272 let tile_num = tile_idx as u32;
22273 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
22274 let mi_row0 = tile_info.mi_row_starts[trow as usize];
22275 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
22276 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
22277 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
22278 // Tile boundaries are always superblock-aligned in mi units (spec
22279 // 5.9.15's uniform/non-uniform derivation both only ever emit
22280 // multiples of the superblock's own mi size), so plain division is
22281 // exact here -- no rounding needed.
22282 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
22283 // tile boundary) are always superblock-aligned by spec 5.9.15; the
22284 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
22285 // last entry) is not, so the upper bound needs `div_ceil` the same
22286 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
22287 // trailing partial superblock row/column in scope.
22288 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
22289 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
22290
22291 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
22292 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
22293 // once per frame. Carried across a tile boundary, the loop-restoration
22294 // coefficients of the next tile decode off the previous tile's
22295 // reference -- same symbol count, so entropy and reconstruction stay
22296 // exact and only the filtered pixels of every tile after the first
22297 // are wrong.
22298 let mut lr_reference = [(
22299 crate::restoration::WienerInfo::default(),
22300 crate::restoration::SgrprojInfo::default(),
22301 ); 3];
22302 let mut cdfs = base_cdfs.clone();
22303 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
22304 // `base_q_idx` at the top of every tile, not once per frame.
22305 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
22306 fctx.quant_deltas.with(|c| c.set(deltas));
22307 fctx.current_delta_lf.with(|c| c.set([0; 4]));
22308 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22309 eprintln!(
22310 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
22311 tile_bytes.len(),
22312 &tile_bytes[..tile_bytes.len().min(8)]
22313 );
22314 }
22315 let mut dec = SymbolDecoder::new(tile_bytes);
22316 crate::census::register_cdfs(&cdfs);
22317 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
22318 y.set_tile_origin(
22319 mi_col0 as usize * 4,
22320 mi_row0 as usize * 4,
22321 (mi_col1 as usize * 4).min(y.width),
22322 (mi_row1 as usize * 4).min(y.height),
22323 );
22324 u.set_tile_origin(
22325 mi_col0 as usize * 2,
22326 mi_row0 as usize * 2,
22327 (mi_col1 as usize * 2).min(u.width),
22328 (mi_row1 as usize * 2).min(u.height),
22329 );
22330 v.set_tile_origin(
22331 mi_col0 as usize * 2,
22332 mi_row0 as usize * 2,
22333 (mi_col1 as usize * 2).min(v.width),
22334 (mi_row1 as usize * 2).min(v.height),
22335 );
22336 hit!(TILE_HITS);
22337
22338 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
22339 // its one block covers all four 64x64 quadrants, so the remaining three
22340 // visits of this superblock code nothing at all.
22341 let mut sb128_none = false;
22342 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
22343 // are performed at their push sites (nothing reaches the queue below).
22344 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
22345 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
22346 // when `sb128`, since a 128 block writes across its four 64x64 visits).
22347 let wave_shift = u32::from(sb128);
22348 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
22349 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
22350 (
22351 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
22352 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
22353 )
22354 } else {
22355 (0, 0)
22356 };
22357 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
22358 let waving = fctx.wave.with(|w| w.borrow().is_some());
22359 let mut wave_job = (0usize, 0usize);
22360 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
22361 // lane-wave1: the previous superblock's recorded writes -- handed to
22362 // the wavefront workers, or replayed here at one recon thread (where
22363 // the queue is empty, every write having run at its push site).
22364 if waving {
22365 if sb_start {
22366 wave_submit(fctx, wave_job.0, wave_job.1);
22367 wave_job = (
22368 (sb_r >> wave_shift) as usize - wave_r0,
22369 (sb_c >> wave_shift) as usize - wave_c0,
22370 );
22371 }
22372 } else {
22373 flush_recon(fctx, &mut y, &mut u, &mut v);
22374 }
22375 if row_start {
22376 neighbours.start_row();
22377 }
22378 if sb_start {
22379 sb128_none = false;
22380 }
22381 if sb128_none {
22382 continue;
22383 }
22384 {
22385 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
22386 // once for the whole 128x128 (spec 5.11.57 is called with the
22387 // superblock's own size), then one partition symbol off the
22388 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
22389 // recurses into the four 64x64 quadrants this decoder codes.
22390 if sb128 && sb_start {
22391 let part128 = read_sb128_root(
22392 &mut dec,
22393 &mut cdfs,
22394 &neighbours,
22395 lr,
22396 &mut lr_grid,
22397 &mut lr_reference,
22398 sb_r,
22399 sb_c,
22400 mi_cols,
22401 mi_rows, fctx,
22402 )?;
22403 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
22404 // lane-sb128c r9: the four AB shapes at the 128 root.
22405 // libaom `decode_partition` (decodeframe.c) codes each as
22406 // two `bsize2` (64x64) squares plus one `subsize`
22407 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
22408 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
22409 // half; VERT_B = left half, TR, BR. AB values only come
22410 // from the FULL alphabet symbol, which is only read when
22411 // both halves of the root are inside the frame, so no
22412 // piece needs libaom's `i > 0` frame-edge break (a piece
22413 // may still overhang the bottom/right, which
22414 // `PlaneBuf::reconstruct`'s r8 clip handles).
22415 sb128_none = true;
22416 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22417 let (br, bc) = (at128.0 + 4, at128.1 + 4);
22418 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22419 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
22420 // BR), so only they switch libaom's `has_tr_vert_*` /
22421 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
22422 let _vert_ab =
22423 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
22424 .then(crate::encode::Reach::vert_ab_partition);
22425 // One `cdef_idx` literal per CODED BLOCK, at the first
22426 // non-skip one of each 64x64 CDEF unit; the 128x64 /
22427 // 64x128 half covers two units and its read lands in the
22428 // unit holding its origin, so that value is copied to the
22429 // other one (libaom: every mi of the block points at the
22430 // same `MB_MODE_INFO`).
22431 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
22432 fctx.cdef_idx_grid.with(|g| {
22433 let mut g = g.borrow_mut();
22434 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22435 if cols == 0 {
22436 return;
22437 }
22438 let (si, di) = (
22439 (q_r + src.0) * cols + q_c + src.1,
22440 (q_r + dst.0) * cols + q_c + dst.1,
22441 );
22442 if q_c + src.1 < cols
22443 && q_c + dst.1 < cols
22444 && si < g.len()
22445 && di < g.len()
22446 {
22447 g[di] = g[si];
22448 }
22449 });
22450 };
22451 macro_rules! square64 {
22452 ($at:expr) => {{
22453 fctx.cdef_transmitted.with(|c| c.set(false));
22454 decode_block(
22455 &mut dec,
22456 &mut cdfs,
22457 &mut neighbours,
22458 $at,
22459 SB,
22460 TxbSet::Luma64,
22461 TxbSet::Chroma32,
22462 TX32,
22463 TX32,
22464 (&scan32, &scan32),
22465 false,
22466 &mut y,
22467 &mut u,
22468 &mut v,
22469 base_q_idx,
22470 enable_filter_intra,
22471 allow_screen_content_tools,
22472 allow_intrabc,
22473 &scan32,
22474 &scan16,
22475 &scan8,
22476 &scan4,
22477 tx_select,
22478 reduced_tx_set, fctx,
22479 )?
22480 }};
22481 }
22482 macro_rules! half128 {
22483 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
22484 fctx.cdef_transmitted.with(|c| c.set(false));
22485 decode_block_128rect(
22486 &mut dec,
22487 &mut cdfs,
22488 &mut neighbours,
22489 $at,
22490 $bw,
22491 $bh,
22492 &mut y,
22493 &mut u,
22494 &mut v,
22495 base_q_idx,
22496 enable_filter_intra,
22497 allow_screen_content_tools,
22498 tx_select,
22499 reduced_tx_set, fctx,
22500 )?;
22501 cdef_copy($src, $dst);
22502 }};
22503 }
22504 match part128 {
22505 PARTITION_HORZ_A => {
22506 square64!(at128);
22507 square64!((at128.0, bc));
22508 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
22509 }
22510 PARTITION_HORZ_B => {
22511 half128!(at128, 128, 64, (0, 0), (0, 1));
22512 square64!((br, at128.1));
22513 square64!((br, bc));
22514 }
22515 PARTITION_VERT_A => {
22516 square64!(at128);
22517 square64!((br, at128.1));
22518 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
22519 }
22520 _ => {
22521 half128!(at128, 64, 128, (0, 0), (1, 0));
22522 square64!((at128.0, bc));
22523 square64!((br, bc));
22524 }
22525 }
22526 continue;
22527 }
22528 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
22529 // lane-sb128c r8: libaom `decode_partition`
22530 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
22531 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
22532 // plus a second one at (mi_row + hbs, mi_col) only
22533 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
22534 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
22535 // = 16 mi. Both halves together cover the whole root, so
22536 // the remaining three 64x64 quadrant visits code nothing
22537 // (same flag the NONE arm sets).
22538 sb128_none = true;
22539 let horz = part128 == PARTITION_HORZ;
22540 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22541 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
22542 for i in 0..2 {
22543 let at = if horz {
22544 (at128.0 + i * 4, at128.1)
22545 } else {
22546 (at128.0, at128.1 + i * 4)
22547 };
22548 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
22549 if i > 0
22550 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
22551 {
22552 break;
22553 }
22554 // Each half reads its OWN `cdef_idx` literal
22555 // (libaom `read_cdef` keys the `-1` test on the
22556 // block's own `MB_MODE_INFO`, and the two halves have
22557 // different ones).
22558 fctx.cdef_transmitted.with(|c| c.set(false));
22559 decode_block_128rect(
22560 &mut dec,
22561 &mut cdfs,
22562 &mut neighbours,
22563 at,
22564 bw,
22565 bh,
22566 &mut y,
22567 &mut u,
22568 &mut v,
22569 base_q_idx,
22570 enable_filter_intra,
22571 allow_screen_content_tools,
22572 tx_select,
22573 reduced_tx_set, fctx,
22574 )?;
22575 }
22576 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
22577 // unit it covers (the inter path's own fan-out).
22578 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22579 fctx.cdef_idx_grid.with(|g| {
22580 let mut g = g.borrow_mut();
22581 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22582 if cols == 0 {
22583 return;
22584 }
22585 for (src, dst) in if horz {
22586 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
22587 } else {
22588 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
22589 } {
22590 let (si, di) = (
22591 (q_r + src.0) * cols + q_c + src.1,
22592 (q_r + dst.0) * cols + q_c + dst.1,
22593 );
22594 if q_c + src.1 < cols
22595 && q_c + dst.1 < cols
22596 && si < g.len()
22597 && di < g.len()
22598 {
22599 g[di] = g[si];
22600 }
22601 }
22602 });
22603 continue;
22604 }
22605 if part128 == PARTITION_NONE {
22606 // One 128x128 intra block: four TX_64X64 luma units and a
22607 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
22608 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
22609 // block). No CfL, no filter intra, no palette at this size --
22610 // [`read_intra_mode`]'s own size gates already say so.
22611 sb128_none = true;
22612 fctx.cdef_transmitted.with(|c| c.set(false));
22613 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22614 decode_block(
22615 &mut dec,
22616 &mut cdfs,
22617 &mut neighbours,
22618 at128,
22619 SB * 2,
22620 TxbSet::Luma64,
22621 TxbSet::Chroma32,
22622 TX32,
22623 TX32,
22624 (&scan32, &scan32),
22625 false,
22626 &mut y,
22627 &mut u,
22628 &mut v,
22629 base_q_idx,
22630 enable_filter_intra,
22631 allow_screen_content_tools,
22632 allow_intrabc,
22633 &scan32,
22634 &scan16,
22635 &scan8,
22636 &scan4,
22637 tx_select,
22638 reduced_tx_set, fctx,
22639 )?;
22640 // libaom writes one `cdef_strength` into the block's own
22641 // `MB_MODE_INFO`, which every mi cell of the block --
22642 // hence all four 64x64 CDEF units -- points at; our grid
22643 // is per-unit, so the read (which only ever lands in the
22644 // top-left unit, `read_cdef`'s index 0) is copied across.
22645 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22646 fctx.cdef_idx_grid.with(|g| {
22647 let mut g = g.borrow_mut();
22648 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22649 if cols > 0 && q_r * cols + q_c < g.len() {
22650 let idx = g[q_r * cols + q_c];
22651 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
22652 let i = (q_r + dr) * cols + q_c + dc;
22653 if q_c + dc < cols && i < g.len() {
22654 g[i] = idx;
22655 }
22656 }
22657 }
22658 });
22659 continue;
22660 }
22661 }
22662 if !sb128 {
22663 crate::restoration::read_lr(
22664 &mut dec,
22665 &mut cdfs,
22666 lr,
22667 &mut lr_grid,
22668 &mut lr_reference,
22669 sb_r * SB_MI,
22670 sb_c * SB_MI,
22671 SB_MI, fctx,
22672 );
22673 }
22674 fctx.cdef_transmitted.with(|c| c.set(false));
22675 let at = (sb_r as usize * 4, sb_c as usize * 4);
22676 let ctx = neighbours.partition_ctx(at, SB);
22677 let (has_cols, has_rows) = (
22678 sb_c * SB_MI + SB_MI / 2 < mi_cols,
22679 sb_r * SB_MI + SB_MI / 2 < mi_rows,
22680 );
22681 // Recomputed at this superblock's own half (spec
22682 // `decode_partition`): a full alphabet symbol when both halves are
22683 // inside the true frame, a single gathered bit when just one is
22684 // (the superblock cannot be left whole, so this is forced split),
22685 // and nothing at all (SPLIT inferred, no bits) when neither is —
22686 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
22687 // three-way write exactly.
22688 let part = if has_cols && has_rows {
22689 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
22690 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22691 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
22692 }
22693 p
22694 } else {
22695 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
22696 // the unmerged lane-golomb r1): the gathered bit IS the
22697 // partition -- libaom `ec_read_partition_impl` returns
22698 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
22699 // Forcing SPLIT desynced the last superblock row of every
22700 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
22701 // the first block of that row.
22702 match (has_cols, has_rows) {
22703 (true, false) => {
22704 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22705 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
22706 bump_edge32(4 + b.min(1) as usize);
22707 bump_edge_part(b.min(1) as usize);
22708 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22709 }
22710 (false, true) => {
22711 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22712 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
22713 bump_edge32(4 + b.min(1) as usize);
22714 bump_edge_part(b.min(1) as usize);
22715 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22716 }
22717 _ => {
22718 bump_edge_both_cut(2);
22719 PARTITION_SPLIT
22720 }
22721 }
22722 };
22723 match part {
22724 PARTITION_NONE => {
22725 decode_block(
22726 &mut dec,
22727 &mut cdfs,
22728 &mut neighbours,
22729 at,
22730 SB,
22731 TxbSet::Luma64,
22732 TxbSet::Chroma32,
22733 TX32,
22734 TX32,
22735 (&scan32, &scan32),
22736 false,
22737 &mut y,
22738 &mut u,
22739 &mut v,
22740 base_q_idx,
22741 enable_filter_intra,
22742 allow_screen_content_tools,
22743 allow_intrabc,
22744 &scan32,
22745 &scan16,
22746 &scan8,
22747 &scan4,
22748 tx_select,
22749 reduced_tx_set, fctx,
22750 )?;
22751 }
22752 PARTITION_SPLIT => {
22753 for q in 0..4 {
22754 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
22755 if r32 >= rows32 || c32 >= cols32 {
22756 continue;
22757 }
22758 let at32 = (r32 as usize * 2, c32 as usize * 2);
22759 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
22760 let (has_cols32, has_rows32) = (
22761 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
22762 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
22763 );
22764 let part32 = if has_cols32 && has_rows32 {
22765 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
22766 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22767 let (rng, _) = dec.debug_state();
22768 eprintln!(
22769 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
22770 r32 * BLOCK_MI,
22771 c32 * BLOCK_MI
22772 );
22773 }
22774 p
22775 } else {
22776 // lane-hgkf r1: the 32-level frame-edge bit is the
22777 // partition too (same libaom reader as the
22778 // superblock level above).
22779 match (has_cols32, has_rows32) {
22780 (true, false) => {
22781 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22782 let b = dec.symbol_fixed(&gather(
22783 &cdfs.partition_w32[ctx32],
22784 VERT_ALIKE,
22785 ));
22786 bump_edge32(b.min(1) as usize);
22787 bump_edge_part(2 + b.min(1) as usize);
22788 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22789 }
22790 (false, true) => {
22791 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22792 let b = dec.symbol_fixed(&gather(
22793 &cdfs.partition_w32[ctx32],
22794 HORZ_ALIKE,
22795 ));
22796 bump_edge32(b.min(1) as usize);
22797 bump_edge_part(2 + b.min(1) as usize);
22798 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22799 }
22800 _ => {
22801 bump_edge_both_cut(1);
22802 PARTITION_SPLIT
22803 }
22804 }
22805 };
22806 match part32 {
22807 PARTITION_NONE => {
22808 decode_block(
22809 &mut dec,
22810 &mut cdfs,
22811 &mut neighbours,
22812 at32,
22813 BLOCK,
22814 TxbSet::Luma32,
22815 TxbSet::Chroma16,
22816 TX32,
22817 TX16,
22818 (&scan32, &scan16),
22819 true,
22820 &mut y,
22821 &mut u,
22822 &mut v,
22823 base_q_idx,
22824 enable_filter_intra,
22825 allow_screen_content_tools,
22826 allow_intrabc,
22827 &scan32,
22828 &scan16,
22829 &scan8,
22830 &scan4,
22831 tx_select,
22832 reduced_tx_set, fctx,
22833 )?;
22834 }
22835 PARTITION_SPLIT => {
22836 for sub in 0..4 {
22837 let (sr, sc) =
22838 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
22839 if (sr as u32) * SUB_MI >= mi_rows
22840 || (sc as u32) * SUB_MI >= mi_cols
22841 {
22842 continue;
22843 }
22844 let (has_cols16, has_rows16) = (
22845 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
22846 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
22847 );
22848 let at16 = (sr, sc);
22849 let ctx16 = neighbours.partition_ctx(at16, SUB);
22850 if has_cols16 && has_rows16 {
22851 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
22852 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22853 eprintln!(
22854 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
22855 at16.0, at16.1
22856 );
22857 }
22858 if part16 == PARTITION_NONE {
22859 decode_block(
22860 &mut dec,
22861 &mut cdfs,
22862 &mut neighbours,
22863 at16,
22864 SUB,
22865 TxbSet::Luma16,
22866 TxbSet::Chroma8,
22867 TX16,
22868 TX8,
22869 (&scan16, &scan8),
22870 true,
22871 &mut y,
22872 &mut u,
22873 &mut v,
22874 base_q_idx,
22875 enable_filter_intra,
22876 allow_screen_content_tools,
22877 allow_intrabc,
22878 &scan32,
22879 &scan16,
22880 &scan8,
22881 &scan4,
22882 tx_select,
22883 reduced_tx_set, fctx,
22884 )?;
22885 continue;
22886 }
22887 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
22888 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
22889 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
22890 // `decode_partition` visit order (decodeframe.c):
22891 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
22892 // HORZ_B: top 16x8, BL 8x8, BR 8x8
22893 // VERT_A: TL 8x8, BL 8x8, right 8x16
22894 // VERT_B: left 8x16, TR 8x8, BR 8x8
22895 // The squares go through `decode_leaf8`, the strip through
22896 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
22897 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
22898 // used refuses the non-skip case at this size). Both writers keep
22899 // mi-granular mode/skip/palette records, so a later block's
22900 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
22901 // 16x16 cell.
22902 //
22903 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
22904 // top-right neighbour is the partition's own not-yet-decoded
22905 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
22906 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
22907 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
22908 let arm = part16 - PARTITION_HORZ_A;
22909 bump_ab16(arm);
22910 if part16 == PARTITION_VERT_B {
22911 hit!(VERT_B_INTRA_HITS);
22912 }
22913 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
22914 Some(crate::encode::Reach::vert_ab_partition())
22915 } else {
22916 None
22917 };
22918 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
22919 macro_rules! ab_leaf8 {
22920 ($mi:expr, $prev:expr) => {
22921 decode_leaf8(
22922 &mut dec,
22923 &mut cdfs,
22924 &mut neighbours,
22925 at16,
22926 $mi,
22927 (&scan8, &scan4),
22928 $prev,
22929 &mut y,
22930 &mut u,
22931 &mut v,
22932 base_q_idx,
22933 enable_filter_intra,
22934 allow_screen_content_tools,
22935 allow_intrabc,
22936 tx_select,
22937 reduced_tx_set, fctx,
22938 )?
22939 };
22940 }
22941 macro_rules! ab_strip {
22942 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
22943 decode_leaf_rect(
22944 &mut dec,
22945 &mut cdfs,
22946 &mut neighbours,
22947 at16,
22948 $mi,
22949 $bw,
22950 $bh,
22951 $prev,
22952 &mut y,
22953 &mut u,
22954 &mut v,
22955 enable_filter_intra,
22956 allow_screen_content_tools,
22957 base_q_idx,
22958 tx_select,
22959 reduced_tx_set, fctx,
22960 )?
22961 };
22962 }
22963 let tl = (mi_row0, mi_col0);
22964 let tr = (mi_row0, mi_col0 + 2);
22965 let bl = (mi_row0 + 2, mi_col0);
22966 let br = (mi_row0 + 2, mi_col0 + 2);
22967 let mut done: Vec<((usize, usize), usize)> = Vec::new();
22968 match part16 {
22969 PARTITION_HORZ_A => {
22970 let m_tl = ab_leaf8!(tl, done.last().copied());
22971 done.push((tl, m_tl));
22972 let m_tr = ab_leaf8!(tr, done.last().copied());
22973 done.push((tr, m_tr));
22974 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
22975 done.push((bl, m_bot));
22976 }
22977 PARTITION_HORZ_B => {
22978 let m_top = ab_strip!(tl, 16, 8, None);
22979 done.push((tl, m_top));
22980 let m_bl = ab_leaf8!(bl, done.last().copied());
22981 done.push((bl, m_bl));
22982 let m_br = ab_leaf8!(br, done.last().copied());
22983 done.push((br, m_br));
22984 }
22985 PARTITION_VERT_A => {
22986 let m_tl = ab_leaf8!(tl, done.last().copied());
22987 done.push((tl, m_tl));
22988 let m_bl = ab_leaf8!(bl, done.last().copied());
22989 done.push((bl, m_bl));
22990 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
22991 done.push((tr, m_right));
22992 }
22993 _ => {
22994 let m_left = ab_strip!(tl, 8, 16, None);
22995 done.push((tl, m_left));
22996 let m_tr = ab_leaf8!(tr, done.last().copied());
22997 done.push((tr, m_tr));
22998 let m_br = ab_leaf8!(br, done.last().copied());
22999 done.push((br, m_br));
23000 }
23001 }
23002 // Same coarse-slot write-back the real SPLIT path takes: the
23003 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
23004 // sub-block on the parent's bottom / right edge (the mi-exact map
23005 // above wins wherever it has an entry).
23006 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
23007 continue;
23008 }
23009 if part16 == PARTITION_HORZ {
23010 hit!(HORZ_VERT_INTRA_HITS);
23011 let (mi_row0, mi_col0) = (
23012 sr as u32 * SUB_MI,
23013 sc as u32 * SUB_MI,
23014 );
23015 let top = (mi_row0 as usize, mi_col0 as usize);
23016 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
23017 let mode_top = decode_leaf_rect(
23018 &mut dec,
23019 &mut cdfs,
23020 &mut neighbours,
23021 at16,
23022 top,
23023 16,
23024 8,
23025 None,
23026 &mut y,
23027 &mut u,
23028 &mut v,
23029 enable_filter_intra,
23030 allow_screen_content_tools,
23031 base_q_idx,
23032 tx_select,
23033 reduced_tx_set, fctx,
23034 )?;
23035 let mode_bot = decode_leaf_rect(
23036 &mut dec,
23037 &mut cdfs,
23038 &mut neighbours,
23039 at16,
23040 bot,
23041 16,
23042 8,
23043 Some((top, mode_top)),
23044 &mut y,
23045 &mut u,
23046 &mut v,
23047 enable_filter_intra,
23048 allow_screen_content_tools,
23049 base_q_idx,
23050 tx_select,
23051 reduced_tx_set, fctx,
23052 )?;
23053 neighbours.above_mode[sc] = mode_bot;
23054 neighbours.left_mode[sr] = mode_bot;
23055 continue;
23056 }
23057 if part16 == PARTITION_VERT {
23058 hit!(HORZ_VERT_INTRA_HITS);
23059 let (mi_row0, mi_col0) = (
23060 sr as u32 * SUB_MI,
23061 sc as u32 * SUB_MI,
23062 );
23063 let left = (mi_row0 as usize, mi_col0 as usize);
23064 let right = (mi_row0 as usize, mi_col0 as usize + 2);
23065 let mode_left = decode_leaf_rect(
23066 &mut dec,
23067 &mut cdfs,
23068 &mut neighbours,
23069 at16,
23070 left,
23071 8,
23072 16,
23073 None,
23074 &mut y,
23075 &mut u,
23076 &mut v,
23077 enable_filter_intra,
23078 allow_screen_content_tools,
23079 base_q_idx,
23080 tx_select,
23081 reduced_tx_set, fctx,
23082 )?;
23083 let mode_right = decode_leaf_rect(
23084 &mut dec,
23085 &mut cdfs,
23086 &mut neighbours,
23087 at16,
23088 right,
23089 8,
23090 16,
23091 Some((left, mode_left)),
23092 &mut y,
23093 &mut u,
23094 &mut v,
23095 enable_filter_intra,
23096 allow_screen_content_tools,
23097 base_q_idx,
23098 tx_select,
23099 reduced_tx_set, fctx,
23100 )?;
23101 neighbours.above_mode[sc] = mode_right;
23102 neighbours.left_mode[sr] = mode_right;
23103 continue;
23104 }
23105 if part16 == PARTITION_HORZ_4
23106 || part16 == PARTITION_VERT_4
23107 {
23108 decode_rect4_16(
23109 &mut dec,
23110 &mut cdfs,
23111 &mut neighbours,
23112 at16,
23113 part16 == PARTITION_HORZ_4,
23114 &mut y,
23115 &mut u,
23116 &mut v,
23117 enable_filter_intra,
23118 allow_screen_content_tools,
23119 base_q_idx,
23120 tx_select,
23121 reduced_tx_set, fctx,
23122 )?;
23123 continue;
23124 }
23125 // lane-r14 r2 (verifier note): every
23126 // one of the 10 symbols this CDF can
23127 // produce is handled above, so SPLIT
23128 // is the only value that reaches
23129 // here -- the refusal that used to
23130 // stand here was unreachable and is
23131 // gone from `refusal_inventory`.
23132 debug_assert_eq!(part16, PARTITION_SPLIT);
23133 // A real (non-straddle) SPLIT of a
23134 // whole 16x16 into four 8x8 leaves --
23135 // the same recursion the straddle
23136 // path below already runs when the
23137 // true frame edge forces it, just
23138 // over all four positions instead of
23139 // the one or two the edge leaves.
23140 let (mi_row0, mi_col0) =
23141 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23142 // Each 8x8 leaf's intra-mode context
23143 // must see its own siblings: the
23144 // bottom-left leaf's ABOVE neighbour
23145 // is leaf 0, not the previously
23146 // decoded leaf 1 (and the bottom-right
23147 // leaf's above is leaf 1, while
23148 // `prev_leaf` only ever carried the
23149 // immediately preceding one). The
23150 // coarse `above_mode`/`left_mode`
23151 // arrays hold one slot per 16x16, so
23152 // the sibling modes are swapped in
23153 // around each leaf call and restored
23154 // after; the loop tail writes the last
23155 // leaf's mode as before.
23156 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
23157 for i in 0..4 {
23158 let (mr, mc) =
23159 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
23160 let leaf_mi = (mr as usize, mc as usize);
23161 let li = i as usize;
23162 let saved_modes =
23163 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
23164 if li >= 2 {
23165 if let Some((below, _)) = sib_modes[li - 2] {
23166 neighbours.above_mode[sc] = below;
23167 }
23168 }
23169 if li % 2 == 1 {
23170 if let Some((_, right)) = sib_modes[li - 1] {
23171 neighbours.left_mode[sr] = right;
23172 }
23173 }
23174 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
23175 let part8 =
23176 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
23177 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23178 eprintln!(
23179 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
23180 );
23181 }
23182 let leaf_mode = if part8 == PARTITION_NONE {
23183 decode_leaf8(
23184 &mut dec,
23185 &mut cdfs,
23186 &mut neighbours,
23187 at16,
23188 leaf_mi,
23189 (&scan8, &scan4),
23190 None,
23191 &mut y,
23192 &mut u,
23193 &mut v,
23194 base_q_idx,
23195 enable_filter_intra,
23196 allow_screen_content_tools,
23197 allow_intrabc,
23198 tx_select,
23199 reduced_tx_set, fctx,
23200 ).map(|m| (m, m))?
23201 } else if part8 == PARTITION_SPLIT {
23202 decode_leaf_split4(
23203 &mut dec,
23204 &mut cdfs,
23205 &mut neighbours,
23206 at16,
23207 leaf_mi,
23208 &scan4,
23209 None,
23210 &mut y,
23211 &mut u,
23212 &mut v,
23213 base_q_idx,
23214 enable_filter_intra,
23215 allow_intrabc,
23216 reduced_tx_set, fctx,
23217 )?
23218 } else if part8 == PARTITION_HORZ
23219 || part8 == PARTITION_VERT
23220 {
23221 decode_leaf_rect8(
23222 &mut dec,
23223 &mut cdfs,
23224 &mut neighbours,
23225 at16,
23226 leaf_mi,
23227 part8 == PARTITION_VERT,
23228 &scan4,
23229 &mut y,
23230 &mut u,
23231 &mut v,
23232 base_q_idx,
23233 enable_filter_intra,
23234 allow_intrabc,
23235 tx_select,
23236 reduced_tx_set, fctx,
23237 )?
23238 } else {
23239 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
23240 };
23241 neighbours.above_mode[sc] = saved_modes.0;
23242 neighbours.left_mode[sr] = saved_modes.1;
23243 sib_modes[li] = Some(leaf_mode);
23244 }
23245 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
23246 neighbours.above_mode[sc] = below;
23247 }
23248 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
23249 neighbours.left_mode[sr] = right;
23250 }
23251 continue;
23252 }
23253 // The true edge falls inside this 16x16
23254 // leaf itself (mod-32==8 target sizes,
23255 // lane-av1-rect): one axis only -- an 8x8
23256 // leaf never itself straddles, so the
23257 // block splits cleanly along whichever
23258 // axis is short.
23259 // lane-edgeboth r1: when the true frame
23260 // edge cuts BOTH axes libaom's
23261 // `decode_partition` takes
23262 // `else if (!has_rows && !has_cols)
23263 // partition = PARTITION_SPLIT;` -- no
23264 // symbol of any kind is read, and the four
23265 // 8x8 children are then visited by the
23266 // same loop below, whose
23267 // `mr < mi_rows && mc < mi_cols` filter IS
23268 // libaom's own
23269 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
23270 // early return, so the three out-of-frame
23271 // quadrants get no neighbour or tx-grid
23272 // write.
23273 if !has_cols16 && !has_rows16 {
23274 bump_edge_both_cut(0);
23275 } else {
23276 // lane-golomb r1 (class
23277 // `parsed-then-discarded`): the gathered
23278 // bit IS the partition -- 0 names
23279 // PARTITION_HORZ (resp. VERT), only 1 is
23280 // SPLIT (libaom `ec_read_partition_impl`).
23281 // This path can only walk the four SPLIT
23282 // leaves, so a 0 refuses by name instead
23283 // of desyncing.
23284 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
23285 let edge_split = if has_cols16 {
23286 dec.symbol_fixed(&gather(
23287 &cdfs.partition_w16[ctx16],
23288 VERT_ALIKE,
23289 ))
23290 } else {
23291 dec.symbol_fixed(&gather(
23292 &cdfs.partition_w16[ctx16],
23293 HORZ_ALIKE,
23294 ))
23295 };
23296 // lane-hgkf r1: slots 2/3 of
23297 // [`EDGE_PART_HITS`], the gate's proof the
23298 // non-SPLIT edge arm actually decoded.
23299 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
23300 if edge_split == 0 {
23301 // lane-oddh r1: the strip IS decodable
23302 // -- libaom's `decode_partition` codes
23303 // only the FIRST half of an edge
23304 // HORZ/VERT (the second call is
23305 // guarded by the same has_rows/
23306 // has_cols test that made the
23307 // partition non-square), so one
23308 // 16x8 (resp. 8x16) strip covers the
23309 // whole visible band of a frame whose
23310 // height (resp. width) is 8 mod 16 --
23311 // the user's 3840x1608 film.
23312 hit!(HORZ_VERT_INTRA_HITS);
23313 hit!(EDGE_RECT_STRIP_HITS);
23314 let (mi_row0, mi_col0) =
23315 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23316 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
23317 let mode = decode_leaf_rect(
23318 &mut dec,
23319 &mut cdfs,
23320 &mut neighbours,
23321 at16,
23322 (mi_row0 as usize, mi_col0 as usize),
23323 bw,
23324 bh,
23325 None,
23326 &mut y,
23327 &mut u,
23328 &mut v,
23329 enable_filter_intra,
23330 allow_screen_content_tools,
23331 base_q_idx,
23332 tx_select,
23333 reduced_tx_set, fctx,
23334 )?;
23335 neighbours.above_mode[sc] = mode;
23336 neighbours.left_mode[sr] = mode;
23337 continue;
23338 }
23339 }
23340 let (mi_row0, mi_col0) =
23341 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23342 let leaf_positions: Vec<(u32, u32)> = (0..4)
23343 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
23344 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
23345 .collect();
23346 // See the sibling-mode note in the clean
23347 // SPLIT path above.
23348 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
23349 for (mr, mc) in leaf_positions {
23350 let leaf_mi = (mr as usize, mc as usize);
23351 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
23352 as usize;
23353 let saved_modes =
23354 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
23355 if li >= 2 {
23356 if let Some((below, _)) = sib_modes[li - 2] {
23357 neighbours.above_mode[sc] = below;
23358 }
23359 }
23360 if li % 2 == 1 {
23361 if let Some((_, right)) = sib_modes[li - 1] {
23362 neighbours.left_mode[sr] = right;
23363 }
23364 }
23365 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
23366 let pre8 = dec.debug_state().0;
23367 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
23368 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23369 eprintln!(
23370 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
23371 );
23372 }
23373 let leaf_mode = if part8 == PARTITION_NONE {
23374 decode_leaf8(
23375 &mut dec,
23376 &mut cdfs,
23377 &mut neighbours,
23378 at16,
23379 leaf_mi,
23380 (&scan8, &scan4),
23381 None,
23382 &mut y,
23383 &mut u,
23384 &mut v,
23385 base_q_idx,
23386 enable_filter_intra,
23387 allow_screen_content_tools,
23388 allow_intrabc,
23389 tx_select,
23390 reduced_tx_set, fctx,
23391 ).map(|m| (m, m))?
23392 } else if part8 == PARTITION_SPLIT {
23393 decode_leaf_split4(
23394 &mut dec,
23395 &mut cdfs,
23396 &mut neighbours,
23397 at16,
23398 leaf_mi,
23399 &scan4,
23400 None,
23401 &mut y,
23402 &mut u,
23403 &mut v,
23404 base_q_idx,
23405 enable_filter_intra,
23406 allow_intrabc,
23407 reduced_tx_set, fctx,
23408 )?
23409 } else if part8 == PARTITION_HORZ
23410 || part8 == PARTITION_VERT
23411 {
23412 decode_leaf_rect8(
23413 &mut dec,
23414 &mut cdfs,
23415 &mut neighbours,
23416 at16,
23417 leaf_mi,
23418 part8 == PARTITION_VERT,
23419 &scan4,
23420 &mut y,
23421 &mut u,
23422 &mut v,
23423 base_q_idx,
23424 enable_filter_intra,
23425 allow_intrabc,
23426 tx_select,
23427 reduced_tx_set, fctx,
23428 )?
23429 } else {
23430 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
23431 };
23432 neighbours.above_mode[sc] = saved_modes.0;
23433 neighbours.left_mode[sr] = saved_modes.1;
23434 sib_modes[li] = Some(leaf_mode);
23435 }
23436 // `record()`'s `above_mode`/`left_mode`
23437 // write is a no-op at an 8x8 leaf's own
23438 // side, so force the write once the whole
23439 // 16x16 slot's leaves are done, from the
23440 // last leaf (mirrors the writer's r15
23441 // fix).
23442 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
23443 neighbours.above_mode[sc] = below;
23444 }
23445 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
23446 neighbours.left_mode[sr] = right;
23447 }
23448 }
23449 }
23450 PARTITION_HORZ => {
23451 // lane-intradisp r1: two true 32x16 strips.
23452 decode_block_rect(
23453 &mut dec,
23454 &mut cdfs,
23455 &mut neighbours,
23456 at32,
23457 32,
23458 16,
23459 &mut y,
23460 &mut u,
23461 &mut v,
23462 enable_filter_intra,
23463 allow_screen_content_tools,
23464 base_q_idx,
23465 tx_select,
23466 reduced_tx_set, fctx,
23467 )?;
23468 if !has_rows32 {
23469 bump_edge32(2);
23470 }
23471 // lane-hgkf r1: at the frame edge only the first half of the strip is
23472 // coded (libaom `decode_partition` guards the second half with the same
23473 // test that made this partition non-square).
23474 if has_rows32 {
23475 decode_block_rect(
23476 &mut dec,
23477 &mut cdfs,
23478 &mut neighbours,
23479 (at32.0 + 1, at32.1),
23480 32,
23481 16,
23482 &mut y,
23483 &mut u,
23484 &mut v,
23485 enable_filter_intra,
23486 allow_screen_content_tools,
23487 base_q_idx,
23488 tx_select,
23489 reduced_tx_set, fctx,
23490 )?;
23491 }
23492 }
23493 PARTITION_VERT => {
23494 // lane-intradisp r1: mirror of PARTITION_HORZ
23495 // above with width/height swapped.
23496 decode_block_rect(
23497 &mut dec,
23498 &mut cdfs,
23499 &mut neighbours,
23500 at32,
23501 16,
23502 32,
23503 &mut y,
23504 &mut u,
23505 &mut v,
23506 en

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