forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1e4e107Tahinli2 months ago2830 commits

decode.rs23494 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 out
279}
280
281use crate::cdf;
282use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
283use crate::encode::{Picture, Reach};
284use crate::intra::predict;
285use crate::mc;
286use crate::msac::SymbolDecoder;
287use crate::mvstack::{
288 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
289 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
290 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
291 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
292 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
293};
294use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
295use crate::transform::{TxType, dequant_and_inverse_typed_wh};
296
297const PARTITION_NONE: usize = 0;
298const PARTITION_HORZ: usize = 1;
299const PARTITION_VERT: usize = 2;
300const PARTITION_SPLIT: usize = 3;
301const PARTITION_HORZ_A: usize = 4;
302const PARTITION_HORZ_B: usize = 5;
303const PARTITION_VERT_A: usize = 6;
304const PARTITION_VERT_B: usize = 7;
305const PARTITION_HORZ_4: usize = 8;
306const PARTITION_VERT_4: usize = 9;
307const SB_MI: u32 = 16;
308const BLOCK_MI: u32 = 8;
309
310// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
311// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
312// superblock's own top-left mi?", the loop-restoration read's unit span, the
313// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
314// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
315// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
316// inside a 128 superblock).
317thread_local! {
318 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
319 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
320 /// prints gigabytes otherwise). Unset = every frame, as before.
321 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
322 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
323}
324
325/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
326/// that frame's DECODE-order index.
327pub fn set_coeff_trace_frame(idx: usize) {
328 COEFF_TRACE_FRAME.with(|c| {
329 if c.get().is_none() {
330 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
331 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
332 // unset: keep tracing every frame, as before this rung existed
333 Err(_) => usize::MAX - 1,
334 };
335 c.set(Some(want));
336 }
337 });
338 COEFF_TRACE_CUR.with(|c| c.set(idx));
339 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
340 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
341 }
342}
343
344pub(crate) fn coeff_trace_on() -> bool {
345 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
346 return false;
347 }
348 match COEFF_TRACE_FRAME.with(|c| c.get()) {
349 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
350 // env var unset: trace every frame.
351 None => true,
352 Some(w) if w >= usize::MAX - 1 => true,
353 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
354 }
355}
356
357
358/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
359pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
360 fctx.sb128_flag.with(|c| c.set(v));
361 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
362}
363
364/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
365pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
366 fctx.lossless_flag.with(|c| c.set(v));
367}
368
369/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
370pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
371 fctx.lossless_flag.with(|c| c.get())
372}
373
374/// The transform side a block of `side` pixels codes: its own (capped at the
375/// caller's own largest) normally, 4 on a lossless frame, where libaom's
376/// `read_tx_size` returns TX_4X4 before it looks at anything else
377/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
378/// TX_4X4;`).
379pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
380 if lossless(fctx) { 4 } else { px }
381}
382
383/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
384/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
385/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
386/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
387/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
388pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
389 if lossless(fctx) {
390 bw <= 8 && bh <= 8
391 } else {
392 bw <= 32 && bh <= 32
393 }
394}
395
396fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
397 fctx.sb128_flag.with(|c| c.get())
398}
399
400/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
401pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
402 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
403}
404
405// How many real 128-level partition symbols this decoder has read, and how
406// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
407// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
408thread_local! {
409 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
410 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
411 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
412}
413
414/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
415/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
416/// 5.11.4), which this decoder used to read and throw away.
417#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
418pub(crate) fn part128_gathered_symbols() -> usize {
419 PART128_GATHERED_SYMBOLS.with(|c| c.get())
420}
421
422/// Current value of [`PART128_SYMBOLS`].
423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
424pub(crate) fn part128_symbols() -> usize {
425 PART128_SYMBOLS.with(|c| c.get())
426}
427
428/// Current value of [`PART128_SPLIT_HITS`].
429#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
430pub(crate) fn part128_split_hits() -> usize {
431 PART128_SPLIT_HITS.with(|c| c.get())
432}
433
434/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
435/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
436/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
437/// the 64/32 levels sum 6.
438pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
439 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
440 [32768 - split, 32768, 0]
441}
442
443/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
444pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
445pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
446
447// How many `use_filter_intra` symbols this decoder has read as `1`, across
448// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
449// tests read (before/after, not the absolute value) to prove a stream
450// actually exercised the filter-intra predictor rather than silently
451// skipping it.
452thread_local! {
453 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
454 const { std::cell::Cell::new(0) };
455}
456
457/// Current value of [`FILTER_INTRA_HITS`].
458#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
459pub(crate) fn filter_intra_hits() -> usize {
460 FILTER_INTRA_HITS.with(|c| c.get())
461}
462
463// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
464// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
465// `read_filter_intra_mode_info` call), which no gate exercised before this
466// round -- every inter gate recipe passed `--enable-filter-intra=0`.
467thread_local! {
468 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
469 const { std::cell::Cell::new(0) };
470}
471
472/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
473#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
474pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
475 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
476}
477
478// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
479// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
480// arms refused a nonzero luma delta before this round, and no inter gate
481// enabled `--enable-angle-delta` (aomenc's own default is 1).
482thread_local! {
483 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
484 const { std::cell::Cell::new(0) };
485 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
486 const { std::cell::Cell::new(0) };
487}
488
489/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
490#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
491pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
492 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
493}
494
495/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
496#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
497pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
498 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
499}
500
501// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
502// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
503// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
504// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
505thread_local! {
506 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
507 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
508 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
509}
510
511thread_local! {
512 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
513}
514
515/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
516/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
517#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
518pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
519 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
520}
521
522/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
523/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
525pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
526 (
527 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
528 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
529 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
530 )
531}
532
533// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
534// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
535// frame-level flag through the recursive block decode -- `0` (the default)
536// makes every call a true no-op, matching every existing gate stream's
537// `cdef_bits == 0` behaviour exactly.
538// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
539// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
540// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
541// blocks every non-8-bit stream from reaching a decode call, so this is `8`
542// on every path that runs today -- threading it now (rather than the literal
543// `8`) is stage 1 of widening past that refusal without re-deriving every
544// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
545// depth (this decoder's own internal choice, matches dav1d/libaom).
546/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
547/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
548pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
549 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
550}
551/// The current stream's bit depth, for callers (e.g. dequant) that need the
552/// raw value rather than the derived clamp bound.
553pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
554 fctx.bit_depth.with(std::cell::Cell::get)
555}
556/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
557/// [`crate::stream`]'s decode loop.
558pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
559 fctx.bit_depth.with(|c| c.set(bit_depth));
560}
561
562 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
563 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
564 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
565 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
566 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
567 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
568 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
569 /// superres arms). Set once per frame from [`crate::stream`]'s decode
570 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
571 /// so a later frame never inherits it.
572
573/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
574/// `denom` 8) for a frame that is not superres-scaled.
575pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
576 fctx.superres.with(|c| c.set((upscaled_width, denom)));
577}
578
579/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
580/// (libaom `av1_superres_scaled`), else `None`.
581pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
582 let (w, d) = fctx.superres.with(std::cell::Cell::get);
583 (w > 0 && d != 8).then_some((w, d))
584}
585// Whether this superblock's single CDEF unit (this decoder has no 128x128
586// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
587// read -- reset to `false` at the top of each superblock in the two tile
588// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
589// Number of superblock columns in the current tile's grid, so
590// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
591// [`CDEF_IDX_GRID`].
592// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
593// which of the header's `1 << cdef.bits` strength pairs applies to that
594// superblock's samples.
595// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
596// has read, across every call on the current thread -- the gate's proof that a
597// `cdef_bits > 0` stream actually reached the new reader rather than every
598// superblock coincidentally being all-skip.
599thread_local! {
600 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
601}
602
603// How many times a warp was suppressed for one PLANE because that plane's own
604// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
605// reconinter.c) -- the gate's proof that a stream really carries the shape,
606// since the square `side`/`chroma_side` can be 8 or more while the plane's
607// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
608thread_local! {
609 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
610}
611
612/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
613#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
614pub(crate) fn warp_plane_suppress_hits() -> usize {
615 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
616}
617
618/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
619/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
620/// block dimensions decide it -- never the square `side`/`chroma_side`, which
621/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
622/// bigger than the real block in one axis.
623pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
624 if w >= 8 && h >= 8 {
625 return true;
626 }
627 hit!(WARP_PLANE_SUPPRESS_HITS);
628 false
629}
630
631/// Current value of [`CDEF_IDX_HITS`].
632#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
633pub(crate) fn cdef_idx_hits() -> usize {
634 CDEF_IDX_HITS.with(|c| c.get())
635}
636
637// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
638// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
639// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
640// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
641// instead of from the coarse 16x16 cell.
642thread_local! {
643 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
644 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
645 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
646}
647
648/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
649#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
650pub(crate) fn intra_in_inter_txctx_hits() -> usize {
651 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
652}
653
654/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
655#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
656pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
657 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
658}
659
660/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
661#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
662pub(crate) fn edge_filter_mi_fix_hits() -> usize {
663 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
664}
665
666// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
667// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
668// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
669// true no-op, matching every existing gate stream's `delta_q_present == 0`
670// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
671// The running quantizer index (spec `CurrentQIndex`, libaom
672// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
673// top of every tile (spec `decode_tile`), carried across superblocks within
674// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
675// dequantization call sites instead of the frame-constant `base_q_idx`.
676// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
677// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
678// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
679// back at every dequantization call site keyed on which plane it is doing.
680// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
681// read, across every call on the current thread -- the gate's proof that a
682// `delta_q_present` stream actually reached the new reader.
683thread_local! {
684 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
685}
686
687/// Current value of [`DELTA_Q_HITS`].
688#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
689pub(crate) fn delta_q_hits() -> usize {
690 DELTA_Q_HITS.with(|c| c.get())
691}
692
693/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
694/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
695/// one), so it is always `0` here.
696fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
697 let d = fctx.quant_deltas.with(|c| c.get());
698 match plane_idx {
699 0 => (d.y_dc, 0),
700 1 => (d.u_dc, d.u_ac),
701 _ => (d.v_dc, d.v_ac),
702 }
703}
704
705/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
706/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
707/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
708/// A no-op when `delta_q_present` is unset, or when this block is not at the
709/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
710/// libaom, collapsed here to a position check since a partition tree's
711/// top-left leaf is the only block that can ever land there), or when that
712/// leaf both *is* the whole superblock and is `skip` (the one case libaom
713/// itself skips the read, state carrying over unchanged).
714fn 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) {
715 if !fctx.delta_q_present.with(|c| c.get()) {
716 return;
717 }
718 let sb_mi = sb_mi_cur(fctx) as usize;
719 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
720 return;
721 }
722 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
723 // computed against the sequence's own superblock size (lane-sb128b r1:
724 // it used to be hardcoded against 64 and disabled under `sb128`, which a
725 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
726 // wrong).
727 if is_whole_sb && skip {
728 return;
729 }
730 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
731 const DELTA_Q_SMALL: i32 = 3;
732 if abs >= DELTA_Q_SMALL {
733 let rem_bits = dec.literal(3) + 1;
734 let thr = (1i32 << rem_bits) + 1;
735 abs = dec.literal(rem_bits) as i32 + thr;
736 }
737 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
738 let reduced = if sign_negative { -abs } else { abs };
739 hit!(DELTA_Q_HITS);
740 let res = fctx.delta_q_res.with(|c| c.get());
741 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
742}
743
744// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
745// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
746// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
747// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
748// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
749// updates index 0 and every reader treats that as the value for all 4
750// indices (spec `read_delta_lf_params`'s own single-cdf branch).
751// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
752// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
753thread_local! {
754 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
755}
756
757/// Current value of [`DELTA_LF_HITS`].
758#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
759pub(crate) fn delta_lf_hits() -> usize {
760 DELTA_LF_HITS.with(|c| c.get())
761}
762
763/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
764/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
765/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
766/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
767/// read once into index 0 otherwise.
768fn 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) {
769 if !fctx.delta_lf_present.with(|c| c.get()) {
770 return;
771 }
772 let sb_mi = sb_mi_cur(fctx) as usize;
773 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
774 return;
775 }
776 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
777 // computed against the sequence's own superblock size (lane-sb128b r1:
778 // it used to be hardcoded against 64 and disabled under `sb128`, which a
779 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
780 // wrong).
781 if is_whole_sb && skip {
782 return;
783 }
784 let multi = fctx.delta_lf_multi.with(|c| c.get());
785 let res = fctx.delta_lf_res.with(|c| c.get());
786 let count = if multi { 4 } else { 1 };
787 let mut cur = fctx.current_delta_lf.with(|c| c.get());
788 for i in 0..count {
789 let mut abs = if multi {
790 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
791 } else {
792 dec.symbol(&mut cdfs.delta_lf) as i32
793 };
794 const DELTA_LF_SMALL: i32 = 3;
795 if abs >= DELTA_LF_SMALL {
796 let rem_bits = dec.literal(3) + 1;
797 let thr = (1i32 << rem_bits) + 1;
798 abs = dec.literal(rem_bits) as i32 + thr;
799 }
800 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
801 let reduced = if sign_negative { -abs } else { abs };
802 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
803 hit!(DELTA_LF_HITS);
804 }
805 fctx.current_delta_lf.with(|c| c.set(cur));
806}
807
808/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
809/// after `skip` is known at every block-decode call site. A no-op at
810/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
811/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
812/// `allow_intrabc`, so neither needs a separate check here. Reads once per
813/// superblock, at the first non-skip block.
814fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
815 let bits = fctx.cdef_bits.with(|c| c.get());
816 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
817 return;
818 }
819 let idx = dec.literal(u32::from(bits)) as u8;
820 fctx.cdef_transmitted.with(|c| c.set(true));
821 hit!(CDEF_IDX_HITS);
822 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
823 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
824 if sb_cols > 0 {
825 fctx.cdef_idx_grid.with(|g| {
826 let mut g = g.borrow_mut();
827 let i = sb_r * sb_cols + sb_c;
828 if i < g.len() {
829 g[i] = idx;
830 }
831 });
832 }
833}
834
835// ---------------------------------------------------------------------------
836// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
837// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
838// the two consumers a real stream exercises: the per-segment quantizer index
839// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
840// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
841// `read_intra_segment_id`/`read_inter_segment_id` and
842// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
843// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
844// is what the oracle every gate here compares against actually does.
845thread_local! {
846 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
847 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
848 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
849 /// this frame has no primary reference (spec `load_previous_segment_ids`).
850 /// `(mi_rows, mi_cols)` for both maps above.
851 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
852 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
853 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
854 /// The block currently being decoded -- read back by [`block_q_idx`].
855 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
856 /// How many real `segment_id` symbols were read, and the set of segment
857 /// ids any block ended up with -- the gate's proof the feature fired.
858 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
859 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
860 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
861 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
862 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
863 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
864 /// nothing about the segments carrying distinct quantizers.
865 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
866 /// How many `seg_id_predicted` symbols were read (temporal update).
867 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
868}
869
870/// Installs this frame's segmentation parameters and allocates its map, with
871/// `prev` the primary reference frame's saved map (spec
872/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
873/// slot). Called once per frame, whether or not segmentation is enabled.
874pub(crate) fn set_segmentation(
875 seg: SegmentationParams,
876 mi_rows: usize,
877 mi_cols: usize,
878 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
879) {
880 if crate::envflags::env_flag!("EC_HDR") {
881 eprintln!(
882 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
883 seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data
884 );
885 }
886 fctx.seg.with(|s| *s.borrow_mut() = seg);
887 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
888 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
889 fctx.prev_seg_ids.with(|m| {
890 let mut m = m.borrow_mut();
891 m.clear();
892 if let Some(p) = prev {
893 if p.len() == mi_rows * mi_cols {
894 m.extend_from_slice(p);
895 }
896 }
897 });
898 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
899 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
900 fctx.cur_segment_id.with(|c| c.set(0));
901}
902
903/// This frame's decoded segment map, to be stored into whichever reference
904/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
905pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
906 fctx.seg_ids.with(|m| m.borrow().clone())
907}
908
909/// How many `segment_id` symbols have been read (never reset per frame).
910#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
911pub(crate) fn segment_id_hits() -> usize {
912 SEG_ID_HITS.with(|c| c.get())
913}
914
915/// How many distinct segment ids any decoded block has carried.
916#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
917pub(crate) fn segment_ids_seen() -> usize {
918 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
919}
920
921/// The lowest and highest quantizer index any decoded block was dequantized
922/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
923#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
924pub(crate) fn block_q_span() -> (i32, i32) {
925 BLOCK_Q_SPAN.with(|c| c.get())
926}
927
928/// How many `seg_id_predicted` symbols have been read (temporal update).
929#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
930pub(crate) fn segment_pred_hits() -> usize {
931 SEG_PRED_HITS.with(|c| c.get())
932}
933
934/// Resets the segmentation hit counters (gate setup).
935#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
936pub(crate) fn reset_segment_hits() {
937 SEG_ID_HITS.with(|c| c.set(0));
938 SEG_IDS_SEEN.with(|c| c.set(0));
939 SEG_PRED_HITS.with(|c| c.set(0));
940 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
941}
942
943/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
944/// being decoded, with its `FeatureData` value.
945fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
946 fctx.seg.with(|s| {
947 let s = s.borrow();
948 s.feature_active(segment_id, feature)
949 .then(|| i32::from(s.feature_data[segment_id][feature]))
950 })
951}
952
953/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
954/// `av1_get_qindex`) for the block currently being decoded: the running
955/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
956/// Every dequant call site reads the block's quantizer through here.
957fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
958 let base = fctx.current_q_idx.with(|c| c.get());
959 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
960 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
961 Some(data) => (base + data).clamp(0, 255),
962 None => base,
963 };
964 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
965 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
966 // already proven equal is a segment-id defect, not a quantizer one.
967 if crate::envflags::env_flag!("EC_DQCOEFF") {
968 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
969 }
970 hit_do!(BLOCK_Q_SPAN.with(|c| {
971 let (lo, hi) = c.get();
972 c.set((lo.min(q), hi.max(q)));
973 }););
974 q
975}
976
977/// The segment id recorded for one mi cell of the current frame's map.
978fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
979 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
980 if mi_r >= mi_rows || mi_c >= mi_cols {
981 return 0;
982 }
983 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
984}
985
986/// `set_segment_id`: stamps `id` over every mi cell this block covers.
987fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
988 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
989 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
990 fctx.seg_ids.with(|m| {
991 let mut m = m.borrow_mut();
992 for y in 0..y_mis {
993 for x in 0..x_mis {
994 m[(mi_r + y) * mi_cols + mi_c + x] = id;
995 }
996 }
997 });
998 fctx.cur_segment_id.with(|c| c.set(id));
999 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1000}
1001
1002/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1003/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1004/// block's own mi footprint. `0` when there is no previous map.
1005fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1006 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1007 fctx.prev_seg_ids.with(|m| {
1008 let m = m.borrow();
1009 if m.is_empty() {
1010 return 0;
1011 }
1012 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1013 let mut id = u8::MAX;
1014 for y in 0..y_mis {
1015 for x in 0..x_mis {
1016 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1017 }
1018 }
1019 if id == u8::MAX { 0 } else { id }
1020 })
1021}
1022
1023/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1024fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1025 if reference == 0 {
1026 return diff;
1027 }
1028 if reference >= max - 1 {
1029 return max - diff - 1;
1030 }
1031 let half = if 2 * reference < max {
1032 diff <= 2 * reference
1033 } else {
1034 diff <= 2 * (max - reference - 1)
1035 };
1036 if half {
1037 return if diff & 1 != 0 {
1038 reference + ((diff + 1) >> 1)
1039 } else {
1040 reference - (diff >> 1)
1041 };
1042 }
1043 if 2 * reference < max { diff } else { max - (diff + 1) }
1044}
1045
1046/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1047/// frame's already-decoded above/left/above-left neighbours.
1048fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1049 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1050 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1051 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1052 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1053 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1054 let ctx = match prev_ul {
1055 None => 0,
1056 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1057 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1058 Some(_) => 0,
1059 };
1060 let pred = match (prev_u, prev_l) {
1061 (None, l) => l.unwrap_or(0),
1062 (Some(u), None) => u,
1063 (Some(u), Some(l)) => {
1064 if prev_ul == Some(u) {
1065 u
1066 } else {
1067 l
1068 }
1069 }
1070 };
1071 (pred, ctx)
1072}
1073
1074/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1075/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1076/// that prediction. Does NOT write the map -- callers do.
1077fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
1078 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1079 if skip {
1080 return pred as u8;
1081 }
1082 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1083 hit!(SEG_ID_HITS);
1084 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1085 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1086 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1087 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1088 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1089 eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0);
1090 }
1091 id as u8
1092}
1093
1094/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1095/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1096/// caller decides which by passing `pre_skip`).
1097fn intra_segment_id(
1098 dec: &mut SymbolDecoder,
1099 cdfs: &mut Cdfs,
1100 mi_r: usize,
1101 mi_c: usize,
1102 w_mi: usize,
1103 h_mi: usize,
1104 skip: bool, fctx: &crate::decode::FrameCtx,
1105) {
1106 if !fctx.seg.with(|s| s.borrow().enabled) {
1107 return;
1108 }
1109 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1110 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1111}
1112
1113/// Whether this frame's intra blocks read their `segment_id` before `skip`
1114/// (`SegIdPreSkip`); `false` also when segmentation is off.
1115fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1116 fctx.seg.with(|s| {
1117 let s = s.borrow();
1118 s.enabled && s.seg_id_pre_skip
1119 })
1120}
1121
1122/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1123/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1124/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1125fn inter_segment_id(
1126 dec: &mut SymbolDecoder,
1127 cdfs: &mut Cdfs,
1128 mi_r: usize,
1129 mi_c: usize,
1130 w_mi: usize,
1131 h_mi: usize,
1132 skip: bool,
1133 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1134) {
1135 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1136 let s = s.borrow();
1137 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1138 });
1139 if !enabled {
1140 return;
1141 }
1142 if !update_map {
1143 // The map is inherited wholesale from the previous frame.
1144 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1145 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1146 return;
1147 }
1148 if pre_skip && !pre_skip_frame {
1149 return;
1150 }
1151 if !pre_skip && skip {
1152 // libaom: a skipped block never codes `seg_id_predicted`, and its
1153 // segment id is the spatial prediction.
1154 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1155 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1156 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1157 return;
1158 }
1159 let id = if temporal_update {
1160 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1161 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1162 hit!(SEG_PRED_HITS);
1163 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1164 if predicted {
1165 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1166 } else {
1167 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1168 }
1169 } else {
1170 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1171 };
1172 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1173}
1174
1175/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1176fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1177 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1178 // so contribute 0) outside the tile -- the availability check here is
1179 // what keeps a previous tile's stamps out of this tile's context.
1180 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1181 let above = if mi_r > row0 {
1182 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1183 } else {
1184 0
1185 };
1186 let left = if mi_c > col0 {
1187 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1188 } else {
1189 0
1190 };
1191 usize::from(above + left)
1192}
1193
1194/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1195fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1196 fctx.above_seg_pred.with(|m| {
1197 let mut m = m.borrow_mut();
1198 for i in 0..w_mi {
1199 if let Some(cell) = m.get_mut(mi_c + i) {
1200 *cell = value;
1201 }
1202 }
1203 });
1204 fctx.left_seg_pred.with(|m| {
1205 let mut m = m.borrow_mut();
1206 for i in 0..h_mi {
1207 if let Some(cell) = m.get_mut(mi_r + i) {
1208 *cell = value;
1209 }
1210 }
1211 });
1212}
1213
1214// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1215// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1216// counter, proving a stream actually put a directional block next to a
1217// smooth-predicted neighbour rather than every block reading the (previously
1218// hardcoded `false`) edge-filter strength bucket unchanged.
1219thread_local! {
1220 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1221 const { std::cell::Cell::new(0) };
1222}
1223
1224/// Current value of [`SMOOTH_LUMA_HITS`].
1225#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1226pub(crate) fn smooth_luma_hits() -> usize {
1227 SMOOTH_LUMA_HITS.with(|c| c.get())
1228}
1229
1230thread_local! {
1231 /// lane-band46 r1: how many split-transform units answered their intra
1232 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1233 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1234 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1235 /// transform unit whose above-right / below-left reference samples would
1236 /// be wrong without that fix.
1237 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1238 const { std::cell::Cell::new(0) };
1239}
1240
1241/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1242#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1243pub(crate) fn split_tu_reach_fix_hits() -> usize {
1244 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1245}
1246
1247/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1248/// answer differs from the standalone-block answer the call sites used before
1249/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1250/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1251/// block's top-left `(px, py)`.
1252#[allow(clippy::too_many_arguments)]
1253fn tu_reach(
1254 bw: usize,
1255 bh: usize,
1256 col_off: usize,
1257 row_off: usize,
1258 tx: usize,
1259 block: Reach,
1260 px: usize,
1261 py: usize,
1262 width: usize,
1263 height: usize, fctx: &crate::decode::FrameCtx,
1264) -> Reach {
1265 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1266 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1267 if fixed != standalone {
1268 hit!(SPLIT_TU_REACH_FIX_HITS);
1269 }
1270 fixed
1271}
1272
1273// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1274// across every call on the current thread -- lane-chroma r3's own before/after
1275// counter, proving a stream actually exercised chroma's smooth/paeth
1276// predictor (the previously-refused round-2 gap) rather than every block
1277// landing on DC/CFL/directional.
1278thread_local! {
1279 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1280 const { std::cell::Cell::new(0) };
1281}
1282
1283/// Current value of [`SMOOTH_UV_HITS`].
1284#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1285pub(crate) fn smooth_uv_hits() -> usize {
1286 SMOOTH_UV_HITS.with(|c| c.get())
1287}
1288
1289// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1290// full superblock walk over, across every call on the current thread --
1291// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1292// multi-tile stream must prove more than one tile actually fired, not just
1293// that the stream carried tile_info.cols > 1.
1294thread_local! {
1295 static TILE_HITS: std::cell::Cell<usize> =
1296 const { std::cell::Cell::new(0) };
1297}
1298/// Current value of [`TILE_HITS`].
1299#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1300pub(crate) fn tile_hits() -> usize {
1301 TILE_HITS.with(|c| c.get())
1302}
1303
1304// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1305// selected for filtering, across every call on the current thread -- the same
1306// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1307// exercised `apply_deblock` rather than every edge landing on level 0.
1308thread_local! {
1309 static DEBLOCK_HITS: std::cell::Cell<usize> =
1310 const { std::cell::Cell::new(0) };
1311}
1312/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1313/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1314/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1315static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1316 std::sync::atomic::AtomicUsize::new(0);
1317
1318/// Current value of [`DEBLOCK_HITS`].
1319#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1320pub(crate) fn deblock_hits() -> usize {
1321 DEBLOCK_HITS.with(|c| c.get())
1322}
1323
1324// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1325// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1326// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1327// stream built with `--enable-onesided-comp=1` really exercised the
1328// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1329thread_local! {
1330 static UNI_COMP_HITS: std::cell::Cell<usize> =
1331 const { std::cell::Cell::new(0) };
1332}
1333
1334/// Current value of [`UNI_COMP_HITS`].
1335#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1336pub(crate) fn uni_comp_hits() -> usize {
1337 UNI_COMP_HITS.with(|c| c.get())
1338}
1339
1340// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1341// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1342// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1343// blend and not only the wedge arm.
1344thread_local! {
1345 static DIFFWTD_HITS: std::cell::Cell<usize> =
1346 const { std::cell::Cell::new(0) };
1347}
1348
1349/// Current value of [`DIFFWTD_HITS`].
1350#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1351pub(crate) fn diffwtd_hits() -> usize {
1352 DIFFWTD_HITS.with(|c| c.get())
1353}
1354
1355// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1356// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1357// this decoder's square inter path reaches), so no `compound_type` symbol is
1358// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1359// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1360thread_local! {
1361 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1362 const { std::cell::Cell::new(0) };
1363}
1364
1365/// Current value of [`DIFFWTD_INFERRED_HITS`].
1366#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1367pub(crate) fn diffwtd_inferred_hits() -> usize {
1368 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1369}
1370
1371// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1372// with `show_frame == 0`, output later by a `show_existing_frame` header
1373// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1374// `stream::decode_stream`, which is where the frame header is consumed; the
1375// gate's proof that the on-value really reached the bitstream rather than
1376// being dropped by the rate control.
1377thread_local! {
1378 static FWD_KF_HITS: std::cell::Cell<usize> =
1379 const { std::cell::Cell::new(0) };
1380}
1381
1382/// Current value of [`FWD_KF_HITS`].
1383#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1384pub(crate) fn fwd_kf_hits() -> usize {
1385 FWD_KF_HITS.with(|c| c.get())
1386}
1387
1388/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1389pub(crate) fn note_fwd_kf() {
1390 hit!(FWD_KF_HITS);
1391}
1392
1393// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1394// the block's own side, across every call on the current thread -- the same
1395// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1396// actually exercised a *split* transform under `TxMode::Select` rather than
1397// every block coincidentally resolving `depth=0` (indistinguishable from
1398// `TxMode::Largest` pixel-wise).
1399thread_local! {
1400 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1401 const { std::cell::Cell::new(0) };
1402}
1403
1404// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1405// transform smaller than their own side (`tx_depth != 0`) while coding a
1406// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1407// only exercises with aomenc's tx-size search left ON (its default), which
1408// every older recipe in this file pins off. Counted at the block, so a stream
1409// where RD happened to give every split-transform block a DC chroma mode
1410// reads as zero rather than silently passing for free.
1411thread_local! {
1412 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1413 const { std::cell::Cell::new(0) };
1414}
1415
1416/// Current value of [`SQ_CHROMA_TX_HITS`].
1417#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1418pub(crate) fn sq_chroma_tx_hits() -> usize {
1419 SQ_CHROMA_TX_HITS.with(|c| c.get())
1420}
1421
1422/// Current value of [`TX_DEPTH_HITS`].
1423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1424pub(crate) fn tx_depth_hits() -> usize {
1425 TX_DEPTH_HITS.with(|c| c.get())
1426}
1427
1428// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1429// read, and how many of those actually took the split, on the current thread
1430// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1431// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1432// coincidentally coding one whole-block transform.
1433thread_local! {
1434 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1435 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1436 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1437 // strips coded one whole-block rect transform unit, and how many split
1438 // their rect max transform into square sub-transforms.
1439 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1440 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1441 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1442 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1443 // truncated low-32 corner.
1444 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1445 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1446 // inter strip, `[32x8, 8x32]`.
1447 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1448 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1449 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1450 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1451 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1452 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1453 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1454 // frame -- 16x8 and 8x16 inter leaves.
1455 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1456 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1457 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1458 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1459 // `decode_inter_block` already carries forty parameters and both are
1460 // frame-constant.
1461 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1462 // frame-constant like the two above and stashed the same way -- an intra
1463 // block inside an inter frame reads `use_filter_intra` under it.
1464}
1465
1466/// Current value of [`TXFM_SPLIT_READS`].
1467#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1468pub(crate) fn txfm_split_reads() -> usize {
1469 TXFM_SPLIT_READS.with(|c| c.get())
1470}
1471
1472/// Current value of [`TXFM_SPLIT_HITS`].
1473#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1474pub(crate) fn txfm_split_hits() -> usize {
1475 TXFM_SPLIT_HITS.with(|c| c.get())
1476}
1477
1478/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1479#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1480pub(crate) fn inter_leaf16_horz_hits() -> usize {
1481 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1482}
1483
1484/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1485#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1486pub(crate) fn inter_leaf16_vert_hits() -> usize {
1487 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1488}
1489
1490/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1491pub(crate) fn rect_inter_tu_hits() -> usize {
1492 RECT_INTER_TU_HITS.with(|c| c.get())
1493}
1494
1495/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1496pub(crate) fn rect_inter_txsplit_hits() -> usize {
1497 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1498}
1499
1500/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1501pub(crate) fn rect64_inter_tu_hits() -> usize {
1502 RECT64_INTER_TU_HITS.with(|c| c.get())
1503}
1504
1505/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1506/// whole-block luma units of a 32x32-level 1:4 inter strip.
1507pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1508 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1509}
1510
1511/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1512/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1513pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1514 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1515}
1516
1517/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1518/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1519pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1520 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1521}
1522
1523/// Records one rectangular var-tx leaf.
1524fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1525 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1526 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1527 }
1528 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1529 cell.with(|c| {
1530 let mut h = c.get();
1531 h[usize::from(th > tw)] += 1;
1532 c.set(h);
1533 });
1534}
1535
1536/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1537/// [`ENABLE_FILTER_INTRA_INTER`].
1538pub(crate) fn set_inter_tx_mode(
1539 tx_select: bool,
1540 reduced_tx_set: bool,
1541 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1542) {
1543 fctx.tx_select_inter.with(|c| c.set(tx_select));
1544 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1545 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1546}
1547
1548// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1549// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1550// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1551// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1552// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1553// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1554// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1555// path above).
1556thread_local! {
1557 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1558 const { std::cell::Cell::new(0) };
1559}
1560
1561/// Current value of [`VERT_B_INTRA_HITS`].
1562#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1563pub(crate) fn vert_b_intra_hits() -> usize {
1564 VERT_B_INTRA_HITS.with(|c| c.get())
1565}
1566
1567// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1568// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1569// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1570// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1571// every arm separately so a run where aomenc's RD only picked one cannot
1572// pass as proof of four.
1573thread_local! {
1574 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1575}
1576
1577// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1578thread_local! {
1579 /// 4x4 transform units decoded inside an 8x8 square of a
1580 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1581 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1582 /// a real `--enable-tx-size-search=1` stream reaches it.
1583 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1584}
1585
1586#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1587pub(crate) fn vert_ab_tx4_hits() -> usize {
1588 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1589}
1590
1591#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1592pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1593 AB16_HITS.with(std::cell::Cell::get)
1594}
1595
1596fn bump_ab16(arm: usize) {
1597 hit_do! {
1598 AB16_HITS.with(|c| {
1599 let mut v = c.get();
1600 v[arm] += 1;
1601 c.set(v);
1602 });
1603 }
1604}
1605
1606// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1607// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1608// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1609// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1610// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1611// superblock's z-order recursion, not raster mi position).
1612thread_local! {
1613 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1614 const { std::cell::Cell::new(0) };
1615}
1616
1617/// Current value of [`HORZ_VERT_INTRA_HITS`].
1618#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1619pub(crate) fn horz_vert_intra_hits() -> usize {
1620 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1621}
1622
1623// How many blocks were decoded as a frame-edge rect strip -- the single
1624// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1625// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1626// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1627// paths share the counter.
1628thread_local! {
1629 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1630 const { std::cell::Cell::new(0) };
1631}
1632
1633/// Current value of [`EDGE_RECT_STRIP_HITS`].
1634#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1635pub(crate) fn edge_rect_strip_hits() -> usize {
1636 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1637}
1638
1639// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1640// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1641// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1642// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1643// are height mod 16 == 8, so every inter frame crosses these nodes.
1644thread_local! {
1645 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1646 const { std::cell::Cell::new([0; 6]) };
1647}
1648
1649/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1650pub(crate) fn bump_inter_edge_strip(idx: usize) {
1651 hit_do! {
1652 INTER_EDGE_STRIP_HITS.with(|c| {
1653 let mut v = c.get();
1654 v[idx] += 1;
1655 c.set(v);
1656 });
1657 }
1658}
1659
1660// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1661// forced split -- libaom `decode_partition` (decodeframe.c):
1662// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1663// straddle case that reads NO symbol at all. Indexed by level:
1664// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1665thread_local! {
1666 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1667 const { std::cell::Cell::new([0; 4]) };
1668}
1669
1670fn bump_edge_both_cut(level: usize) {
1671 hit_do! {
1672 EDGE_BOTH_CUT_HITS.with(|c| {
1673 let mut v = c.get();
1674 v[level] += 1;
1675 c.set(v);
1676 });
1677 }
1678}
1679
1680/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1681pub fn inter_edge_strip_hits() -> [usize; 6] {
1682 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1683}
1684
1685/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1686/// into the next one (class `counter-from-refused-stream`).
1687pub fn reset_inter_edge_strip_hits() {
1688 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1689}
1690
1691/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1692#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1693pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1694 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1695}
1696
1697/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1698#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1699pub(crate) fn reset_edge_both_cut_hits() {
1700 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1701}
1702
1703// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1704// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1705// the case every rect path here refused by name before, and the first
1706// refusal the user's ReelB extract (600s in) stops at.
1707thread_local! {
1708 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1709 const { std::cell::Cell::new(0) };
1710}
1711
1712/// Current value of [`RECT_SPLIT_TX_HITS`].
1713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1714pub(crate) fn rect_split_tx_hits() -> usize {
1715 RECT_SPLIT_TX_HITS.with(|c| c.get())
1716}
1717
1718// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1719// side 64) AND split past the first depth, i.e. tiled more than one unit in
1720// each axis -- the only shape with a transform unit that has neighbours on
1721// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1722// no gate fired before lane-rectsplit r2 (the shared counter above also
1723// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1724thread_local! {
1725 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1726 const { std::cell::Cell::new(0) };
1727}
1728
1729/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1731pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1732 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1733}
1734
1735// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1736// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1737// chroma half takes that had no coefficient tables before (index order:
1738// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1739// proves the pair it happens to hit cannot catch a transposed scan/context
1740// table (class scan-weights-cross-axis).
1741thread_local! {
1742 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1743 const { std::cell::Cell::new([0; 4]) };
1744}
1745
1746/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1747#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1748pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1749 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1750}
1751
1752// How many HORZ/VERT intra strips actually predicted with filter intra
1753// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1754// ("this decoder predicts square-only") until `predict_filter_intra` took
1755// `bw`x`bh`.
1756thread_local! {
1757 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1758 const { std::cell::Cell::new(0) };
1759}
1760
1761/// Current value of [`FILTER_INTRA_RECT_HITS`].
1762#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1763pub(crate) fn filter_intra_rect_hits() -> usize {
1764 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1765}
1766
1767// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1768// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1769// was never read at all before that round, so a gate needs to prove the flag
1770// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1771// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1772// carry different probabilities (18101 vs 20229), so a transposed pair is
1773// only caught by a gate that sees the flag fire on BOTH shapes (class
1774// scan-weights-cross-axis).
1775thread_local! {
1776 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1777 const { std::cell::Cell::new(0) };
1778 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1779 const { std::cell::Cell::new(0) };
1780}
1781
1782/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1783#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1784pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1785 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1786}
1787
1788/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1789#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1790pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1791 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1792}
1793
1794// How many rectangular transform units actually coded coefficients through
1795// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1796// exercised the rect coefficient reader at all rather than passing on
1797// all-skip blocks.
1798thread_local! {
1799 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1800 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1801}
1802
1803/// Current value of [`RECT_COEFF_TU_HITS`].
1804#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1805pub(crate) fn rect_coeff_tu_hits() -> usize {
1806 RECT_COEFF_TU_HITS.with(|c| c.get())
1807}
1808
1809/// Rectangular transform units whose resolved `tx_type` is a 1D class
1810/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1811/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1812/// for the square reader's own 1D types.
1813#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1814pub(crate) fn rect_class1_hits() -> usize {
1815 RECT_CLASS1_HITS.with(|c| c.get())
1816}
1817
1818// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1819// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1820// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1821// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1822// prove nothing about the new shapes.
1823thread_local! {
1824 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1825 const { std::cell::Cell::new(0) };
1826}
1827
1828/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1829#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1830pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1831 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1832}
1833
1834// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1835// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1836// counter would be satisfied by a 16x8 strip and prove nothing here.
1837thread_local! {
1838 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1839 const { std::cell::Cell::new(0) };
1840}
1841
1842/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1844pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1845 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1846}
1847
1848// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1849// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1850// call on the current thread -- the same before/after counter pattern as
1851// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1852// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1853// landing on `DCT_DCT`.
1854thread_local! {
1855 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1856 const { std::cell::Cell::new(0) };
1857}
1858
1859// How many `uv_mode` reads resolved to a directional chroma mode (neither
1860// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1861// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1862// actually exercised chroma's own directional predictor.
1863thread_local! {
1864 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1865 const { std::cell::Cell::new(0) };
1866}
1867
1868/// Current value of [`DIRECTIONAL_UV_HITS`].
1869#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1870pub(crate) fn directional_uv_hits() -> usize {
1871 DIRECTIONAL_UV_HITS.with(|c| c.get())
1872}
1873
1874// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1875// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1876// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1877// proving a stream actually exercised a nonzero angle delta.
1878thread_local! {
1879 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1880 const { std::cell::Cell::new(0) };
1881}
1882
1883// How many [`read_single_ref`] reads resolved to a reference other than
1884// `LAST_FRAME`, across every call on the current thread -- the same before/after
1885// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1886// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1887// only other supported one so far) rather than every block coincidentally
1888// resolving `LAST_FRAME`.
1889thread_local! {
1890 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1891 const { std::cell::Cell::new(0) };
1892}
1893
1894/// Current value of [`NON_LAST_REF_HITS`].
1895#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1896pub(crate) fn non_last_ref_hits() -> usize {
1897 NON_LAST_REF_HITS.with(|c| c.get())
1898}
1899
1900// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1901// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1902// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1903// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1904// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1905// `GOLDEN_FRAME` draw it did not ask for.
1906thread_local! {
1907 static LAST2_HITS: std::cell::Cell<usize> =
1908 const { std::cell::Cell::new(0) };
1909}
1910thread_local! {
1911 static LAST3_HITS: std::cell::Cell<usize> =
1912 const { std::cell::Cell::new(0) };
1913}
1914thread_local! {
1915 static GOLDEN_HITS: std::cell::Cell<usize> =
1916 const { std::cell::Cell::new(0) };
1917}
1918thread_local! {
1919 static BWDREF_HITS: std::cell::Cell<usize> =
1920 const { std::cell::Cell::new(0) };
1921}
1922thread_local! {
1923 static ALTREF2_HITS: std::cell::Cell<usize> =
1924 const { std::cell::Cell::new(0) };
1925}
1926thread_local! {
1927 static ALTREF_HITS: std::cell::Cell<usize> =
1928 const { std::cell::Cell::new(0) };
1929}
1930
1931// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1932// -- proves a `reference_select` stream actually reached a block that picked
1933// compound, not just that the header bit was set. Every such block is
1934// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1935// so this only ever counts attempted reads, never a completed decode.
1936thread_local! {
1937 static COMP_MODE_HITS: std::cell::Cell<usize> =
1938 const { std::cell::Cell::new(0) };
1939}
1940
1941/// Current value of [`COMP_MODE_HITS`].
1942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1943pub(crate) fn comp_mode_hits() -> usize {
1944 COMP_MODE_HITS.with(|c| c.get())
1945}
1946
1947// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1948// use for, across every call on the current thread -- the same before/after
1949// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1950// exercised palette reconstruction rather than only reading and refusing the
1951// `palette_y_mode` symbol.
1952thread_local! {
1953 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1954}
1955
1956/// Current value of [`PALETTE_HITS`].
1957#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1958pub(crate) fn palette_hits() -> usize {
1959 PALETTE_HITS.with(|c| c.get())
1960}
1961
1962// lane-tiles r12: of those, how many sat at their own TILE's left column --
1963// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1964// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1965// palette gate that never hits one proves nothing about the tile guard.
1966thread_local! {
1967 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1968}
1969
1970/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1971#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1972pub(crate) fn palette_tile_left_hits() -> usize {
1973 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1974}
1975
1976// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1977// palette use -- proves a stream actually reconstructed UV palette pixels,
1978// not just read and refused the `palette_uv_mode` symbol.
1979thread_local! {
1980 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1981}
1982
1983/// Current value of [`PALETTE_UV_HITS`].
1984#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1985pub(crate) fn palette_uv_hits() -> usize {
1986 PALETTE_UV_HITS.with(|c| c.get())
1987}
1988
1989// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1990// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1991// (not just the square path's) actually fired.
1992thread_local! {
1993 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1994}
1995
1996/// Current value of [`PALETTE_RECT_HITS`].
1997#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1998pub(crate) fn palette_rect_hits() -> usize {
1999 PALETTE_RECT_HITS.with(|c| c.get())
2000}
2001
2002// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2003// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2004// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2005// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2006// RD, almost always refused-on-use because the block doesn't end up USING a
2007// palette -- see r5's report). This is the site the removed refusal
2008// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2009// fired here whether or not the block picked a palette, so this is the
2010// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2011// never observes.
2012thread_local! {
2013 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2014}
2015
2016/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2017#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2018pub(crate) fn rect_screen_content_hits() -> usize {
2019 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2020}
2021
2022// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2023// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2024// windowing actually ran, not just that the whole-block path stayed exact.
2025// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2026// first actually incremented in r7, when the refusal it guarded was lifted.
2027thread_local! {
2028 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2029}
2030
2031thread_local! {
2032 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2033 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2034 /// (16x8/8x16), the two shapes the lifted refusals named.
2035 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2036}
2037
2038/// Current value of [`RECT4_PALETTE_HITS`].
2039#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2040pub(crate) fn rect4_palette_hits() -> usize {
2041 RECT4_PALETTE_HITS.with(|c| c.get())
2042}
2043
2044/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2045#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2046pub(crate) fn palette_split_tx_hits() -> usize {
2047 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2048}
2049
2050thread_local! {
2051 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2052 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2053 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2054 /// `--min-partition-size=8` puts them on this leaf path.
2055 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2056}
2057
2058/// Current value of [`PALETTE_LEAF8_HITS`].
2059#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2060pub(crate) fn palette_leaf8_hits() -> usize {
2061 PALETTE_LEAF8_HITS.with(|c| c.get())
2062}
2063
2064/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2065#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2066pub(crate) fn reset_palette_leaf8_hits() {
2067 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2068}
2069
2070thread_local! {
2071 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2072 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2073 /// block that also carries a real, corner-cropped luma transform.
2074 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2075}
2076
2077/// Current value of [`PALETTE_SB_STRIP_HITS`].
2078#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2079pub(crate) fn palette_sb_strip_hits() -> usize {
2080 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2081}
2082
2083/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2084#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2085pub(crate) fn reset_palette_sb_strip_hits() {
2086 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2087}
2088
2089// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2090// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2091// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2092// capability rather than the key frame's, which every screen stream also
2093// carries.
2094thread_local! {
2095 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2096 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2097}
2098
2099// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2100// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2101// shared counter too, so only this one proves a gate really reached the leaf
2102// where the refusal used to sit.
2103thread_local! {
2104 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2105 const { std::cell::Cell::new((0, 0)) };
2106}
2107
2108/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2109pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2110 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2111}
2112
2113/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2114pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2115 (
2116 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2117 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2118 )
2119}
2120
2121// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2122// and which are therefore predicted one transform unit at a time (a skipped
2123// block codes no coefficients, so nothing else in the stream witnesses this
2124// path -- only the pixels do).
2125thread_local! {
2126 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2127}
2128
2129/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2130pub fn skip_split_tx_hits() -> usize {
2131 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2132}
2133
2134/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2135pub fn reset_skip_split_tx_hits() {
2136 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2137}
2138
2139// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2140// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2141// the gate's proof that the lifted path actually ran, per size.
2142thread_local! {
2143 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2144 const { std::cell::Cell::new([0; 4]) };
2145}
2146
2147/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2148#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2149pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2150 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2151}
2152
2153 /// A just-decoded palette-Y block's own predicted pixels
2154 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2155 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2156 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2157 /// per-block override through `read_plane`'s two dozen call sites is the
2158 /// alternative this avoids). Always empty again once that call consumes
2159 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2160 /// sees stale state.
2161
2162
2163/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2164/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2165/// site whose reconstruct never runs would be picked up by the NEXT block's
2166/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2167/// lane-lossless2: one transform unit's window on a block-sized palette
2168/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2169/// handing it the whole-block buffer makes every unit reconstruct the block's
2170/// top-left corner (the luma split-transform paths already window; the chroma
2171/// ones did not, which is invisible until a lossless frame codes a palette
2172/// block as 4x4 chroma units).
2173fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> {
2174 (0..h)
2175 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2176 .collect()
2177}
2178
2179/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2180#[track_caller]
2181fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2182 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2183 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2184 eprintln!(
2185 "PALSET len={} stale={stale} at {}",
2186 buf.len(),
2187 std::panic::Location::caller()
2188 );
2189 }
2190 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2191}
2192
2193#[track_caller]
2194fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2195 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2196 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2197 eprintln!(
2198 "PALTAKE len={:?} at {}",
2199 got.as_ref().map(Vec::len),
2200 std::panic::Location::caller()
2201 );
2202 }
2203 got
2204}
2205
2206/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2207/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2208/// pixels, because at parse time this block's own luma is still queued.
2209#[derive(Clone, Copy, Debug)]
2210pub(crate) struct CflSrc {
2211 px: usize,
2212 py: usize,
2213 bw: usize,
2214 bh: usize,
2215 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2216 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2217 rect: bool,
2218}
2219
2220fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2221 CflSrc { px, py, bw: side, bh: side, rect: false }
2222}
2223
2224fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2225 CflSrc { px, py, bw, bh, rect: true }
2226}
2227
2228/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2229/// instead of executed. Each variant is the resolved argument tuple of the
2230/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2231/// order performs exactly the same writes in exactly the same order --
2232/// entropy parsing no longer touches the frame's own planes (except the two
2233/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2234/// the replay on a superblock-row wavefront worker.
2235/// The dequantization + inverse transform of one transform unit, kept as its
2236/// INPUTS so that a recorded write carries the work instead of its result
2237/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2238/// recon worker, not on the parsing thread. `stride == 0` means the dense
2239/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2240/// `reconstruct_mc_rect` reads both of its buffers at.
2241#[derive(Clone, Copy)]
2242pub(crate) struct TxParams {
2243 pub(crate) w: usize,
2244 pub(crate) h: usize,
2245 pub(crate) bit_depth: u8,
2246 pub(crate) q_idx: i32,
2247 pub(crate) dc_delta: i32,
2248 pub(crate) ac_delta: i32,
2249 pub(crate) tx_type: TxType,
2250 pub(crate) stride: usize,
2251 /// lane-lossless: this transform unit belongs to a lossless frame, so the
2252 /// residual comes off the 4x4 Walsh-Hadamard
2253 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2254 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2255 pub(crate) lossless: bool,
2256}
2257
2258impl TxParams {
2259 /// The one copy of the produce-the-residual code: the inline path calls it
2260 /// on the parse thread, the wavefront worker calls it on its own, so both
2261 /// are the same function on the same inputs and byte-identical.
2262 fn run(self, grid: &[i32]) -> Vec<i32> {
2263 let residual = if self.lossless {
2264 debug_assert_eq!((self.w, self.h), (4, 4));
2265 debug_assert_eq!(self.tx_type, TxType::DctDct);
2266 crate::transform::dequant_and_inverse_wht4x4(
2267 grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2268 )
2269 } else {
2270 dequant_and_inverse_typed_wh(
2271 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2272 self.tx_type,
2273 )
2274 };
2275 // An all-zero grid transforms to the empty marker, and a strided copy
2276 // of zeros is still zeros: the marker passes straight through.
2277 if residual.is_empty() {
2278 return residual;
2279 }
2280 if self.stride == 0 {
2281 return residual;
2282 }
2283 let mut strided = vec![0i32; self.stride * self.stride];
2284 for row in 0..self.h {
2285 strided[row * self.stride..][..self.w]
2286 .copy_from_slice(&residual[row * self.w..][..self.w]);
2287 }
2288 strided
2289 }
2290}
2291
2292/// A recorded write's residual: already transformed, or the coefficients and
2293/// [`TxParams`] the worker transforms itself.
2294pub(crate) enum Residual {
2295 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2296 /// `len` is the all-zero marker [`dense_residual`] expands.
2297 Done(u32, u32),
2298 /// The coefficients live in the pushing tile's arena
2299 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2300 /// len)` in it.
2301 Coeffs(TxParams, u32, u32),
2302}
2303
2304impl Residual {
2305 /// The record for a transform unit whose coefficient grid is all zero:
2306 /// the empty marker, so neither the grid nor the residual is cloned and
2307 /// the worker never runs the transform (60% of the 4K segment's units).
2308 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2309 if is_zero_grid(grid) {
2310 return Self::Done(0, 0);
2311 }
2312 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2313 }
2314
2315 /// A residual the parse thread already transformed, kept in the arena
2316 /// instead of its own `Vec`.
2317 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2318 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2319 // which is exactly the all-zero marker -- one pointer compare instead
2320 // of copying up to 64 KB of zeros into the arena per block.
2321 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2322 return Self::Done(0, 0);
2323 }
2324 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2325 }
2326
2327 /// The residual to reconstruct with; `scratch` is where a transform run
2328 /// on this thread lands, so the caller owns that buffer.
2329 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2330 match self {
2331 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2332 Self::Coeffs(p, off, len) => {
2333 *scratch = p.run(&arena[off as usize..][..len as usize]);
2334 scratch
2335 }
2336 }
2337 }
2338}
2339
2340/// Appends to the tile's coefficient arena, returning the offset the record
2341/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2342fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2343 fctx.coeff_arena.with(|a| {
2344 let mut a = a.borrow_mut();
2345 let off = a.len();
2346 a.extend_from_slice(v);
2347 off as u32
2348 })
2349}
2350
2351/// [`push_coeffs`] for a recorded prediction.
2352fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2353 fctx.pred_arena.with(|a| {
2354 let mut a = a.borrow_mut();
2355 let off = a.len();
2356 a.extend_from_slice(v);
2357 off as u32
2358 })
2359}
2360
2361/// An all-zero residual, for the transform units that code no coefficient:
2362/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2363/// and the reconstruction loops below read this instead of a per-unit
2364/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2365/// (a 128-wide inter block's prediction stride).
2366pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2367
2368/// lane-blockscratch: one plane's coefficient levels as the block-tail
2369/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2370/// strip with no chroma, luma under a var-tx split whose units already wrote
2371/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2372/// zeroing up to 64 KB of its own per block.
2373#[derive(Clone)]
2374enum Grid {
2375 Zero(usize),
2376 Own(Vec<i32>),
2377}
2378
2379/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2380/// unit that writes into it. Only a block wider or taller than 64 px codes its
2381/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2382/// collectors per block and then drop them untouched.
2383fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2384 if v.is_empty() {
2385 *v = vec![0i32; n];
2386 }
2387 v
2388}
2389
2390impl std::ops::Deref for Grid {
2391 type Target = [i32];
2392 fn deref(&self) -> &[i32] {
2393 match self {
2394 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2395 Grid::Own(v) => v,
2396 }
2397 }
2398}
2399
2400/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2401/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2402/// transform units that code no coefficient without the scan (lane-coefgrid).
2403pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2404 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2405}
2406
2407/// `residual`, or `n` zeros when it is the empty all-zero marker.
2408fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2409 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2410}
2411
2412/// Where a recorded motion-compensated write reads its prediction from.
2413///
2414/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2415/// the parse thread's single biggest reconstruction cost, so at
2416/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2417/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2418/// runs it into its own three-plane slot, and every transform unit of that
2419/// block then reads its window out of that slot ([`Pred::Cur`]).
2420#[derive(Clone, Copy)]
2421pub(crate) enum Pred<'a> {
2422 /// A prediction the parse thread already built, at its own stride
2423 /// (`stride == 0` means "the reader's own `stride` argument").
2424 Inline(&'a [u16], usize),
2425 /// The current block's deferred prediction: plane, its stride, and this
2426 /// unit's offset into it.
2427 Cur { plane: usize, stride: usize, off: usize },
2428}
2429
2430impl<'a> Pred<'a> {
2431 /// The same prediction read at an explicit stride.
2432 fn view(self, stride: usize) -> Self {
2433 match self {
2434 Self::Inline(b, _) => Self::Inline(b, stride),
2435 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2436 }
2437 }
2438 /// The materialised buffer and the stride to read it at (`stride` is the
2439 /// reader's own when this prediction was built dense); `None` for a
2440 /// deferred prediction, which only a recorded op can carry.
2441 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2442 match self {
2443 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2444 Self::Cur { .. } => None,
2445 }
2446 }
2447 /// This prediction's window starting `n` samples in.
2448 fn offset(self, n: usize) -> Self {
2449 match self {
2450 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2451 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2452 }
2453 }
2454}
2455
2456/// [`Pred`], resolved into what a recorded op carries.
2457pub(crate) enum PredSrc {
2458 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2459 Owned(u32, u32),
2460 /// A window of the block prediction: its plane, its offset, and the
2461 /// stride it is read at -- which is the block's, not necessarily the
2462 /// op's (a transform unit's residual stays dense, so the worker takes
2463 /// its window out of the block prediction itself).
2464 Cur { plane: usize, off: usize, src: usize },
2465}
2466
2467/// One block's whole-block prediction build, deferred to a recon worker.
2468///
2469/// The closure borrows the tile's reference pictures and its own frame-level
2470/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2471/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2472/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2473pub(crate) struct PredBuild(
2474 Box<
2475 dyn FnOnce(
2476 &mut PlaneBuf<'static>,
2477 &mut PlaneBuf<'static>,
2478 &mut PlaneBuf<'static>,
2479 &crate::decode::FrameCtx,
2480 // lane-blockmem: the previous block's three prediction buffers,
2481 // refilled in place -- the build used to return three fresh
2482 // `Vec`s per block and drop these.
2483 &mut [Vec<u16>; 3],
2484 ),
2485 >,
2486);
2487
2488// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2489// pictures and frame tables, and the closure runs on exactly one worker.
2490#[allow(unsafe_code)]
2491unsafe impl Send for PredBuild {}
2492
2493/// `true` when this tile's writes are recorded for the wavefront instead of
2494/// performed at the push site, i.e. when a prediction may be deferred.
2495fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2496 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2497}
2498
2499/// The previous block's prediction buffer, cleared and zero-filled to `n`
2500/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2501/// without the per-block allocation and free.
2502fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2503 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2504 // than resized element by element -- which is every block on the inline
2505 // path, where there is no previous buffer to reuse.
2506 if v.capacity() < n {
2507 return vec![0u16; n];
2508 }
2509 v.clear();
2510 v.resize(n, 0);
2511 v
2512}
2513
2514/// Records one block's prediction build for the worker that reconstructs it.
2515#[allow(unsafe_code)]
2516fn push_pred<'a>(
2517 fctx: &crate::decode::FrameCtx,
2518 f: impl FnOnce(
2519 &mut PlaneBuf<'static>,
2520 &mut PlaneBuf<'static>,
2521 &mut PlaneBuf<'static>,
2522 &crate::decode::FrameCtx,
2523 &mut [Vec<u16>; 3],
2524 ) + 'a,
2525) {
2526 type Dyn<'x> = dyn FnOnce(
2527 &mut PlaneBuf<'static>,
2528 &mut PlaneBuf<'static>,
2529 &mut PlaneBuf<'static>,
2530 &crate::decode::FrameCtx,
2531 &mut [Vec<u16>; 3],
2532 ) + 'x;
2533 let boxed: Box<Dyn<'a>> = Box::new(f);
2534 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2535 // before the borrows the closure holds go out of scope.
2536 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2537 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2538}
2539
2540/// One superblock's recorded writes plus the two arenas they index -- the
2541/// unit a wavefront worker takes off the queue (lane-recoparse).
2542pub(crate) struct ReconJob {
2543 ops: Vec<ReconOp>,
2544 coeffs: Vec<i32>,
2545 preds: Vec<u16>,
2546}
2547
2548pub(crate) enum ReconOp {
2549 /// lane-wave4: build this block's prediction into the worker's slot.
2550 Pred(PredBuild),
2551 Intra {
2552 plane: usize,
2553 x: usize,
2554 y: usize,
2555 bw: usize,
2556 bh: usize,
2557 /// `true` when the parse site called `reconstruct_rect` (whose
2558 /// `edges_rect` differs from `edges` even at `bw == bh`).
2559 rect: bool,
2560 mode: usize,
2561 angle_delta: i32,
2562 reach: Reach,
2563 residual: Residual,
2564 cfl: Option<(i32, CflSrc)>,
2565 filter_intra: Option<usize>,
2566 smooth_neighbor: bool,
2567 /// The palette/intrabc prediction override, taken off
2568 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2569 /// from that slot by the replay.
2570 pred: Option<Vec<u16>>,
2571 },
2572 Mc {
2573 plane: usize,
2574 x: usize,
2575 y: usize,
2576 stride: usize,
2577 w: usize,
2578 h: usize,
2579 prediction: PredSrc,
2580 residual: Residual,
2581 },
2582}
2583
2584/// The three planes of the tile currently being decoded, as raw pointers.
2585///
2586/// corner-cut: at one reconstruction thread a recorded write must cost
2587/// nothing -- deferring it to the end of the superblock is +1.2%
2588/// instructions and +4.5% wall on 4K, because the residual is written at
2589/// parse and read back cache-cold at replay. So the recorded op is performed
2590/// at the push site instead, through the pointers the tile decoder registers
2591/// once ([`ReconInline`]), which is the same thread, the same order and the
2592/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2593/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2594/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2595/// threading the three planes down every `read_plane`/`read_inter_plane`
2596/// call site (~40) so the push site owns the borrow it writes through.
2597#[derive(Clone, Copy)]
2598pub(crate) struct ReconPlanes(
2599 *mut PlaneBuf<'static>,
2600 *mut PlaneBuf<'static>,
2601 *mut PlaneBuf<'static>,
2602);
2603
2604// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2605// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2606// value travelling is `None`; the pointers never leave the tile decoder's
2607// own thread.
2608#[allow(unsafe_code)]
2609unsafe impl Send for ReconPlanes {}
2610// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2611// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2612// contract, one superblock per band instead of one row band.
2613#[allow(unsafe_code)]
2614unsafe impl Sync for ReconPlanes {}
2615
2616/// Registers the tile's planes for inline reconstruction and unregisters them
2617/// on every exit from the tile decoder, including the `?` ones -- a stale
2618/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2619/// tile.
2620pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2621
2622#[allow(unsafe_code)]
2623impl<'a> ReconInline<'a> {
2624 /// Installs the guard for this tile when reconstruction is inline
2625 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2626 /// to the queue instead, for the wavefront workers to replay.
2627 fn install(
2628 fctx: &'a crate::decode::FrameCtx,
2629 y: &mut PlaneBuf<'static>,
2630 u: &mut PlaneBuf<'static>,
2631 v: &mut PlaneBuf<'static>,
2632 ) -> Option<Self> {
2633 if crate::par::recon_threads() != 1 {
2634 return None;
2635 }
2636 // SAFETY: the planes are locals of the tile decoder and outlive the
2637 // guard, which is dropped on every exit from it (including `?`); see
2638 // [`ReconPlanes`] for the aliasing trade-off.
2639 let planes = ReconPlanes(
2640 std::ptr::from_mut(y),
2641 std::ptr::from_mut(u),
2642 std::ptr::from_mut(v),
2643 );
2644 fctx.recon_planes.with(|c| c.set(Some(planes)));
2645 Some(Self(fctx))
2646 }
2647}
2648
2649impl Drop for ReconInline<'_> {
2650 fn drop(&mut self) {
2651 self.0.recon_planes.with(|c| c.set(None));
2652 }
2653}
2654
2655#[allow(unsafe_code)]
2656fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2657 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2658 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2659 // the parse site would have performed itself before lane-wave1.
2660 // The inline path never records coefficients (the transform runs at
2661 // the push site), so the arena is not read here.
2662 unsafe {
2663 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2664 };
2665 return;
2666 }
2667 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2668}
2669
2670/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2671/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2672///
2673/// The parser keeps parsing and never touches the planes; each superblock's
2674/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2675/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2676/// four of their 64x64 visits, since a 128 block writes across quadrants).
2677/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2678/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2679/// every pixel an intra predictor can read (its edges reach one block right
2680/// along the row above and one block down the column to the left, both
2681/// inside those two neighbours) and every CfL AC read (this block's own
2682/// luma, written by this same job). Jobs are handed out in raster order, so
2683/// the oldest outstanding one always has its dependencies met: no deadlock.
2684///
2685/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2686/// `thread_local!` and miss every worker, which is why the default is 1.
2687pub(crate) struct WaveState {
2688 q: std::sync::Mutex<WaveQueue>,
2689 cv: std::sync::Condvar,
2690 planes: ReconPlanes,
2691 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2692 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2693 bit_depth: u8,
2694 enable_edge_filter: bool,
2695 last_col: usize,
2696}
2697
2698struct WaveQueue {
2699 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2700 /// row's front job can ever be runnable -- a job waits on its own left
2701 /// neighbour -- so a worker takes the lowest row whose front job's
2702 /// dependencies are met. Popping the raster-oldest job instead (what
2703 /// this replaced) put every worker on the SAME row, where the wavefront
2704 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2705 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
2706 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2707 /// walking it.
2708 queued: usize,
2709 /// Per superblock row, the last column reconstructed (-1 = none yet).
2710 done: Vec<isize>,
2711 /// Per superblock row, the last column PARSED (submitted, whether or not
2712 /// it recorded any write) and the last column actually pushed as a job
2713 /// (-1 = none). A row is fully reconstructed once it has been parsed to
2714 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2715 /// reads that to release the row's filters (see [`wave_rows_complete`]).
2716 last_sub: Vec<isize>,
2717 last_push: Vec<isize>,
2718 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2719 active: usize,
2720 closed: bool,
2721 /// lane-sballoc: the three per-superblock buffers a finished job hands
2722 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
2723 /// first-touch page faults) instead of the `Vec::with_capacity` it used
2724 /// to make per superblock -- 3 allocations and 3 frees per superblock,
2725 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
2726 /// inside the queue's own mutex, which both sides already take.
2727 free: Vec<JobBufs>,
2728 free_cap: usize,
2729}
2730
2731/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
2732type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
2733
2734impl WaveQueue {
2735 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2736 /// or `None` (with the blocking condition counted when instrumented).
2737 fn take_runnable(
2738 &mut self,
2739 last_col: usize,
2740 stats: bool,
2741 ) -> Option<(usize, usize, ReconJob)> {
2742 let mut blocked: Option<bool> = None;
2743 for r in 0..self.rows.len() {
2744 let Some(front) = self.rows[r].front() else {
2745 continue;
2746 };
2747 let c = front.0;
2748 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2749 let left = c == 0 || self.done[r] >= c as isize - 1;
2750 if above && left {
2751 let (c, job) = self.rows[r].pop_front().expect("front checked above");
2752 self.queued -= 1;
2753 return Some((r, c, job));
2754 }
2755 if blocked.is_none() {
2756 blocked = Some(above);
2757 }
2758 }
2759 if stats {
2760 match blocked {
2761 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2762 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2763 None => 0,
2764 };
2765 }
2766 None
2767 }
2768}
2769
2770/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2771/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2772/// empty queue), how far ahead the parse thread is, and how often the two
2773/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2774/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2775/// whole run.
2776const WS_SLOTS: usize = 16;
2777use std::sync::atomic::AtomicU64;
2778use std::sync::atomic::Ordering::Relaxed;
2779static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2780static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2781static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2782static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2783static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2784static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2785/// Parse-thread time between two submits, i.e. everything parse still does
2786/// itself (symbol decode plus the predictions not deferred).
2787static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2788/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2789/// (the intrabc/interintra reads) and at the tile's end.
2790static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2791static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2792static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2793static WS_TILES: AtomicU64 = AtomicU64::new(0);
2794
2795fn wave_stats() -> bool {
2796 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2797 match ON.load(Relaxed) {
2798 0 => {
2799 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2800 .map(|v| v.trim() == "1")
2801 .unwrap_or(false);
2802 ON.store(1 + u8::from(on), Relaxed);
2803 on
2804 }
2805 n => n == 2,
2806 }
2807}
2808
2809fn wave_stats_dump() {
2810 let ms = |n: u64| n as f64 / 1e6;
2811 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2812 for i in 0..WS_SLOTS {
2813 let jobs = WS_JOBS[i].load(Relaxed);
2814 if jobs == 0 {
2815 continue;
2816 }
2817 s += &format!(
2818 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2819 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2820 ms(WS_BUSY[i].load(Relaxed)),
2821 ms(WS_WAIT[i].load(Relaxed)),
2822 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2823 );
2824 }
2825 s += &format!(
2826 " | pipe={}/{}",
2827 PIPE_FRAMES.load(Relaxed),
2828 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2829 );
2830 s += &format!(
2831 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2832 ms(WS_PARSE.load(Relaxed)),
2833 ms(WS_BARRIER.load(Relaxed)),
2834 WS_BARRIERS.load(Relaxed),
2835 ms(WS_DRAIN.load(Relaxed)),
2836 WS_BLOCK_ABOVE.load(Relaxed),
2837 WS_BLOCK_LEFT.load(Relaxed),
2838 );
2839 eprintln!("{s}");
2840}
2841
2842#[allow(unsafe_code)]
2843fn wave_worker(st: &WaveState, idx: usize) {
2844 let fctx = FrameCtx::new();
2845 fctx.bit_depth.set(st.bit_depth);
2846 fctx.enable_edge_filter.set(st.enable_edge_filter);
2847 let stats = wave_stats();
2848 let slot = idx.min(WS_SLOTS - 1);
2849 loop {
2850 let t0 = std::time::Instant::now();
2851 let mut q = st.q.lock().unwrap();
2852 let (r, c, job) = loop {
2853 if let Some(job) = q.take_runnable(st.last_col, stats) {
2854 break job;
2855 }
2856 if q.closed && q.queued == 0 {
2857 return;
2858 }
2859 q = st.cv.wait(q).unwrap();
2860 };
2861 q.active += 1;
2862 drop(q);
2863 if stats {
2864 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2865 WS_JOBS[slot].fetch_add(1, Relaxed);
2866 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
2867 }
2868 let t1 = std::time::Instant::now();
2869 let ReconPlanes(y, u, v) = st.planes;
2870 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2871 // every superblock that could have written or be reading them is
2872 // complete by the wavefront rule above.
2873 let mut cur: [Vec<u16>; 3] = Default::default();
2874 let ReconJob { mut ops, mut coeffs, mut preds } = job;
2875 unsafe {
2876 for op in ops.drain(..) {
2877 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
2878 }
2879 }
2880 if stats {
2881 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2882 }
2883 coeffs.clear();
2884 preds.clear();
2885 let mut q = st.q.lock().unwrap();
2886 // lane-sballoc: hand the three buffers back for the next submit.
2887 if q.free.len() < q.free_cap {
2888 q.free.push((ops, coeffs, preds));
2889 }
2890 q.done[r] = c as isize;
2891 q.active -= 1;
2892 st.cv.notify_all();
2893 }
2894}
2895
2896/// Installs the wavefront for one tile and joins its workers on every exit
2897/// from the tile decoder, including the `?` ones -- the jobs hold raw
2898/// pointers into the tile's planes, so no worker may outlive them.
2899/// (lane-pool1: the workers come from this thread's persistent pool, so a
2900/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
2901/// with fresh scratch.)
2902pub(crate) struct WaveGuard<'a>(
2903 &'a crate::decode::FrameCtx,
2904 Option<crate::par::Batch<'static>>,
2905);
2906
2907#[allow(unsafe_code)]
2908impl<'a> WaveGuard<'a> {
2909 fn install(
2910 fctx: &'a crate::decode::FrameCtx,
2911 y: &mut PlaneBuf<'static>,
2912 u: &mut PlaneBuf<'static>,
2913 v: &mut PlaneBuf<'static>,
2914 rows: usize,
2915 cols: usize,
2916 ) -> Option<Self> {
2917 let threads = crate::par::recon_threads();
2918 if threads == 1 || rows == 0 || cols == 0 {
2919 return None;
2920 }
2921 let st = std::sync::Arc::new(WaveState {
2922 q: std::sync::Mutex::new(WaveQueue {
2923 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2924 queued: 0,
2925 done: vec![-1; rows],
2926 last_sub: vec![-1; rows],
2927 last_push: vec![-1; rows],
2928 active: 0,
2929 closed: false,
2930 free: Vec::new(),
2931 free_cap: threads + 2,
2932 }),
2933 cv: std::sync::Condvar::new(),
2934 // SAFETY: the planes are locals of the tile decoder and outlive
2935 // this guard, which joins every worker in `drop`.
2936 planes: ReconPlanes(
2937 std::ptr::from_mut(y),
2938 std::ptr::from_mut(u),
2939 std::ptr::from_mut(v),
2940 ),
2941 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
2942 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
2943 last_col: cols - 1,
2944 });
2945 let batch = crate::par::Batch::new("ec-av1-recon");
2946 for idx in 0..threads {
2947 let st = std::sync::Arc::clone(&st);
2948 batch.submit(move || wave_worker(&st, idx));
2949 }
2950 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2951 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
2952 Some(Self(fctx, Some(batch)))
2953 }
2954}
2955
2956impl Drop for WaveGuard<'_> {
2957 fn drop(&mut self) {
2958 let st = self.0.wave.with(|w| w.borrow_mut().take());
2959 if let Some(st) = st {
2960 st.q.lock().unwrap().closed = true;
2961 st.cv.notify_all();
2962 }
2963 let t0 = std::time::Instant::now();
2964 // Dropping the batch waits every worker out, as the joins did.
2965 drop(self.1.take());
2966 if wave_stats() {
2967 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2968 WS_TILES.fetch_add(1, Relaxed);
2969 wave_stats_dump();
2970 }
2971 }
2972}
2973
2974/// An empty buffer for the next superblock: the recycled one when it is at
2975/// least as big as the superblock just parsed, else a fresh sized one
2976/// (lane-sballoc; `v` is always empty).
2977fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
2978 if v.capacity() < cap {
2979 v.reserve_exact(cap - v.len());
2980 }
2981 v
2982}
2983
2984/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
2985/// when there is no wavefront (one reconstruction thread), in which case the
2986/// caller replays them itself.
2987fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2988 let st = fctx.wave.with(|w| w.borrow().clone());
2989 let Some(st) = st else { return false };
2990 // lane-blockmem: the op list is replaced sized for the next superblock,
2991 // exactly as the two arenas below are -- taking it left a zero-capacity
2992 // `Vec` that regrew (and memmoved every recorded op) from nothing on
2993 // every superblock.
2994 // lane-sballoc: the replacement comes from the finished jobs' free list
2995 // when there is one (warm capacity, already faulted in); only the first
2996 // superblocks of a tile allocate.
2997 let mut q = st.q.lock().unwrap();
2998 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
2999 let ops = fctx.recon_ops.with(|c| {
3000 let mut c = c.borrow_mut();
3001 let cap = c.len();
3002 std::mem::replace(&mut *c, reuse(sops, cap))
3003 });
3004 // The job owns its coefficients: the arena is replaced by an empty one
3005 // sized for the next superblock, so parse never regrows from nothing and
3006 // the worker frees this buffer once, instead of once per unit.
3007 let coeffs = fctx.coeff_arena.with(|c| {
3008 let mut c = c.borrow_mut();
3009 let cap = c.len();
3010 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3011 });
3012 let preds = fctx.pred_arena.with(|c| {
3013 let mut c = c.borrow_mut();
3014 let cap = c.len();
3015 std::mem::replace(&mut *c, reuse(spreds, cap))
3016 });
3017 {
3018 if (c as isize) > q.last_sub[r] {
3019 q.last_sub[r] = c as isize;
3020 }
3021 if !ops.is_empty() {
3022 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3023 q.queued += 1;
3024 q.last_push[r] = c as isize;
3025 }
3026 drop(q);
3027 st.cv.notify_all();
3028 }
3029 if wave_stats() {
3030 let now = std::time::Instant::now();
3031 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3032 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3033 }
3034 }
3035 true
3036}
3037
3038/// Waits until every submitted job is reconstructed, so the parser may read
3039/// the planes itself (the intrabc source fetch and the interintra intra
3040/// predictor -- see [`flush_recon`]).
3041fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3042 let st = fctx.wave.with(|w| w.borrow().clone());
3043 let Some(st) = st else { return };
3044 let stats = wave_stats();
3045 let t0 = std::time::Instant::now();
3046 let mut q = st.q.lock().unwrap();
3047 while q.queued > 0 || q.active > 0 {
3048 q = st.cv.wait(q).unwrap();
3049 }
3050 drop(q);
3051 if stats {
3052 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3053 WS_BARRIERS.fetch_add(1, Relaxed);
3054 }
3055}
3056
3057/// Performs an intra write at its push site when the tile registered its
3058/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3059/// caller must record it for the wavefront workers instead.
3060#[allow(unsafe_code)]
3061#[allow(clippy::too_many_arguments)]
3062fn inline_intra(
3063 plane: usize,
3064 x: usize,
3065 oy: usize,
3066 bw: usize,
3067 bh: usize,
3068 rect: bool,
3069 mode: usize,
3070 angle_delta: i32,
3071 reach: Reach,
3072 residual: &[i32],
3073 cfl: Option<(i32, CflSrc)>,
3074 filter_intra: Option<usize>,
3075 smooth_neighbor: bool,
3076 fctx: &crate::decode::FrameCtx,
3077) -> bool {
3078 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3079 return false;
3080 };
3081 let pred = take_palette_pred(fctx);
3082 // SAFETY: see [`ReconPlanes`].
3083 unsafe {
3084 exec_intra(
3085 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3086 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
3087 );
3088 }
3089 true
3090}
3091
3092/// [`inline_intra`] for a motion-compensated write.
3093#[allow(unsafe_code)]
3094#[allow(clippy::too_many_arguments)]
3095fn inline_mc(
3096 plane: usize,
3097 x: usize,
3098 oy: usize,
3099 stride: usize,
3100 w: usize,
3101 h: usize,
3102 prediction: &[u16],
3103 residual: &[i32],
3104 fctx: &crate::decode::FrameCtx,
3105) -> bool {
3106 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3107 return false;
3108 };
3109 // SAFETY: see [`ReconPlanes`].
3110 unsafe {
3111 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
3112 }
3113 true
3114}
3115
3116/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3117#[allow(clippy::too_many_arguments)]
3118fn push_intra(
3119 plane: usize,
3120 x: usize,
3121 y: usize,
3122 side: usize,
3123 mode: usize,
3124 angle_delta: i32,
3125 reach: Reach,
3126 residual: &[i32],
3127 cfl: Option<(i32, CflSrc)>,
3128 filter_intra: Option<usize>,
3129 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3130) {
3131 if inline_intra(
3132 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3133 smooth_neighbor, fctx,
3134 ) {
3135 return;
3136 }
3137 let pred = take_palette_pred(fctx);
3138 push_op(fctx, ReconOp::Intra {
3139 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3140 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3141 });
3142}
3143
3144/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3145#[allow(clippy::too_many_arguments)]
3146fn push_intra_rect(
3147 plane: usize,
3148 x: usize,
3149 y: usize,
3150 bw: usize,
3151 bh: usize,
3152 mode: usize,
3153 angle_delta: i32,
3154 reach: Reach,
3155 residual: &[i32],
3156 cfl: Option<(i32, CflSrc)>,
3157 filter_intra: Option<usize>,
3158 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3159) {
3160 if inline_intra(
3161 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3162 smooth_neighbor, fctx,
3163 ) {
3164 return;
3165 }
3166 let pred = take_palette_pred(fctx);
3167 push_op(fctx, ReconOp::Intra {
3168 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3169 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3170 });
3171}
3172
3173/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3174fn push_mc(
3175 plane: usize,
3176 x: usize,
3177 y: usize,
3178 side: usize,
3179 prediction: Pred<'_>,
3180 residual: &[i32], fctx: &crate::decode::FrameCtx,
3181) {
3182 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3183}
3184
3185/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3186#[allow(clippy::too_many_arguments)]
3187fn push_mc_rect(
3188 plane: usize,
3189 x: usize,
3190 y: usize,
3191 stride: usize,
3192 w: usize,
3193 h: usize,
3194 prediction: Pred<'_>,
3195 residual: &[i32], fctx: &crate::decode::FrameCtx,
3196) {
3197 let (src, stride) = match prediction.inline(stride) {
3198 Some(v) => v,
3199 None => {
3200 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3201 push_op(fctx, ReconOp::Mc {
3202 plane, x, y, stride: ss, w, h,
3203 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3204 residual: Residual::done(residual, fctx),
3205 });
3206 return;
3207 }
3208 };
3209 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3210 return;
3211 }
3212 push_op(fctx, ReconOp::Mc {
3213 plane, x, y, stride, w, h,
3214 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3215 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3216 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3217 residual: Residual::done(residual, fctx),
3218 });
3219}
3220
3221/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3222/// thread the transform runs here, exactly as before; on the wavefront it
3223/// travels with the op and runs on the worker (lane-wave3).
3224#[allow(clippy::too_many_arguments)]
3225fn push_intra_tx(
3226 plane: usize,
3227 x: usize,
3228 y: usize,
3229 bw: usize,
3230 bh: usize,
3231 rect: bool,
3232 mode: usize,
3233 angle_delta: i32,
3234 reach: Reach,
3235 tx: TxParams,
3236 grid: &[i32],
3237 cfl: Option<(i32, CflSrc)>,
3238 filter_intra: Option<usize>,
3239 smooth_neighbor: bool,
3240 fctx: &crate::decode::FrameCtx,
3241) {
3242 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3243 inline_intra(
3244 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3245 smooth_neighbor, fctx,
3246 );
3247 return;
3248 }
3249 let pred = take_palette_pred(fctx);
3250 push_op(fctx, ReconOp::Intra {
3251 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3252 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3253 });
3254}
3255
3256/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3257#[allow(clippy::too_many_arguments)]
3258fn push_mc_rect_tx(
3259 plane: usize,
3260 x: usize,
3261 y: usize,
3262 stride: usize,
3263 w: usize,
3264 h: usize,
3265 prediction: Pred<'_>,
3266 tx: TxParams,
3267 grid: &[i32],
3268 fctx: &crate::decode::FrameCtx,
3269) {
3270 // lane-wave4: a deferred prediction is not there to be windowed -- the
3271 // op carries its offset into the block's prediction instead, and the
3272 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3273 // both buffers at one stride).
3274 let (prediction, stride) = match prediction.inline(stride) {
3275 Some(v) => v,
3276 None => {
3277 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3278 let mut tx = tx;
3279 tx.stride = 0;
3280 push_op(fctx, ReconOp::Mc {
3281 plane, x, y, stride: w, w, h,
3282 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3283 residual: Residual::coeffs(tx, grid, fctx),
3284 });
3285 return;
3286 }
3287 };
3288 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3289 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3290 // stride, so a prediction handed over at the block's stride (a var-tx
3291 // unit's window, lane-wave4) has to be densified for a dense residual
3292 // -- which is exactly what the recorded path below does.
3293 let residual = tx.run(grid);
3294 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3295 let window;
3296 let prediction = if stride == res_stride {
3297 prediction
3298 } else {
3299 debug_assert_eq!(res_stride, w);
3300 let mut win = Vec::with_capacity(w * h);
3301 for row in 0..h {
3302 win.extend_from_slice(&prediction[row * stride..][..w]);
3303 }
3304 window = win;
3305 &window[..]
3306 };
3307 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3308 return;
3309 }
3310 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3311 // two buffers at `stride`, so the record carries that window densely
3312 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3313 // copied 64*64 samples on the PARSING thread before. The residual is then
3314 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3315 // in the same places at stride `w`.
3316 let off = fctx.pred_arena.with(|a| {
3317 let mut a = a.borrow_mut();
3318 let off = a.len();
3319 for row in 0..h {
3320 a.extend_from_slice(&prediction[row * stride..][..w]);
3321 }
3322 off as u32
3323 });
3324 let mut tx = tx;
3325 tx.stride = 0;
3326 push_op(fctx, ReconOp::Mc {
3327 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3328 residual: Residual::coeffs(tx, grid, fctx),
3329 });
3330}
3331
3332/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3333/// and empties the queue (lane-wave1 step (i)).
3334///
3335/// Called at the top of each superblock visit and at the end of each tile, so
3336/// a whole superblock's parsing runs with no plane access at all; the two
3337/// parse-time pixel READS that survive -- the intrabc source fetch and the
3338/// interintra intra predictor -- flush ahead of themselves instead, which
3339/// keeps them byte-exact and names exactly what step (ii) still has to move.
3340fn flush_recon(
3341 fctx: &crate::decode::FrameCtx,
3342 y: &mut PlaneBuf<'static>,
3343 u: &mut PlaneBuf<'static>,
3344 v: &mut PlaneBuf<'static>,
3345) {
3346 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3347 // writes in place, not just this superblock's queue.
3348 wave_barrier(fctx);
3349 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3350 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3351 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3352 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3353 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3354 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3355 let mut cur: [Vec<u16>; 3] = Default::default();
3356 for op in ops.drain(..) {
3357 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3358 }
3359 coeffs.clear();
3360 preds.clear();
3361 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3362 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3363 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3364}
3365
3366/// Performs one recorded write: the body [`flush_recon`] replays, and the
3367/// body [`push_op`] runs immediately when reconstruction is inline.
3368fn exec_op(
3369 op: ReconOp,
3370 y: &mut PlaneBuf<'static>,
3371 u: &mut PlaneBuf<'static>,
3372 v: &mut PlaneBuf<'static>,
3373 cur: &mut [Vec<u16>; 3],
3374 coeffs: &[i32],
3375 preds: &[u16],
3376 fctx: &crate::decode::FrameCtx,
3377) {
3378 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
3379 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
3380 // alone. It makes the encoder's own streams garbage, so it is a
3381 // MEASUREMENT rung only -- what it measures is how much of the encoder's
3382 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
3383 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
3384 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
3385 // stage and the parse plus the neighbour grids are the other 94%. That
3386 // is why handing the decoder the encoder's own reconstruction cannot
3387 // shrink the stage: only publishing the per-mi neighbour state the
3388 // filters read (and so never parsing at all) can.
3389 if crate::envflags::env_flag!("EC_AV1_NORECON") {
3390 return;
3391 }
3392 let mut scratch = Vec::new();
3393 match op {
3394 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3395 ReconOp::Intra {
3396 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3397 filter_intra, smooth_neighbor, pred,
3398 } => exec_intra(
3399 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3400 residual.resolve(coeffs, &mut scratch),
3401 cfl, filter_intra, smooth_neighbor, pred, fctx,
3402 ),
3403 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3404 let residual = residual.resolve(coeffs, &mut scratch);
3405 match prediction {
3406 PredSrc::Owned(off, len) => {
3407 let p = &preds[off as usize..][..len as usize];
3408 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3409 }
3410 PredSrc::Cur { plane: sp, off, src } => {
3411 let block = std::mem::take(&mut cur[sp]);
3412 if src == stride {
3413 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3414 } else {
3415 // A transform unit's residual is dense, so its window
3416 // of the block prediction is taken out dense too --
3417 // the copy the parsing thread used to make, made here.
3418 let mut window = Vec::with_capacity(w * h);
3419 for row in 0..h {
3420 window.extend_from_slice(&block[off + row * src..][..w]);
3421 }
3422 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3423 }
3424 cur[sp] = block;
3425 }
3426 }
3427 }
3428 }
3429}
3430
3431/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3432/// path ([`push_op`]'s registered planes) reaches it without ever building
3433/// the record -- which is what keeps one reconstruction thread at the cost of
3434/// the pre-lane-wave1 decoder.
3435#[allow(clippy::too_many_arguments)]
3436fn exec_intra(
3437 y: &mut PlaneBuf<'static>,
3438 u: &mut PlaneBuf<'static>,
3439 v: &mut PlaneBuf<'static>,
3440 plane: usize,
3441 x: usize,
3442 oy: usize,
3443 bw: usize,
3444 bh: usize,
3445 rect: bool,
3446 mode: usize,
3447 angle_delta: i32,
3448 reach: Reach,
3449 residual: &[i32],
3450 cfl: Option<(i32, CflSrc)>,
3451 filter_intra: Option<usize>,
3452 smooth_neighbor: bool,
3453 pred: Option<Vec<u16>>,
3454 fctx: &crate::decode::FrameCtx,
3455) {
3456 // The CfL AC signal is read HERE, off the luma that has already been
3457 // written for this block -- at parse time it would have been the previous
3458 // frame's samples.
3459 let ac = cfl.map(|(alpha, src)| {
3460 let sig = if src.rect {
3461 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3462 } else {
3463 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3464 };
3465 (alpha, sig)
3466 });
3467 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3468 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3469 if rect {
3470 target.reconstruct_rect(
3471 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3472 smooth_neighbor, pred, fctx,
3473 );
3474 } else {
3475 target.reconstruct(
3476 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3477 smooth_neighbor, pred, fctx,
3478 );
3479 }
3480}
3481
3482/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3483#[allow(clippy::too_many_arguments)]
3484fn exec_mc(
3485 y: &mut PlaneBuf<'static>,
3486 u: &mut PlaneBuf<'static>,
3487 v: &mut PlaneBuf<'static>,
3488 plane: usize,
3489 x: usize,
3490 oy: usize,
3491 stride: usize,
3492 w: usize,
3493 h: usize,
3494 prediction: &[u16],
3495 residual: &[i32],
3496 fctx: &crate::decode::FrameCtx,
3497) {
3498 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3499 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3500}
3501
3502thread_local! {
3503 /// The current frame's `mi` grid, kept only while a frame header set
3504 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3505 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3506 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3507 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3508 /// does not allow intrabc (so nothing is paid for it).
3509 ///
3510 /// corner-cut: only [`decode_block`] (the square path) records into it,
3511 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3512 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3513 /// be wrong there; upgrade = record from the rect/leaf paths too.
3514 /// The block vector [`read_intra_mode`] just decoded, handed to
3515 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3516 /// which the alternative -- a tenth tuple member through every caller --
3517 /// already avoids). Always `.take()`n by the block that reads it.
3518 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
3519 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3520}
3521 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3522 // an intrabc block's chroma reads can inherit it (see
3523 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3524 // through that one arming site.
3525 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3526 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3527 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3528 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3529 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3530 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3531 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3532 // -- getting it wrong desyncs the chroma coefficients, it is not a
3533 // reconstruction-only detail.
3534
3535/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3536/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3537/// needs no separate plumbing to reach the rect-strip mode reader.
3538fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3539 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3540}
3541
3542thread_local! {
3543 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3544 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3545 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3546 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3547}
3548
3549/// Current value of [`RECT_INTRABC_READS`].
3550pub(crate) fn rect_intrabc_reads() -> usize {
3551 RECT_INTRABC_READS.with(|c| c.get())
3552}
3553
3554/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3555#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3556pub(crate) fn reset_rect_intrabc_reads() {
3557 RECT_INTRABC_READS.with(|c| c.set(0));
3558}
3559
3560thread_local! {
3561 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3562 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3563 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3564}
3565
3566/// Current value of [`LEAF8_INTRABC_HITS`].
3567pub(crate) fn leaf8_intrabc_hits() -> usize {
3568 LEAF8_INTRABC_HITS.with(|c| c.get())
3569}
3570
3571/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3572#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3573pub(crate) fn reset_leaf8_intrabc_hits() {
3574 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3575}
3576
3577/// Current value of [`INTRABC_HITS`].
3578#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3579pub(crate) fn intrabc_hits() -> usize {
3580 INTRABC_HITS.with(|c| c.get())
3581}
3582
3583/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3584#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3585pub(crate) fn reset_intrabc_hits() {
3586 INTRABC_HITS.with(|c| c.set(0));
3587}
3588
3589thread_local! {
3590 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3591 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3592 /// that replaced the refusal "an intrabc block under TxMode::Select".
3593 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3594}
3595
3596/// Current value of [`INTRABC_VARTX_HITS`].
3597#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3598pub(crate) fn intrabc_vartx_hits() -> usize {
3599 INTRABC_VARTX_HITS.with(|c| c.get())
3600}
3601
3602/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3603#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3604pub(crate) fn reset_intrabc_vartx_hits() {
3605 INTRABC_VARTX_HITS.with(|c| c.set(0));
3606}
3607
3608/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3609/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3610/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3611/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3612fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
3613 fctx.intrabc_mi_grid.with(|g| {
3614 let mut g = g.borrow_mut();
3615 let Some((grid, _, _)) = g.as_mut() else {
3616 return;
3617 };
3618 let info = crate::mvstack::MiInfo {
3619 is_inter: dv.is_some(),
3620 ref_frame: 0,
3621 ref_frame1: NO_REF1,
3622 mv: mv16(dv.unwrap_or((0, 0))),
3623 mv1: (0, 0),
3624 is_new_mv: dv.is_some(),
3625 is_global_mv0: false,
3626 is_global_mv1: false,
3627 size: n4 as u8,
3628 size_h: n4 as u8,
3629 };
3630 for r in mi_r..mi_r + n4 {
3631 for c in mi_c..mi_c + n4 {
3632 grid.set(r, c, info);
3633 }
3634 }
3635 });
3636}
3637
3638// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3639// proves a real `skip_mode_present` stream actually reached a block that
3640// picked it, not just that the frame header bit was set.
3641thread_local! {
3642 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3643 const { std::cell::Cell::new(0) };
3644}
3645
3646/// Current value of [`SKIP_MODE_HITS`].
3647#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3648pub(crate) fn skip_mode_hits() -> usize {
3649 SKIP_MODE_HITS.with(|c| c.get())
3650}
3651
3652// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3653// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3654// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3655// reached [`obmc_blend`], not just the header bit.
3656thread_local! {
3657 static OBMC_HITS: std::cell::Cell<usize> =
3658 const { std::cell::Cell::new(0) };
3659}
3660
3661// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3662// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3663// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3664// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3665// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3666// decoder used to read with the wrong alphabet, so a gate that asserts this
3667// counter advanced proves the fixed path fired (class
3668// `gate-blind-to-feature`).
3669thread_local! {
3670 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3671}
3672
3673/// Current value of [`FIMV_ALPHABET_HITS`].
3674pub fn fimv_alphabet_hits() -> usize {
3675 FIMV_ALPHABET_HITS.with(|c| c.get())
3676}
3677
3678// lane-fimv r1: how many frame headers this decoder has decoded with
3679// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3680// prove the encoder really produced the header state under test rather than
3681// assume it.
3682thread_local! {
3683 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3684}
3685
3686/// Current value of [`FIMV_FRAME_HITS`].
3687pub fn fimv_frame_hits() -> usize {
3688 FIMV_FRAME_HITS.with(|c| c.get())
3689}
3690
3691/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3692/// `force_integer_mv` bit is set.
3693pub fn note_force_integer_mv_frame() {
3694 hit!(FIMV_FRAME_HITS);
3695}
3696
3697/// Current value of [`OBMC_HITS`].
3698#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3699pub(crate) fn obmc_hits() -> usize {
3700 OBMC_HITS.with(|c| c.get())
3701}
3702
3703// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3704// off the neighbour band -- the positive half of the proof for "an OBMC
3705// neighbour whose switchable interp filter was never recorded". A
3706// fixed-filter frame returns before this point (its neighbours legitimately
3707// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3708// `interp_filter` symbols were published by `record_inter_rect_mi`.
3709thread_local! {
3710 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3711}
3712
3713/// Current value of [`OBMC_FILTER_BAND_READS`].
3714#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3715pub(crate) fn obmc_filter_band_reads() -> usize {
3716 OBMC_FILTER_BAND_READS.with(|c| c.get())
3717}
3718
3719// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3720// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3721// reference would pass just as well and prove nothing, so the gate
3722// hard-asserts each combination this round lifts actually occurred:
3723// a compound block with a scaled tap, a warp block whose warp libaom
3724// suppresses because the reference is scaled, an OBMC block, an interintra
3725// block, and an 8x8 leaf.
3726thread_local! {
3727 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3728 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3729 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3730 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3731 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3732 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3733 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3734}
3735
3736/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
3737/// scaled and one unscaled tap.
3738#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3739pub(crate) fn mixed_scale_compound_hits() -> usize {
3740 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
3741}
3742
3743/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
3744/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
3745/// instead because their reference is scaled (libaom `motion_mode_allowed`,
3746/// `blockd.h:1484`).
3747#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3748pub(crate) fn scaled_warp_suppressed_hits() -> usize {
3749 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
3750}
3751
3752/// Current value of [`SCALED_COMPOUND_HITS`].
3753#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3754pub(crate) fn scaled_compound_hits() -> usize {
3755 SCALED_COMPOUND_HITS.with(|c| c.get())
3756}
3757
3758/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
3759pub fn scaled_warp_fallback_hits() -> usize {
3760 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
3761}
3762
3763/// Current value of [`SCALED_OBMC_HITS`].
3764#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3765pub(crate) fn scaled_obmc_hits() -> usize {
3766 SCALED_OBMC_HITS.with(|c| c.get())
3767}
3768
3769/// Current value of [`SCALED_INTERINTRA_HITS`].
3770#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3771pub(crate) fn scaled_interintra_hits() -> usize {
3772 SCALED_INTERINTRA_HITS.with(|c| c.get())
3773}
3774
3775/// Current value of [`SCALED_BLOCK8_HITS`].
3776#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3777pub(crate) fn scaled_block8_hits() -> usize {
3778 SCALED_BLOCK8_HITS.with(|c| c.get())
3779}
3780
3781// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
3782// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
3783// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
3784// 8x8-leaf OBMC block apart from a 16x16+ one.
3785thread_local! {
3786 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3787}
3788
3789// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
3790// pair whose two directions differ (`enable_dual_filter` only -- with dual
3791// filter off both directions take the single symbol, so this can never fire).
3792// A gate asserting it proves the stream really carries dual-filter blocks.
3793thread_local! {
3794 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3795}
3796
3797// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
3798// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
3799// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
3800// no-filter sentinel that made a neighbouring OBMC block panic).
3801thread_local! {
3802 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3803}
3804
3805/// Current value of [`DUAL_FILTER_DIFF_HITS`].
3806#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3807pub(crate) fn dual_filter_diff_hits() -> usize {
3808 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
3809}
3810
3811/// Current value of [`COMPOUND8_FILTER_HITS`].
3812#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3813pub(crate) fn compound8_filter_hits() -> usize {
3814 COMPOUND8_FILTER_HITS.with(|c| c.get())
3815}
3816
3817// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
3818// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
3819// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
3820// -- the gate's proof that a fixture really exercises the alphabet this
3821// round changed, even though the block itself still refuses (warp
3822// estimation/filter not ported).
3823thread_local! {
3824 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
3825 const { std::cell::Cell::new(0) };
3826}
3827
3828/// Current value of [`WARP_SELECTED_HITS`].
3829#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3830pub(crate) fn warp_selected_hits() -> usize {
3831 WARP_SELECTED_HITS.with(|c| c.get())
3832}
3833
3834// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
3835// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
3836// into the compound intermediate) rather than translationally -- the
3837// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
3838// really reached [`crate::warp::warp_affine_compound`].
3839thread_local! {
3840 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
3841 const { std::cell::Cell::new(0) };
3842}
3843
3844/// Current value of [`COMPOUND_WARP_HITS`].
3845#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3846pub(crate) fn compound_warp_hits() -> usize {
3847 COMPOUND_WARP_HITS.with(|c| c.get())
3848}
3849
3850// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
3851// arm ([`decode_inter_block8`]) -- that arm predicted both taps
3852// translationally until r3, so a gate needs to tell a warped 8x8 compound
3853// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
3854thread_local! {
3855 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
3856 const { std::cell::Cell::new(0) };
3857}
3858
3859/// Current value of [`COMPOUND_WARP_HITS_8`].
3860#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3861pub(crate) fn compound_warp_hits_8() -> usize {
3862 COMPOUND_WARP_HITS_8.with(|c| c.get())
3863}
3864
3865// lane-gmaffine r1: how many blocks built their prediction from a
3866// SIX-parameter (`AFFINE`) global-motion model through
3867// `crate::warp::global_warp_params` -- the gate's proof that a stream really
3868// carried an AFFINE `global_motion_params` AND that a block was predicted
3869// with it, not merely that the header parsed one.
3870thread_local! {
3871 static AFFINE_GM_HITS: std::cell::Cell<usize> =
3872 const { std::cell::Cell::new(0) };
3873}
3874
3875/// Current value of [`AFFINE_GM_HITS`].
3876#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3877pub(crate) fn affine_gm_hits() -> usize {
3878 AFFINE_GM_HITS.with(|c| c.get())
3879}
3880
3881// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
3882// differently at the block's WIDTH than at libaom's
3883// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
3884// pick the wrong motion_mode alphabet.
3885thread_local! {
3886 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3887}
3888
3889/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
3890pub fn tr_reach_longer_side_hits() -> usize {
3891 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
3892}
3893
3894// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
3895// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
3896// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
3897// reads its interp-filter symbol. Counts the blocks where that guard flips
3898// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
3899// and a 4-px side, which we used to suppress the interp read on (a pre-mode
3900// entropy desync one symbol wide).
3901thread_local! {
3902 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3903}
3904
3905/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
3906pub fn gm_nontrans_small_side_hits() -> usize {
3907 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
3908}
3909
3910// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
3911// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
3912// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
3913// only once `find_projection` returned a usable model, unlike
3914// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
3915// proof that the leaf path itself fired, not the 16x16+ one.
3916thread_local! {
3917 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3918 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3919}
3920
3921/// Current value of [`GLOBALMV_HITS_8`].
3922#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3923pub(crate) fn globalmv_hits_8() -> usize {
3924 GLOBALMV_HITS_8.with(|c| c.get())
3925}
3926
3927/// Current value of [`WARP_HITS_8`].
3928#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3929pub(crate) fn warp_hits_8() -> usize {
3930 WARP_HITS_8.with(|c| c.get())
3931}
3932
3933// How many blocks decoded `interintra == 1` with the non-wedge blended
3934// prediction applied (lane-interintra r1) -- the gate's proof that a
3935// stream actually exercised interintra.
3936thread_local! {
3937 static INTERINTRA_HITS: std::cell::Cell<usize> =
3938 const { std::cell::Cell::new(0) };
3939}
3940
3941/// Current value of [`INTERINTRA_HITS`].
3942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3943pub(crate) fn interintra_hits() -> usize {
3944 INTERINTRA_HITS.with(|c| c.get())
3945}
3946
3947// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
3948// -- the shape `interintra_blend` used to build a square `side x side` intra
3949// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
3950// pre-existing interintra gate passed with that bug, so the rect arm needs
3951// its own counter to stop being vacuous.
3952thread_local! {
3953 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3954}
3955
3956/// Current value of [`INTERINTRA_RECT_HITS`].
3957pub fn interintra_rect_hits() -> usize {
3958 INTERINTRA_RECT_HITS.with(|c| c.get())
3959}
3960
3961// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
3962// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
3963// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
3964// gate fixture actually exercises this alphabet, even though the block
3965// still refuses (the mask blend itself is unported).
3966thread_local! {
3967 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3968 const { std::cell::Cell::new(0) };
3969}
3970
3971/// Current value of [`MASKED_COMPOUND_HITS`].
3972#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3973pub(crate) fn masked_compound_hits() -> usize {
3974 MASKED_COMPOUND_HITS.with(|c| c.get())
3975}
3976
3977// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
3978// masked-compound block whose true footprint is rectangular, i.e. the case
3979// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
3980// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
3981// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
3982thread_local! {
3983 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3984 const { std::cell::Cell::new(0) };
3985}
3986
3987/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
3988#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3989pub(crate) fn rect_masked_compound_hits() -> usize {
3990 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
3991}
3992
3993// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
3994// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
3995// actually exercised the wedge blend, not just the DIFFWTD half of
3996// `MASKED_COMPOUND_HITS`.
3997thread_local! {
3998 static WEDGE_HITS: std::cell::Cell<usize> =
3999 const { std::cell::Cell::new(0) };
4000}
4001
4002/// Current value of [`WEDGE_HITS`].
4003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4004pub(crate) fn wedge_hits() -> usize {
4005 WEDGE_HITS.with(|c| c.get())
4006}
4007
4008// How many blocks decoded a real wedge-INTERINTRA block
4009// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
4010// a gate fixture exercised the wedge blend (fixed sign 0), not just the
4011// smooth arm counted by `INTERINTRA_HITS`.
4012thread_local! {
4013 static WII_HITS: std::cell::Cell<usize> =
4014 const { std::cell::Cell::new(0) };
4015}
4016
4017/// Current value of [`WII_HITS`].
4018#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4019pub(crate) fn wii_hits() -> usize {
4020 WII_HITS.with(|c| c.get())
4021}
4022
4023// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
4024// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
4025// wide <= 32 && high <= 32). The witness that a gate stream really carries a
4026// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
4027// frame carrying one.
4028thread_local! {
4029 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4030}
4031
4032/// Current value of [`NOCFL_UV_MODE_HITS`].
4033#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4034pub(crate) fn nocfl_uv_mode_hits() -> usize {
4035 NOCFL_UV_MODE_HITS.with(|c| c.get())
4036}
4037
4038/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
4039/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
4040pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
4041 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
4042
4043fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
4044 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
4045}
4046
4047// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
4048// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
4049// the rect wedge masks lifted this round actually fired, not just the square
4050// ones already counted by `WEDGE_HITS`/`WII_HITS`.
4051thread_local! {
4052 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4053 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4054}
4055
4056/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4057pub(crate) fn rect_wedge_hits() -> [usize; 6] {
4058 RECT_WEDGE_HITS.with(|c| c.get())
4059}
4060
4061/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4062pub(crate) fn rect_wii_hits() -> [usize; 6] {
4063 RECT_WII_HITS.with(|c| c.get())
4064}
4065
4066// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
4067// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
4068// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
4069// aomdec, neighbour list included).
4070thread_local! {
4071 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4072}
4073
4074/// Current value of [`OBMC_RECT_LEAF_HITS`].
4075pub(crate) fn obmc_rect_leaf_hits() -> usize {
4076 OBMC_RECT_LEAF_HITS.with(|c| c.get())
4077}
4078
4079// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
4080// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
4081// to be read from the pair's FIRST mi, which is a different block and, when
4082// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
4083// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
4084thread_local! {
4085 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4086}
4087
4088/// Current value of [`OBMC_PAIR_FILTER_HITS`].
4089pub(crate) fn obmc_pair_filter_hits() -> usize {
4090 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
4091}
4092
4093// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
4094// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
4095// own side, so a block overhanging the bottom/right still predicts the full
4096// neighbour strip (the destination write is what clips). We used to shrink the
4097// prediction to the visible part, which at 4 chroma rows/cols also swaps the
4098// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
4099thread_local! {
4100 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4101}
4102
4103/// Current value of [`OBMC_EDGE_SPAN_HITS`].
4104#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4105pub(crate) fn obmc_edge_span_hits() -> usize {
4106 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
4107}
4108
4109/// Current value of [`OBMC_HITS_8`].
4110#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4111pub(crate) fn obmc_hits_8() -> usize {
4112 OBMC_HITS_8.with(|c| c.get())
4113}
4114
4115// lane-rectgate r1: how many 32x32 quadrants actually decoded a
4116// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
4117// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
4118// `VERT_B` all still fall into the generic "a partition type this encoder
4119// never writes" refusal below) -- the gate's proof that a free-partition
4120// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
4121// coincidentally never selecting one.
4122thread_local! {
4123 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
4124 const { std::cell::Cell::new(0) };
4125}
4126
4127/// Current value of [`EXTENDED_PARTITION_HITS`].
4128#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4129pub(crate) fn extended_partition_hits() -> usize {
4130 EXTENDED_PARTITION_HITS.with(|c| c.get())
4131}
4132
4133// lane-partitions r1: how many 32x32 quadrants decoded a real
4134// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
4135// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
4136// gate's proof this round's arms actually fired.
4137thread_local! {
4138 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
4139 const { std::cell::Cell::new(0) };
4140}
4141
4142/// Current value of [`RECT_PARTITION_HITS`].
4143#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4144pub(crate) fn rect_partition_hits() -> usize {
4145 RECT_PARTITION_HITS.with(|c| c.get())
4146}
4147
4148// lane-inter8 r1: how many superblocks an inter tile coded as a single
4149// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4150// static content, previously a named refusal).
4151thread_local! {
4152 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4153 /// path decoded as one whole block (its gate's own witness).
4154 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4155 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4156 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4157 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4158}
4159
4160/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4161pub(crate) fn inter_sb128_horz_hits() -> usize {
4162 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4163}
4164
4165/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4166pub(crate) fn inter_sb128_vert_hits() -> usize {
4167 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4168}
4169
4170/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4171pub fn inter_sb128_none_hits() -> usize {
4172 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4173}
4174
4175thread_local! {
4176 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4177 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4178 /// units) -- the gate's witness that the lifted refusal's case fired.
4179 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4180}
4181
4182/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4183pub fn intra_128_in_inter_hits() -> usize {
4184 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4185}
4186
4187thread_local! {
4188 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4189 const { std::cell::Cell::new(0) };
4190}
4191
4192/// Current value of [`INTER_SB_NONE_HITS`].
4193#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4194pub(crate) fn inter_sb_none_hits() -> usize {
4195 INTER_SB_NONE_HITS.with(|c| c.get())
4196}
4197
4198// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4199// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4200// path has always run that loop, so only this counter proves the newly-lifted
4201// alphabet value fired.
4202thread_local! {
4203 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4204 const { std::cell::Cell::new(0) };
4205}
4206
4207/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4208#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4209pub(crate) fn inter_sub16_split_hits() -> usize {
4210 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4211}
4212
4213// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4214// while at least one reference picture was SCALED (superres) -- the counter
4215// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4216thread_local! {
4217 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4218 const { std::cell::Cell::new(0) };
4219}
4220
4221/// Current value of [`SCALED_LEAF8_HITS`].
4222pub fn scaled_leaf8_hits() -> usize {
4223 SCALED_LEAF8_HITS.with(|c| c.get())
4224}
4225
4226// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4227// rect pair) were predicted from a SCALED reference -- the counter behind the
4228// lifted "sub-8x8 inter block under a scaled reference" refusal.
4229thread_local! {
4230 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4231 const { std::cell::Cell::new(0) };
4232}
4233
4234/// Current value of [`SCALED_SUB8_HITS`].
4235pub fn scaled_sub8_hits() -> usize {
4236 SCALED_SUB8_HITS.with(|c| c.get())
4237}
4238
4239// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4240// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4241// rect coefficient reader itself fired, not just the strip-level partition
4242// symbol [`RECT_PARTITION_HITS`] already counts.
4243thread_local! {
4244 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4245 const { std::cell::Cell::new(0) };
4246}
4247
4248/// Current value of [`RECT_COEFF_HITS`].
4249#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4250pub(crate) fn rect_coeff_hits() -> usize {
4251 RECT_COEFF_HITS.with(|c| c.get())
4252}
4253
4254// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4255// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4256// charter's real-aomenc gate hard-asserts.
4257thread_local! {
4258 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4259 const { std::cell::Cell::new(0) };
4260}
4261
4262/// Current value of [`RECT_LEAF_COEFF_HITS`].
4263#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4264pub(crate) fn rect_leaf_coeff_hits() -> usize {
4265 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4266}
4267
4268// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4269// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4270// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4271// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4272// needs rectangular intra prediction" before this round.
4273thread_local! {
4274 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4275 const { std::cell::Cell::new([0; 3]) };
4276}
4277
4278/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4279/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4280#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4281pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4282 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4283}
4284
4285// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4286// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4287// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4288// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4289// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4290// a single counter cannot tell an axis swap from a working arm
4291// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4292thread_local! {
4293 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4294 const { std::cell::Cell::new([0; 2]) };
4295}
4296
4297/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4298/// (0 = 64x32, 1 = 32x64).
4299pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4300 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4301}
4302
4303// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4304// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4305// is never incremented) -- the gate's proof that the lifted path ran per depth.
4306thread_local! {
4307 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4308 const { std::cell::Cell::new([0; 3]) };
4309}
4310
4311// lane-t900 r21: rect intra strips inside an inter frame that read the
4312// screen-content palette syntax (`allow_screen_content_tools` set and the
4313// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4314// refusal used to guard, so this counter is what keeps its witness gate
4315// non-vacuous.
4316thread_local! {
4317 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4318}
4319
4320/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4321#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4322pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4323 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4324}
4325
4326/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4327#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4328pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4329 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4330}
4331
4332/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4333#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4334pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4335 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4336}
4337
4338// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
4339// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
4340// the blocks the key frame's deblock-grid approximation used to mis-read.
4341thread_local! {
4342 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
4343 const { std::cell::Cell::new(0) };
4344}
4345
4346/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
4347#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4348pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
4349 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
4350}
4351
4352// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4353// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4354// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4355// rect strip on the inter block path" before this round.
4356thread_local! {
4357 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4358 const { std::cell::Cell::new([0; 4]) };
4359}
4360
4361/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4362/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4363pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4364 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4365}
4366
4367// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4368// through one of the key-frame rect readers ([`decode_block_rect4`],
4369// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4370// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4371// already read by [`decode_inter_block`] and (b) the luma mode comes off
4372// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4373// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4374
4375// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4376// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4377// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4378// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4379thread_local! {
4380 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4381 const { std::cell::Cell::new(0) };
4382}
4383
4384/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4385#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4386pub(crate) fn mode_mi_override_hits() -> usize {
4387 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4388}
4389
4390// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4391// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4392// mode from the previous tile, where libaom's `up_available`/`left_available`
4393// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4394// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4395// per superblock row in `start_row`, so the luma fallback cannot leak the way
4396// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4397// the invariant that makes the coarse fallback safe.
4398thread_local! {
4399 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4400 const { std::cell::Cell::new(0) };
4401}
4402
4403/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4404#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4405pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4406 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4407}
4408
4409// lane-cfl r1: how many times a chroma intra-edge filter-type read
4410// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4411// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4412// r1 defect would have filtered a chroma edge with the wrong strength.
4413thread_local! {
4414 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4415 const { std::cell::Cell::new(0) };
4416}
4417
4418/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4419#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4420pub(crate) fn uv_mode_mi_override_hits() -> usize {
4421 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4422}
4423
4424// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4425// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4426// answered differently -- the sub-8x8 pair case where the pair's own first
4427// half had already overwritten the column slot the chroma-ref half reads.
4428thread_local! {
4429 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4430 const { std::cell::Cell::new(0) };
4431}
4432
4433/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4434pub fn uv_mode_grid_override_hits() -> usize {
4435 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4436}
4437
4438// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4439// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4440// from an earlier block in that pixel row/column while the mi-exact map --
4441// which an inter block only started writing this round -- correctly says the
4442// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4443// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4444thread_local! {
4445 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4446 const { std::cell::Cell::new(0) };
4447}
4448
4449/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4450#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4451pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4452 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4453}
4454
4455// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4456// suppressed at a TILE edge that is not a frame edge -- the above/left
4457// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4458// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4459// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4460// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4461// above would decide this tile's chroma edge filter strength.
4462thread_local! {
4463 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4464 const { std::cell::Cell::new(0) };
4465}
4466
4467/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4468#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4469pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4470 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4471}
4472
4473// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4474// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4475// shapes the r1 chroma defect showed up on.
4476thread_local! {
4477 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4478 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4479}
4480
4481/// Current value of [`CFL_BLOCK_HITS`].
4482#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4483pub(crate) fn cfl_block_hits() -> usize {
4484 CFL_BLOCK_HITS.with(|c| c.get())
4485}
4486
4487/// Current value of [`UV_ANGLE_DELTA_HITS`].
4488#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4489pub(crate) fn uv_angle_delta_hits() -> usize {
4490 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4491}
4492
4493// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4494// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4495// gate's proof this round's arms actually reached a real block, not just
4496// that `partition_w64` read one of those two symbol values.
4497thread_local! {
4498 static SB_RECT_HITS: std::cell::Cell<usize> =
4499 const { std::cell::Cell::new(0) };
4500}
4501
4502// Current value of [`SB_RECT_HITS`].
4503// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4504// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4505// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4506// non-SPLIT edge arm actually decoded (before this round the bit was read and
4507// thrown away, so that arm was unreachable).
4508thread_local! {
4509 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4510}
4511
4512/// Current value of [`EDGE_PART_HITS`].
4513#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4514pub(crate) fn edge_part_hits() -> [usize; 4] {
4515 EDGE_PART_HITS.with(|c| c.get())
4516}
4517
4518/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4520pub(crate) fn reset_edge_part_hits() {
4521 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4522}
4523
4524fn bump_edge_part(slot: usize) {
4525 hit_do! {
4526 EDGE_PART_HITS.with(|c| {
4527 let mut h = c.get();
4528 h[slot] += 1;
4529 c.set(h);
4530 });
4531 }
4532}
4533
4534#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4535pub(crate) fn sb_rect_hits() -> usize {
4536 SB_RECT_HITS.with(|c| c.get())
4537}
4538
4539// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4540// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4541// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4542// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4543// paths (intra and inter) feed the same counter.
4544//
4545// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4546// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4547// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4548// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4549// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4550// every SB of the last row), so the 32-level slots stay 0 on that content and
4551// only these prove the arm fired.
4552thread_local! {
4553 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4554 const { std::cell::Cell::new([0; 8]) };
4555}
4556
4557/// Current value of [`EDGE32_HITS`].
4558#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4559pub(crate) fn edge32_hits() -> [usize; 8] {
4560 EDGE32_HITS.with(|c| c.get())
4561}
4562
4563/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4564/// reads are `if`-conditions, so the counter has to ride the expression.
4565fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4566 bump_edge32(base + bit.min(1));
4567 bit
4568}
4569
4570fn bump_edge32(slot: usize) {
4571 hit_do! {
4572 EDGE32_HITS.with(|c| {
4573 let mut h = c.get();
4574 h[slot] += 1;
4575 c.set(h)
4576 });
4577 }
4578}
4579
4580// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4581// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4582// strip) fired. Real aomenc picks these at 64 even with
4583// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4584// the counter the gate hard-asserts.
4585thread_local! {
4586 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4587 const { std::cell::Cell::new([0; 4]) };
4588}
4589
4590/// Current value of [`SB_AB_HITS`], summed over the four arms.
4591#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4592pub(crate) fn sb_ab_hits() -> usize {
4593 SB_AB_HITS.with(|c| c.get().iter().sum())
4594}
4595
4596/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4597/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4598/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4599/// proof of all four.
4600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4601pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4602 SB_AB_HITS.with(std::cell::Cell::get)
4603}
4604
4605// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4606// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4607// strips). Two counters, not one, because a gate that only proved "some 1:4
4608// strip fired" would pass on a stream that never coded the other axis, and
4609// every scan/context table this round added comes in a transposed pair.
4610thread_local! {
4611 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4612 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4613}
4614
4615/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4616#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4617pub(crate) fn sb_rect4_horz_hits() -> usize {
4618 SB_RECT4_HORZ_HITS.with(|c| c.get())
4619}
4620
4621/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4622#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4623pub(crate) fn sb_rect4_vert_hits() -> usize {
4624 SB_RECT4_VERT_HITS.with(|c| c.get())
4625}
4626
4627// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4628// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4629// strips), the arms the ReelB mid-film extract stops at.
4630thread_local! {
4631 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4632 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4633 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4634 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4635 /// `PARTITION_VERT_4`.
4636 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4637 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4638 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4639 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4640 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4641 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4642 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4643 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4644}
4645
4646// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4647// a gate that only counted strips would pass on an all-skip stream, which
4648// exercises none of the new scan/context tables.
4649thread_local! {
4650 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4651}
4652
4653// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4654// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4655// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4656// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4657// counts the same for a 16x8/8x16 strip below 16x16.
4658thread_local! {
4659 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4660 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4661 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4662}
4663
4664/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4665#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4666pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4667 (
4668 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4669 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4670 )
4671}
4672
4673/// Current value of `SUB16_SPLIT_HITS`.
4674#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4675pub(crate) fn sub16_split_hits() -> usize {
4676 SUB16_SPLIT_HITS.with(|c| c.get())
4677}
4678
4679// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4680// luma transform is SPLIT and which therefore leave through that fn's early
4681// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4682thread_local! {
4683 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4684}
4685
4686/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4687#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4688pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4689 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4690}
4691
4692/// Current value of `RECT4_COEFF_HITS`.
4693pub(crate) fn rect4_coeff_hits() -> usize {
4694 RECT4_COEFF_HITS.with(|c| c.get())
4695}
4696
4697// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4698// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4699// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4700// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4701// asserts the arms it proves separately so a run whose RD only picked one
4702// cannot pass as proof of the others.
4703thread_local! {
4704 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4705}
4706
4707/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4708/// inter frame).
4709pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4710 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4711}
4712
4713// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4714// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4715// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4716// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4717// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4718// arm separately so a run whose RD only picked one cannot pass as proof of
4719// four.
4720thread_local! {
4721 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4722}
4723
4724/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4725/// inter frame).
4726pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4727 AB16_INTER_HITS.with(std::cell::Cell::get)
4728}
4729
4730// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
4731// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
4732// counts the odd strips that close a 4:2:0 chroma pair
4733// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
4734// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
4735// the PREVIOUS strip's own mv/ref/filters -- libaom
4736// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
4737// through `is_sub8x8_inter` (same file, :54).
4738thread_local! {
4739 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4740 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4741 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4742 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4743}
4744
4745// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
4746// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
4747// pair's single 8x4 (4x8) chroma unit for BOTH strips.
4748thread_local! {
4749 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4750 const { std::cell::Cell::new([0; 3]) };
4751}
4752
4753/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
4754/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
4755pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
4756 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
4757 (v[0], v[1], v[2])
4758}
4759
4760/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
4761/// strips, chroma pairs closed, chroma pairs built from two different
4762/// strips' motion vectors)`.
4763pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
4764 (
4765 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
4766 INTER16_VERT4_HITS.with(std::cell::Cell::get),
4767 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
4768 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
4769 )
4770}
4771
4772/// One 16x4 / 4x16 inter strip's chroma situation, handed to
4773/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
4774/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
4775/// that all mean "an ordinary block, chroma of its own".
4776#[derive(Clone, Copy)]
4777pub(crate) struct InterStripChroma {
4778 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
4779 /// read and reconstruct NO chroma at all.
4780 has_chroma: bool,
4781 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
4782 horz: bool,
4783 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
4784 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
4785 /// i.e. the origin of the 8x4 (4x8) chroma transform.
4786 pair_mi: (usize, usize),
4787 /// The previous (even) strip's single-reference MC parameters, `None`
4788 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
4789 /// and the whole chroma block is predicted from THIS strip's mv.
4790 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
4791}
4792
4793 /// The single-reference MC parameters of the inter block that decoded
4794 /// last -- read by the next 1:4 strip to build its pair's chroma.
4795
4796fn bump_ab16_inter(arm: usize) {
4797 hit_do! {
4798 AB16_INTER_HITS.with(|c| {
4799 let mut v = c.get();
4800 v[arm] += 1;
4801 c.set(v);
4802 });
4803 }
4804}
4805
4806// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
4807// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
4808// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
4809thread_local! {
4810 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4811 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4812 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4813 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4814 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4815 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
4816 /// base mi differs from what the strip's own (odd) mi would have said --
4817 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
4818 /// key frame miss by 1. Zero here means a gate never exercised the fix.
4819 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4820 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
4821 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
4822 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4823}
4824
4825/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
4826/// that reconstructed as flat DC before lane-kf1200 r2).
4827pub fn skip_cfl_hits() -> usize {
4828 SKIP_CFL_HITS.with(|c| c.get())
4829}
4830
4831/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
4832/// from the pair's base mi than the strip's own mi would have given.
4833pub fn rect4_16_uv_pair_filt_hits() -> usize {
4834 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
4835}
4836
4837// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
4838// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
4839// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
4840// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
4841// intra-edge filter type must come from the chroma-reference position).
4842thread_local! {
4843 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4844 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4845}
4846
4847/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
4848pub fn reelc_chroma_counters() -> (usize, usize) {
4849 (
4850 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
4851 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
4852 )
4853}
4854
4855/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
4856/// strips, chroma-reference strips, strips with a coded residual, strips
4857/// whose luma transform is split)`.
4858pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
4859 (
4860 RECT4_16_HORZ_HITS.with(|c| c.get()),
4861 RECT4_16_VERT_HITS.with(|c| c.get()),
4862 RECT4_16_CHROMA_HITS.with(|c| c.get()),
4863 RECT4_16_COEFF_HITS.with(|c| c.get()),
4864 RECT4_16_SPLIT_HITS.with(|c| c.get()),
4865 )
4866}
4867
4868/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
4869pub(crate) fn rect4_32_horz_hits() -> usize {
4870 RECT4_32_HORZ_HITS.with(|c| c.get())
4871}
4872
4873/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
4874pub(crate) fn rect4_32_vert_hits() -> usize {
4875 RECT4_32_VERT_HITS.with(|c| c.get())
4876}
4877
4878/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
4879pub(crate) fn rect4_32_horz_inter_hits() -> usize {
4880 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
4881}
4882
4883/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
4884pub(crate) fn rect4_32_vert_inter_hits() -> usize {
4885 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
4886}
4887
4888/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
4889pub(crate) fn inter_sb_horz_hits() -> usize {
4890 INTER_SB_HORZ_HITS.with(|c| c.get())
4891}
4892
4893/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
4894pub(crate) fn inter_sb_vert_hits() -> usize {
4895 INTER_SB_VERT_HITS.with(|c| c.get())
4896}
4897
4898/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
4899pub(crate) fn inter_sb_horz4_hits() -> usize {
4900 INTER_SB_HORZ4_HITS.with(|c| c.get())
4901}
4902
4903/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
4904pub(crate) fn inter_sb_vert4_hits() -> usize {
4905 INTER_SB_VERT4_HITS.with(|c| c.get())
4906}
4907
4908// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
4909// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
4910// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
4911// just inert-compiled. Zero forever on a passing gate means that gate's
4912// stream never carries `delta_q_present=1` through a rect64 block.
4913thread_local! {
4914 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
4915 const { std::cell::Cell::new(0) };
4916}
4917
4918/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
4919#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4920pub(crate) fn rect64_qidx_drift_hits() -> usize {
4921 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
4922}
4923
4924// lane-partab r1: how many 32x32 quadrants decoded an AB partition
4925// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
4926// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
4927// free-partition gate's proof this round's arms actually fired.
4928thread_local! {
4929 static PARTAB_HITS: std::cell::Cell<usize> =
4930 const { std::cell::Cell::new(0) };
4931}
4932
4933/// Current value of [`PARTAB_HITS`].
4934#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4935pub(crate) fn partab_hits() -> usize {
4936 PARTAB_HITS.with(|c| c.get())
4937}
4938
4939// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
4940// one counter per arm rather than one shared total -- the gate hard-asserts
4941// each of these individually nonzero so a recipe that only ever fires
4942// HORZ_A can't silently stand in for the whole set.
4943thread_local! {
4944 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
4945 const { std::cell::Cell::new(0) };
4946 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
4947 const { std::cell::Cell::new(0) };
4948 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
4949 const { std::cell::Cell::new(0) };
4950 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
4951 const { std::cell::Cell::new(0) };
4952}
4953
4954/// Current value of [`INTRA_HORZ_A_HITS`].
4955#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4956pub(crate) fn intra_horz_a_hits() -> usize {
4957 INTRA_HORZ_A_HITS.with(|c| c.get())
4958}
4959/// Current value of [`INTRA_HORZ_B_HITS`].
4960#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4961pub(crate) fn intra_horz_b_hits() -> usize {
4962 INTRA_HORZ_B_HITS.with(|c| c.get())
4963}
4964/// Current value of [`INTRA_VERT_A_HITS`].
4965#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4966pub(crate) fn intra_vert_a_hits() -> usize {
4967 INTRA_VERT_A_HITS.with(|c| c.get())
4968}
4969/// Current value of [`INTRA_VERT_B_HITS`].
4970#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4971pub(crate) fn intra_vert_b_hits() -> usize {
4972 INTRA_VERT_B_HITS.with(|c| c.get())
4973}
4974
4975// How many [`read_inter_compound_mode`] reads actually happened
4976// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
4977// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
4978// mvstack build), not just that `comp_mode` fired. Still refused right
4979// after (no MV assignment or MC wired), so this only counts attempted
4980// reads.
4981thread_local! {
4982 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
4983 const { std::cell::Cell::new(0) };
4984}
4985
4986/// Current value of [`COMPOUND_MODE_HITS`].
4987#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4988pub(crate) fn compound_mode_hits() -> usize {
4989 COMPOUND_MODE_HITS.with(|c| c.get())
4990}
4991
4992/// How many query blocks folded in at least one temporal MV candidate
4993/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
4994/// temporal-MV gate's own firing counter (lane-av1tmvp).
4995///
4996/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
4997/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
4998/// this file (`decode_inter_block`) still passes `tpl: None` -- this
4999/// counter compiles and the projection math it counts is unit-tested
5000/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
5001/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
5002/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
5003/// against any real stream today. See the module doc on
5004/// `crate::motion_field` and this crate's ledger for the remaining wiring.
5005#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5006pub(crate) fn tmv_hits() -> usize {
5007 crate::mvstack::tmv_hits()
5008}
5009
5010/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
5011/// produced on this thread, the 10-bit inter gate's firing proof.
5012#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5013pub(crate) fn inter_pred_hits() -> usize {
5014 crate::mc::inter_pred_hits()
5015}
5016
5017/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
5018/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
5019/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
5020/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
5021/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
5022/// needs to turn a query block's own resolved `ref_frame` into
5023/// `TplArgs::cur_offset_0` (spec 7.9.3).
5024pub(crate) struct TplFrameArgs<'a> {
5025 pub field: &'a crate::motion_field::TplField,
5026 pub order_hint_bits: u32,
5027 pub order_hint: u32,
5028 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
5029 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
5030 /// frame's own `ref_frame_idx` names for each single reference.
5031 pub ref_order_hints: [u32; 7],
5032}
5033
5034/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
5035/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
5036/// decoded `grid`: every 4x4 unit an inter block covers reads the same
5037/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
5038/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
5039/// exact — every block this crate ever codes is at least 8x8, so no 8x8
5040/// cell straddles two different blocks' values.
5041#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
5042pub(crate) fn build_motion_field(
5043 grid: &MiGrid,
5044 mi_cols: usize,
5045 mi_rows: usize,
5046 order_hint: u32,
5047 order_hint_bits: u32,
5048 ref_order_hints: [u32; 7],
5049 fctx: &FrameCtx,
5050) -> crate::motion_field::MotionField {
5051 let mut field =
5052 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
5053 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
5054 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
5055 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
5056 // referencing one stores only its OTHER side's mv. With
5057 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
5058 // nothing is skipped.
5059 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
5060 // only on the reference frame, so it is 7 table lookups per frame instead
5061 // of two per inter unit.
5062 let other_side: [bool; 8] = std::array::from_fn(|rf| {
5063 let i = rf.wrapping_sub(LAST_FRAME as usize);
5064 order_hint_bits != 0
5065 && i < 7
5066 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
5067 || ref_order_hints[i] == order_hint)
5068 });
5069 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
5070 // capped at 12 bits per component; a longer one is not stored at all.
5071 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
5072 let (cols, rows, cells) = field.cells_mut();
5073 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
5074 // never touch each other (an 8x8 cell lives in one cell row, and mi row
5075 // `row` writes cell row `row / 2`).
5076 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
5077 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
5078 let out = &mut out[(row / 2 - r0) * cols..][..cols];
5079 for col in 0..mi_cols {
5080 let Some(info) = grid.get_frame(row, col) else {
5081 continue;
5082 };
5083 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
5084 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
5085 // so an intra block -- or an inter block whose every slot is on the
5086 // other side / over the limit -- wipes what an earlier block wrote
5087 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
5088 // share a cell).
5089 if !info.is_inter {
5090 out[col / 2] = None;
5091 continue;
5092 }
5093 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
5094 // qualifying one wins -- a compound block stores its second
5095 // reference's mv, never its first (unless the second is on the
5096 // other side or over the limit). Storing slot 0 unconditionally
5097 // put the wrong (mv, ref_frame_offset) pair in every compound
5098 // block's cell, which a later frame's temporal candidate then
5099 // projected with the wrong reference distance.
5100 let mut saved: Option<crate::motion_field::SavedMv> = None;
5101 for (rf, mv) in [
5102 (info.ref_frame, Some(mv32(info.mv))),
5103 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
5104 ] {
5105 let (Some(mv), true) = (mv, rf > 0) else {
5106 continue;
5107 };
5108 if other_side[rf as usize] {
5109 continue;
5110 }
5111 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
5112 continue;
5113 }
5114 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
5115 }
5116 out[col / 2] = saved;
5117 }
5118 }
5119 };
5120 // lane-mf: the whole-frame pass split over the filter pool in cell-row
5121 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
5122 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
5123 let bands = crate::par::bands(rows, crate::par::filter_threads());
5124 if bands.len() <= 1 {
5125 fill(0, rows, cells);
5126 } else {
5127 let shared = crate::par::Shared::new(cells);
5128 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
5129 // SAFETY: cell rows `r0..r1` are this band's alone.
5130 let cells = unsafe { shared.get() };
5131 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
5132 });
5133 }
5134 if crate::envflags::env_flag!("EC_TRACE_TPL") {
5135 eprintln!("EC_TPL_SAVED oh={order_hint}");
5136 for (r, row) in field.occupancy().iter().enumerate() {
5137 eprintln!("EC_TPL_SAVED r{r} {row}");
5138 }
5139 }
5140 field
5141}
5142
5143/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5144/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5145#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5146pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5147 let c = match ref_frame {
5148 LAST2_FRAME => &LAST2_HITS,
5149 LAST3_FRAME => &LAST3_HITS,
5150 GOLDEN_FRAME => &GOLDEN_HITS,
5151 BWDREF_FRAME => &BWDREF_HITS,
5152 ALTREF2_FRAME => &ALTREF2_HITS,
5153 ALTREF_FRAME => &ALTREF_HITS,
5154 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5155 };
5156 c.with(|v| v.get())
5157}
5158
5159 /// The sequence header's `enable_intra_edge_filter`, set once per
5160 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5161 /// own read of it, kept off the call stack (see that function's own doc
5162 /// comment for why) rather than threaded through every `read_plane`/
5163 /// `decode_block`/`decode_leaf8` call between here and there.
5164
5165/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5166///
5167/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5168/// never did -- so an inter frame's intra blocks read whatever value the last
5169/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5170/// harmless (its own key frame sets it first), but a caller that decodes an
5171/// inter frame directly, or a test harness running several streams on one
5172/// thread, inherits a foreign sequence's bit: decode stops being a pure
5173/// function of the bitstream. `decode_stream` now calls this once per stream
5174/// from the sequence header, which covers every frame including inter ones.
5175pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5176 fctx.enable_edge_filter.with(|f| f.set(value));
5177}
5178
5179/// Current value of [`ANGLE_DELTA_HITS`].
5180#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5181pub(crate) fn angle_delta_hits() -> usize {
5182 ANGLE_DELTA_HITS.with(|c| c.get())
5183}
5184
5185/// Current value of [`TX_CLASS1_HITS`].
5186#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5187pub(crate) fn tx_class1_hits() -> usize {
5188 TX_CLASS1_HITS.with(|c| c.get())
5189}
5190
5191// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5192// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5193// bottom) this thread's decode actually reconstructed -- the same
5194// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5195// genuinely exercised the sub-8x8 leaf path rather than every attempt
5196// coincidentally landing on `PARTITION_NONE`.
5197thread_local! {
5198 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5199 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5200 /// sub-blocks (lane-intersub8).
5201 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5202 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5203 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5204 /// `[1] = VERT` (two BLOCK_4X8).
5205 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5206 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5207 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5208 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5209 /// MIXED groups whose chroma reference is INTER while its sibling is
5210 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5211 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5212 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5213 /// so only this cell separates the split arm from the HORZ/VERT one).
5214 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5215}
5216
5217/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5218/// mixed groups, split 4x4 leaves)`.
5219pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5220 SUB8_INTRA_RECT_HITS.with(|c| {
5221 let h = c.get();
5222 (h[0], h[1], h[2], h[3], h[4])
5223 })
5224}
5225
5226/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5227pub fn sub8_inter_rect_hits() -> (usize, usize) {
5228 SUB8_INTER_RECT_HITS.with(|c| {
5229 let h = c.get();
5230 (h[0], h[1])
5231 })
5232}
5233
5234// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5235// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5236// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5237// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5238// (b) was 0 for every stream before this round -- the leaf path never touched
5239// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5240// filtered where libaom skips it. A gate asserts both are non-zero.
5241thread_local! {
5242 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5243 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5244 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5245 // crosses the cropped frame edge -- the only units for which "clamp at
5246 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5247 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5248 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5249 // whose width or height is not a multiple of 8 is the only shape that
5250 // produces one; the straddling-band gate arms assert it grew.
5251 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5252 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5253 // (see `Neighbours::skip_written`).
5254 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5255 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5256 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5257 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5258 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5259 // 8-tall strip pair where only one half is skip must still be FILTERED.
5260 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5261 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5262}
5263
5264/// Current value of `RECT_SKIP_BAND_HITS`.
5265pub fn rect_skip_band_hits() -> usize {
5266 RECT_SKIP_BAND_HITS.with(|c| c.get())
5267}
5268
5269/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5270pub fn cdef_mixed_skip_units() -> usize {
5271 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5272}
5273
5274/// Current value of `CDEF_SKIPPED_UNITS`.
5275#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5276pub(crate) fn cdef_skipped_units() -> usize {
5277 CDEF_SKIPPED_UNITS.with(|c| c.get())
5278}
5279
5280/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5281/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5282pub fn cdef_unwritten_skip_units() -> usize {
5283 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5284}
5285
5286/// Current value of `INTER8_SKIP_BAND_HITS`.
5287#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5288pub(crate) fn inter8_skip_band_hits() -> usize {
5289 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5290}
5291
5292/// Current value of `CDEF_STRADDLE_UNITS`.
5293#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5294pub(crate) fn cdef_straddle_units() -> usize {
5295 CDEF_STRADDLE_UNITS.with(|c| c.get())
5296}
5297
5298/// Current value of [`SUB8_SPLIT_HITS`].
5299#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5300pub(crate) fn sub8_split_hits() -> usize {
5301 SUB8_SPLIT_HITS.with(|c| c.get())
5302}
5303
5304/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5305pub fn sub8_inter_split_hits() -> usize {
5306 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5307}
5308
5309// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5310// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5311// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5312// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5313// first sub-block's type is never the one). Reading it off sub-block 0
5314// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5315// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5316// see this rule through this counter.
5317thread_local! {
5318 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5319}
5320
5321/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5322pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5323 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5324}
5325
5326fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5327 if coeffs && first_sub != chroma_ref {
5328 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5329 }
5330}
5331
5332// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5333// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5334// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5335// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5336// asserts on these two rather than a plain leaf count.
5337thread_local! {
5338 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5339 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5340 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5341 /// two 4x4 transform units, predicted one after the other. A separate
5342 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5343 /// the gate can prove THIS path fired.
5344 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5345 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5346 /// own width (above-right) or height (below-left) -- the samples
5347 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5348 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5349 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5350 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5351 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5352 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5353}
5354
5355/// Current value of [`RECT8_SPLIT_TX_HITS`].
5356#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5357pub(crate) fn rect8_split_tx_hits() -> usize {
5358 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5359}
5360
5361/// Current value of [`RECT_STRIP_PRED_HITS`].
5362#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5363pub(crate) fn rect_strip_pred_hits() -> usize {
5364 RECT_STRIP_PRED_HITS.with(|c| c.get())
5365}
5366
5367/// Current value of [`RECT_STRIP_REACH_HITS`].
5368#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5369pub(crate) fn rect_strip_reach_hits() -> usize {
5370 RECT_STRIP_REACH_HITS.with(|c| c.get())
5371}
5372
5373/// Current value of [`TX4X8_CODED_HITS`].
5374#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5375pub(crate) fn tx4x8_coded_hits() -> usize {
5376 TX4X8_CODED_HITS.with(|c| c.get())
5377}
5378
5379/// Current value of [`TX8X4_CODED_HITS`].
5380#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5381pub(crate) fn tx8x4_coded_hits() -> usize {
5382 TX8X4_CODED_HITS.with(|c| c.get())
5383}
5384
5385// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5386// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5387// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5388// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5389// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5390// (`eob_pt_{16,64,128,256}_chroma_class1`).
5391thread_local! {
5392 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5393 const { std::cell::Cell::new(0) };
5394}
5395
5396/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5397#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5398pub(crate) fn chroma_eob_class1_hits() -> usize {
5399 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5400}
5401
5402/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5403/// `tx_type` put this block's `eob_pt` on the class-1 row.
5404fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5405 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5406 hit!(CHROMA_EOB_CLASS1_HITS);
5407 }
5408}
5409
5410const SUB_MI: u32 = 4;
5411const MI: usize = 4;
5412const SB: usize = 64;
5413/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5414/// (tile start, superblock-row start).
5415///
5416/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5417/// `av1_get_partition_plane_context` reads its own zero-initialised
5418/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5419/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5420/// (64), which reads identically at every level up to 64x64 but sets the bit
5421/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5422/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5423/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5424const NO_NEIGHBOUR_SIDE: usize = 128;
5425const BLOCK: usize = 32;
5426const SUB: usize = 16;
5427const TX32: usize = 32;
5428const TX16: usize = 16;
5429const TX8: usize = 8;
5430const TX4: usize = 4;
5431const DC_PRED: usize = 0;
5432/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5433/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5434/// constant.
5435const V_PRED: usize = 1;
5436const H_PRED: usize = 2;
5437/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
5438/// `Fimode_To_Intradir`, libaom `blockd.h`).
5439const D157_PRED: usize = 6;
5440/// The last directional mode, `D67_PRED`.
5441const D67_PRED: usize = 8;
5442/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
5443/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
5444/// codes anything else, so this decoder never reads anything else either.
5445const ANGLE_DELTA_ZERO: usize = 3;
5446const NUM_BASE_LEVELS: i32 = 2;
5447const COEFF_BASE_RANGE: i32 = 12;
5448const BR_STEP: i32 = 3;
5449const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
5450
5451/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
5452/// whose probability mass a superblock or block half outside the frame
5453/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
5454/// duplicated here (that module is another lane's territory this round) and
5455/// kept in step with it by the byte-exact round-trip tests below rather than
5456/// by sharing code.
5457const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
5458const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
5459
5460fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
5461 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5462 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
5463 }
5464}
5465
5466fn element_prob(cdf: &[u16], element: usize) -> u16 {
5467 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5468}
5469
5470/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5471/// with: the mass of `elements` becomes the probability of the one partition
5472/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5473/// (the encoder's non-adapting counterpart to this read).
5474fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5475 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5476 [32768 - split, 32768, 0]
5477}
5478
5479fn unsupported(what: impl Into<String>) -> Error {
5480 Error::unsupported("AV1 tile", what.into())
5481}
5482
5483/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5484/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5485/// same rule.
5486pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5487 match base_q_idx {
5488 0..=20 => 0,
5489 21..=60 => 1,
5490 61..=120 => 2,
5491 _ => 3,
5492 }
5493}
5494
5495/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5496/// [`crate::tile`]'s writer generates its scan tables with.
5497fn default_scan(side: usize) -> &'static [u16] {
5498 // One table per transform side (4/8/16/32), built once: this used to be a
5499 // fresh heap allocation plus the whole anti-diagonal walk on every
5500 // transform block read.
5501 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5502 [
5503 default_scan_gen(4),
5504 default_scan_gen(8),
5505 default_scan_gen(16),
5506 default_scan_gen(32),
5507 ]
5508 });
5509 assert!(
5510 matches!(side, 4 | 8 | 16 | 32),
5511 "no default scan for a {side}-point transform"
5512 );
5513 &SCANS[side.trailing_zeros() as usize - 2]
5514}
5515
5516fn default_scan_gen(side: usize) -> Vec<u16> {
5517 let mut scan = Vec::with_capacity(side * side);
5518 for d in 0..(2 * side - 1) {
5519 let lo = d.saturating_sub(side - 1);
5520 let hi = d.min(side - 1);
5521 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5522 if d % 2 == 0 {
5523 scan.extend(diagonal.rev());
5524 } else {
5525 scan.extend(diagonal);
5526 }
5527 }
5528 scan
5529}
5530
5531/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5532/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5533/// in, instead of the default zigzag. libaom's own tables are keyed by a
5534/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5535/// physically column-major level buffer, but they decompose to the exact
5536/// same (row, col) walk as a flat row-major traversal of *our* row-major
5537/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5538/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5539/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5540/// transposed (column 0 down every row, then column 1, ...).
5541pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5542 class_scan_table_wh(side, side, class)
5543}
5544
5545/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5546/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5547/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5548/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5549/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5550/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5551fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5552 match class {
5553 TxClass::Vert => (0..(w * h) as u16).collect(),
5554 TxClass::Horiz => (0..w)
5555 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5556 .collect(),
5557 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5558 }
5559}
5560
5561fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5562 match scan_idx {
5563 0 => 0,
5564 i if i <= area / 8 => 1,
5565 i if i <= area / 4 => 2,
5566 _ => 3,
5567 }
5568}
5569
5570/// One cell of [`read_coeffs`]'s level buffer.
5571///
5572/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
5573/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
5574/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
5575/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
5576/// zero cells instead of needing the `row >= side || col >= side` edge test
5577/// this used to run five times per coefficient. Nothing writes a padding
5578/// cell, so the values are the same zeros the test returned.
5579#[inline]
5580fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5581 grid[row * stride + col] as i32
5582}
5583
5584/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5585/// `txb_common.h`): everything but the two lone-axis-identity types this
5586/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5587#[derive(Clone, Copy, PartialEq, Eq)]
5588pub(crate) enum TxClass {
5589 TwoD,
5590 Horiz,
5591 Vert,
5592}
5593
5594impl TxClass {
5595 pub(crate) fn of(tx_type: TxType) -> Self {
5596 match tx_type {
5597 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5598 // key on axis alone -- FLIPADST is still ADST for this purpose.
5599 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5600 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5601 _ => Self::TwoD,
5602 }
5603 }
5604}
5605
5606/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5607/// table (indexed by the position along the transform's *coded* axis --
5608/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5609/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5610/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5611pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
5612 match i {
5613 0 => 26,
5614 1 => 31,
5615 _ => 36,
5616 }
5617}
5618
5619fn base_ctx(
5620 grid: &[u8],
5621 stride: usize,
5622 row: usize,
5623 col: usize,
5624 class: TxClass,
5625 rect_shape: Option<(usize, usize)>,
5626) -> usize {
5627 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5628 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5629 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5630 // position through the full 1D neighbour sum and offset table. Skipping
5631 // that for every class desynced the last (DC) coefficient of a
5632 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5633 // 0, which then read one extra `BR` symbol at the max and forced a
5634 // spurious third Golomb call).
5635 if class == TxClass::TwoD && row == 0 && col == 0 {
5636 return 0;
5637 }
5638 let offsets: [(usize, usize); 5] = match class {
5639 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5640 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5641 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5642 };
5643 let mag: i32 = offsets
5644 .iter()
5645 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
5646 .sum();
5647 let ctx = ((mag + 1) >> 1).min(4) as usize;
5648 match class {
5649 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5650 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5651 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5652 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5653 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5654 // strip, which own a genuinely different table from the square one
5655 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5656 // square table vs the real ctx 13 the rect table gives).
5657 TxClass::TwoD => {
5658 // lane-rectsplit r4: apply libaom's GENERATING RULE
5659 // (`txb_common.h:199-209`) directly instead of indexing the
5660 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5661 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5662 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5663 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5664 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5665 // transcriptions are `[col][row]` and this read had them as
5666 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5667 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5668 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5669 // pins the rule against the tables over their whole 5x5 domain.
5670 if let Some((w, h)) = rect_shape {
5671 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5672 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
5673 }
5674 if w < h && row < 2 {
5675 return ctx + 11;
5676 }
5677 if w > h && col < 2 {
5678 return ctx + 16;
5679 }
5680 }
5681 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5682 }
5683 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5684 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5685 }
5686}
5687
5688/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
5689/// offsets into the padded level frame (lane-coefread): the tap pattern is a
5690/// function of the tx class alone, which is fixed for a whole transform unit,
5691/// so resolving it once per unit takes the class match and the `(dr, dc)`
5692/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
5693/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
5694/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
5695/// original `(dr, dc)` form.
5696fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
5697 match class {
5698 TxClass::TwoD => (
5699 [stride, 1, stride + 1, 2 * stride, 2],
5700 [stride, 1, stride + 1],
5701 ),
5702 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
5703 TxClass::Vert => (
5704 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
5705 [stride, 1, 2 * stride],
5706 ),
5707 }
5708}
5709
5710/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
5711/// neighbours) + 1) >> 1`, clamped to 4.
5712#[inline(always)]
5713fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
5714 let mut mag = 0u32;
5715 for &t in taps {
5716 mag += u32::from(grid[idx + t]).min(3);
5717 }
5718 (((mag + 1) >> 1) as usize).min(4)
5719}
5720
5721/// [`br_ctx`]'s neighbour sum, off flat taps.
5722#[inline(always)]
5723fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
5724 let mut mag = 0u32;
5725 for &t in taps {
5726 mag += u32::from(grid[idx + t]);
5727 }
5728 (((mag + 1) >> 1) as usize).min(6)
5729}
5730
5731/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
5732/// origin-offset tail the two coefficient readers state inline; kept as the
5733/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
5734/// flat one against.
5735#[cfg(test)]
5736fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
5737 let extra = match class {
5738 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
5739 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
5740 TxClass::Vert => neighbour(grid, stride, row + 2, col),
5741 };
5742 let mag = neighbour(grid, stride, row + 1, col)
5743 + neighbour(grid, stride, row, col + 1)
5744 + extra;
5745 let mag = (((mag + 1) >> 1).min(6)) as usize;
5746 if row == 0 && col == 0 {
5747 return mag;
5748 }
5749 let near_origin = match class {
5750 TxClass::TwoD => row < 2 && col < 2,
5751 TxClass::Horiz => col == 0,
5752 TxClass::Vert => row == 0,
5753 };
5754 if near_origin { mag + 7 } else { mag + 14 }
5755}
5756
5757/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
5758/// transposed from libaom's column-major buffer into this decoder's row-major
5759/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
5760/// against the real table). Not the square zigzag formula generalized to
5761/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
5762const SCAN_32X16: [u16; 512] = [
5763 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
5764 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
5765 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
5766 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
5767 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
5768 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
5769 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
5770 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
5771 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
5772 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
5773 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
5774 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
5775 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
5776 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
5777 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
5778 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
5779 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
5780 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
5781 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
5782 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
5783 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
5784 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
5785 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
5786 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
5787 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
5788 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
5789 509, 478, 447, 510, 479, 511,
5790];
5791
5792/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
5793/// [`SCAN_32X16`]'s doc comment).
5794const SCAN_16X32: [u16; 512] = [
5795 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,
5796 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
5797 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
5798 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
5799 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
5800 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
5801 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
5802 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
5803 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
5804 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
5805 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
5806 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
5807 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
5808 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
5809 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
5810 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
5811 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
5812 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
5813 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
5814 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
5815 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
5816 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
5817 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
5818 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
5819 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
5820 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
5821];
5822
5823/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
5824/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
5825/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
5826/// the same source).
5827const SCAN_4X8: [u16; 32] = [
5828 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,
5829 23, 26, 29, 27, 30, 31,
5830];
5831
5832/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
5833const SCAN_8X4: [u16; 32] = [
5834 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,
5835 29, 22, 15, 30, 23, 31,
5836];
5837
5838/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
5839/// [`SCAN_32X16`]'s doc comment).
5840const SCAN_16X8: [u16; 128] = [
5841 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,
5842 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
5843 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
5844 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
5845 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
5846 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
5847];
5848
5849/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
5850/// [`SCAN_32X16`]'s doc comment).
5851const SCAN_8X16: [u16; 128] = [
5852 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,
5853 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5854 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5855 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5856 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
5857 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
5858];
5859
5860/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
5861/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
5862/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
5863/// scans column-major (`p = col * height + row`), so a naive copy of
5864/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
5865/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
5866/// are byte-identical to this decoder's [`SCAN_8X16`].
5867const SCAN_32X8: [u16; 256] = [
5868 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
5869 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
5870 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
5871 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
5872 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
5873 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
5874 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
5875 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
5876 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
5877 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
5878 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
5879 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
5880 222, 191, 254, 223, 255,
5881];
5882/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
5883/// 16x64 `PARTITION_VERT_4` strip).
5884const SCAN_8X32: [u16; 256] = [
5885 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,
5886 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5887 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5888 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5889 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
5890 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
5891 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
5892 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
5893 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
5894 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
5895 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
5896 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
5897 239, 246, 253, 247, 254, 255,
5898];
5899/// `Default_Scan_16x4`, this decoder's own row-major transcription of
5900/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
5901/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
5902/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
5903/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
5904/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
5905/// were emitted -- a naive copy installs the transpose (class
5906/// reference-layout-not-spec).
5907const SCAN_16X4: [u16; 64] = [
5908 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,
5909 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
5910 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
5911];
5912/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
5913/// 8x32 `PARTITION_VERT_4` strip).
5914const SCAN_4X16: [u16; 64] = [
5915 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,
5916 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
5917 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
5918];
5919
5920/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
5921/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
5922/// padding already holds.
5923#[inline]
5924fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5925 grid[row * stride + col] as i32
5926}
5927
5928/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
5929/// the rect generalization is libaom's own comment in
5930/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
5931/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
5932/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
5933/// [`decode_block_rect`] codes (see that function's own doc comment).
5934fn base_ctx_rect(
5935 grid: &[u8],
5936 stride: usize,
5937 w: usize,
5938 h: usize,
5939 row: usize,
5940 col: usize,
5941 class: TxClass,
5942) -> usize {
5943 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
5944 // the 2D class short-circuits the DC position.
5945 if class == TxClass::TwoD && row == 0 && col == 0 {
5946 return 0;
5947 }
5948 let offsets: [(usize, usize); 5] = match class {
5949 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5950 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5951 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5952 };
5953 let mag: i32 = offsets
5954 .iter()
5955 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
5956 .sum();
5957 let ctx = ((mag + 1) >> 1).min(4) as usize;
5958 match class {
5959 TxClass::TwoD => {
5960 if w < h && row < 2 {
5961 return ctx + 11;
5962 }
5963 if w > h && col < 2 {
5964 return ctx + 16;
5965 }
5966 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5967 }
5968 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
5969 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
5970 // position along one axis only).
5971 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5972 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5973 }
5974}
5975
5976/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
5977/// neighbour-offset math itself is shape-independent, only the boundary
5978/// clamp needs the real bound in each axis.
5979/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
5980/// its body was character-for-character [`br_ctx`]'s, which
5981/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
5982#[cfg(test)]
5983fn br_ctx_rect(
5984 grid: &[u8],
5985 stride: usize,
5986 row: usize,
5987 col: usize,
5988 class: TxClass,
5989) -> usize {
5990 let extra = match class {
5991 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
5992 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
5993 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
5994 };
5995 let mag = neighbour_rect(grid, stride, row + 1, col)
5996 + neighbour_rect(grid, stride, row, col + 1)
5997 + extra;
5998 let mag = (((mag + 1) >> 1).min(6)) as usize;
5999 if row == 0 && col == 0 {
6000 return mag;
6001 }
6002 let near_origin = match class {
6003 TxClass::TwoD => row < 2 && col < 2,
6004 TxClass::Horiz => col == 0,
6005 TxClass::Vert => row == 0,
6006 };
6007 if near_origin { mag + 7 } else { mag + 14 }
6008}
6009
6010fn dc_vote(dc: Option<bool>) -> i32 {
6011 match dc {
6012 None => 0,
6013 Some(true) => -1,
6014 Some(false) => 1,
6015 }
6016}
6017
6018fn dc_sign_ctx(vote: i32) -> usize {
6019 match vote.signum() {
6020 0 => 0,
6021 -1 => 1,
6022 _ => 2,
6023 }
6024}
6025
6026/// The `tx_type` a CDF symbol names, given the width of the row it was read
6027/// from.
6028///
6029/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
6030/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
6031/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
6032/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
6033/// members are a prefix of the five.
6034///
6035/// One function rather than a `match` at each reader, so
6036/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
6037/// tests the mapping the readers actually use.
6038pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
6039 match cdf_len {
6040 17 => TxType::from_symbol_all16(t),
6041 13 => TxType::from_symbol_set2_12(t),
6042 8 => TxType::from_symbol_set1(t),
6043 _ => TxType::from_symbol(t),
6044 }
6045}
6046
6047/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
6048/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
6049/// (class `table-and-reader-move-together` -- the writer picks its symbol
6050/// through the reader's own map, so the two cannot drift).
6051pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
6052 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
6053}
6054
6055/// The remainder of a level the base and base-range syntax could not reach
6056/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
6057/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
6058pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
6059 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
6060 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
6061 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
6062 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
6063 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
6064 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
6065 // stream_can_carry` enumerates that whole value domain.
6066 //
6067 // So this refusal never names a reader gap: it is always the SYMPTOM of an
6068 // earlier desync (class `refusal-hides-a-defect`), and every historical
6069 // instance was closed by fixing that desync -- lane-dgolomb's
6070 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
6071 // Raising the cap only trades a clean refusal for silent corruption:
6072 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
6073 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
6074 // from a refusal into a frame-0 LUMA MISMATCH.
6075 let mut length = 1u32;
6076 while dec.literal(1) == 0 {
6077 length += 1;
6078 if length > 20 {
6079 return Err(unsupported("a Golomb tail longer than this decoder reads"));
6080 }
6081 }
6082 let mut x = 1u32;
6083 for _ in 1..length {
6084 x = (x << 1) | dec.literal(1);
6085 }
6086 Ok(x - 1)
6087}
6088
6089/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
6090/// [`crate::tile`]'s `write_eob`.
6091fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
6092 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6093 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6094
6095 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6096 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
6097 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
6098 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
6099 // `eob_multi_ctx`). Missing that split desynced the very first
6100 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
6101 // against a real aomdec trace).
6102 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6103 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6104 (_, Some(class1)) => class1,
6105 };
6106 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6107 let (range, value) = dec.debug_state();
6108 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
6109 }
6110 let group = dec.symbol(eob_pt) + 1;
6111 if trace {
6112 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
6113 }
6114 let bits = OFFSET_BITS[group];
6115 let mut offset = 0u32;
6116 if bits > 0 {
6117 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
6118 if trace {
6119 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
6120 }
6121 offset = top << (bits - 1);
6122 if bits > 1 {
6123 offset |= dec.literal(bits - 1);
6124 }
6125 }
6126 GROUP_START[group] + offset as usize
6127}
6128
6129/// One transform block's levels, the inverse of [`crate::tile`]'s
6130/// `write_coeffs`, returned as a `side * side` grid in raster order, along
6131/// with the transform type that grid was coded under (`DCT_DCT` when the
6132/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
6133/// 64-point transforms, which never code anything else).
6134///
6135/// # Errors
6136/// Returns an error if the `tx_type` symbol decodes to a value outside its
6137/// CDF's own set (a corrupt or unsupported bitstream) — every value the
6138/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
6139/// produce dispatches to a real inverse transform.
6140/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
6141/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
6142/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
6143/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
6144/// the plane's own predicted mode instead. Every entry this table can
6145/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
6146/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
6147/// table ever names), so unlike the CDF-coded luma path there is no
6148/// ext-tx-set membership check to fall back from here.
6149pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
6150 use crate::intra::{
6151 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
6152 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
6153 };
6154 match mode {
6155 DC_PRED | D45_PRED => TxType::DctDct,
6156 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6157 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6158 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6159 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6160 }
6161}
6162
6163/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6164/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6165/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6166fn is_smooth_mode(mode: usize) -> bool {
6167 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6168}
6169
6170/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6171/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6172/// nine of them inside the base/sign loops pinned nine sets of values in the
6173/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6174/// traffic). Out of line, the loop keeps its values in registers and the
6175/// trace output is character-for-character what it was.
6176#[cold]
6177#[inline(never)]
6178fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6179 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6180}
6181
6182#[cold]
6183#[inline(never)]
6184fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6185 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6186}
6187
6188#[cold]
6189#[inline(never)]
6190fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6191 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6192}
6193
6194#[cold]
6195#[inline(never)]
6196fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6197 let (rng, _) = dec.debug_state();
6198 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6199}
6200
6201#[cold]
6202#[inline(never)]
6203fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6204 let (rng, _) = dec.debug_state();
6205 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6206}
6207
6208#[cold]
6209#[inline(never)]
6210fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6211 let (rng, _) = dec.debug_state();
6212 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6213}
6214
6215#[cold]
6216#[inline(never)]
6217fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6218 let (rng, _) = dec.debug_state();
6219 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6220}
6221
6222#[cold]
6223#[inline(never)]
6224fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6225 let (rng, _) = dec.debug_state();
6226 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6227}
6228
6229fn read_coeffs(
6230 dec: &mut SymbolDecoder,
6231 coding: &mut TxbTables,
6232 scan: &[u16],
6233 skip_ctx: usize,
6234 sign_ctx: usize,
6235 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6236 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6237 // nothing at all; `DctDct` for every luma call and every chroma call at
6238 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6239 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6240 default_tx_type: TxType,
6241 // `Some((w, h))` with `w != h` when this read is a superblock-level
6242 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6243 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6244 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6245 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6246 // caller's block genuinely is `side` x `side`.
6247 rect_shape: Option<(usize, usize)>,
6248) -> Result<(Grid, TxType)> {
6249 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6250 let side = coding.side;
6251 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6252 let (range, value) = dec.debug_state();
6253 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6254 }
6255 let dbg_txbskip = if coeff_trace_on() {
6256 coding.txb_skip[skip_ctx]
6257 } else {
6258 [0; 3]
6259 };
6260 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6261 if coeff_trace_on() {
6262 let (rng, _) = dec.debug_state();
6263 eprintln!(
6264 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6265 coding.side,
6266 all_zero as i32
6267 );
6268 }
6269 if crate::envflags::env_flag!("EC_AV1_TELL") {
6270 eprintln!(
6271 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6272 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6273 );
6274 }
6275 if trace {
6276 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6277 }
6278 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6279 let (range, value) = dec.debug_state();
6280 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6281 }
6282 if all_zero {
6283 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6284 // shared zero grid instead of allocating and zeroing its own.
6285 return Ok((Grid::Zero(side * side), TxType::DctDct));
6286 }
6287 let mut grid = vec![0i32; side * side];
6288 let mut tx_type = default_tx_type;
6289 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6290 // The CDF row's own width names its set (lane-cdffwd2: extended
6291 // past the original two-way intra split once wider `reduced_tx_set
6292 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6293 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6294 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6295 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6296 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6297 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6298 let len = tx_type_cdf.len();
6299 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6300 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6301 }
6302 let t = dec.symbol(tx_type_cdf);
6303 crate::census::tx_type(len, t);
6304 if coeff_trace_on() {
6305 let (rng, _) = dec.debug_state();
6306 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6307 }
6308 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6309 let (range, value) = dec.debug_state();
6310 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6311 }
6312 if trace {
6313 eprintln!("TRACE tx_type value={t} len={len}");
6314 }
6315 tx_type = tx_type_from_symbol(len, t)
6316 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6317 }
6318
6319 let class = TxClass::of(tx_type);
6320 if class != TxClass::TwoD {
6321 hit!(TX_CLASS1_HITS);
6322 hit!(RECT_CLASS1_HITS);
6323 }
6324 let eob = read_eob(dec, coding, class);
6325 if trace {
6326 eprintln!("TRACE eob value={eob}");
6327 }
6328 let ec_trace_coeff = coeff_trace_on();
6329 if ec_trace_coeff {
6330 let (rng, _) = dec.debug_state();
6331 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6332 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6333 }
6334 let class_scan;
6335 let scan: &[u16] = if class == TxClass::TwoD {
6336 scan
6337 } else {
6338 class_scan = class_scan_table(side, class);
6339 &class_scan
6340 };
6341 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6342 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6343 // shift and a mask say the same thing, and the level buffer fits a fixed
6344 // 32x32 frame of stack instead of a heap allocation per transform block.
6345 debug_assert!(side.is_power_of_two() && side <= 32);
6346 let sh = side.trailing_zeros();
6347 let col_mask = side - 1;
6348 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6349 // `stride = side + 4` columns and four spare rows, so the widest read
6350 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6351 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6352 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6353 let stride = side + 4;
6354 let mut levels_buf = [0u8; 36 * 36];
6355 let levels = &mut levels_buf[..stride * stride];
6356 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6357 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6358 // padded frame just to skip the zeros. The base pass already knows both,
6359 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6360 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6361 // pass walks that list in reverse (the base pass runs in reverse scan
6362 // order, so reversing it is forward scan order: the same coefficients, in
6363 // the same order, with the same `c` the trace prints).
6364 let mut nz_buf = [0u16; 1024];
6365 let mut nz_n = 0usize;
6366 let (base_taps, br_taps) = flat_taps(stride, class);
6367 for scan_idx in (0..eob).rev() {
6368 let pos = scan[scan_idx] as usize;
6369 let (row, col) = (pos >> sh, pos & col_mask);
6370 let idx = row * stride + col;
6371 let level = if scan_idx == eob - 1 {
6372 let ctx = eob_coeff_ctx(scan_idx, side * side);
6373 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6374 if trace {
6375 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6376 }
6377 v
6378 } else {
6379 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6380 if row == 0 && col == 0 {
6381 0
6382 } else {
6383 base_mag(levels, idx, &base_taps)
6384 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6385 }
6386 } else {
6387 base_ctx(levels, stride, row, col, class, rect_shape)
6388 };
6389 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6390 if ec_trace_coeff {
6391 // `pos` in libaom's column-major `coeff_idx` convention, so
6392 // the ladder lines up with instrumented `aomdec`.
6393 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6394 }
6395 if trace {
6396 trace_base(scan_idx, pos, row, col, ctx, v);
6397 }
6398 v
6399 };
6400 let level = if level > NUM_BASE_LEVELS {
6401 let ctx = {
6402 let mag = br_mag(levels, idx, &br_taps);
6403 if row == 0 && col == 0 {
6404 mag
6405 } else {
6406 let near_origin = match class {
6407 TxClass::TwoD => row < 2 && col < 2,
6408 TxClass::Horiz => col == 0,
6409 TxClass::Vert => row == 0,
6410 };
6411 if near_origin { mag + 7 } else { mag + 14 }
6412 }
6413 };
6414 let mut level = level;
6415 let mut sent = 0;
6416 loop {
6417 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6418 if ec_trace_coeff {
6419 // lane-leaf8tx r3: the `br` rung was missing from THIS
6420 // path's trace, so the cross-decoder range ladder was
6421 // blind to every base-range symbol and mis-reported the
6422 // first divergence (class [[gate-blind-to-feature]]).
6423 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6424 }
6425 if trace {
6426 trace_br(scan_idx, pos, row, col, ctx, k);
6427 }
6428 level += k;
6429 sent += BR_STEP;
6430 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6431 break;
6432 }
6433 }
6434 level
6435 } else {
6436 level
6437 };
6438 if ec_trace_coeff && scan_idx == eob - 1 {
6439 coeff_step_base_eob_level(dec, level);
6440 }
6441 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
6442 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
6443 // added in the sign pass below, straight into `grid`), so the context
6444 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
6445 // byte gather (lane-coefbuf).
6446 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6447 levels[idx] = level as u8;
6448 if level != 0 {
6449 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6450 nz_n += 1;
6451 }
6452 }
6453 if ec_trace_coeff {
6454 let (rng, _) = dec.debug_state();
6455 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6456 }
6457
6458 for &packed in nz_buf[..nz_n].iter().rev() {
6459 let c = (packed >> 4) as usize;
6460 let pos = scan[c] as usize;
6461 let level = (packed & 15) as i32;
6462 let negative = if pos == 0 {
6463 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
6464 if trace {
6465 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
6466 }
6467 v
6468 } else {
6469 dec.literal(1) == 1
6470 };
6471 if ec_trace_coeff {
6472 coeff_step_sign(dec, c, negative);
6473 }
6474 let level = if level > MAX_BR_LEVEL {
6475 let g = read_golomb(dec)?;
6476 if trace {
6477 eprintln!("TRACE golomb pos={pos} value={g}");
6478 }
6479 level + g as i32
6480 } else {
6481 level
6482 };
6483 if ec_trace_coeff {
6484 coeff_step_post_golomb(dec, c, level);
6485 }
6486 grid[pos] = if negative { -level } else { level };
6487 }
6488 Ok((Grid::Own(grid), tx_type))
6489}
6490
6491/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
6492/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
6493/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
6494/// can ever produce, since every `tx_type` this decoder's rect sets can read
6495/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
6496/// rather than guess-decode if a non-2D class ever shows up here, since
6497/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
6498/// form for those.
6499
6500fn read_coeffs_rect(
6501 dec: &mut SymbolDecoder,
6502 coding: &mut TxbTables,
6503 scan: &[u16],
6504 w: usize,
6505 h: usize,
6506 skip_ctx: usize,
6507 sign_ctx: usize,
6508 default_tx_type: TxType,
6509) -> Result<(Grid, TxType)> {
6510 let rect_trace = coeff_trace_on();
6511 let entry_rng = dec.debug_state().0;
6512 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6513 if rect_trace {
6514 eprintln!(
6515 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
6516 all_zero as i32,
6517 dec.debug_state().0
6518 );
6519 }
6520 if all_zero {
6521 return Ok((Grid::Zero(w * h), TxType::DctDct));
6522 }
6523 let mut grid = vec![0i32; w * h];
6524 hit!(RECT_COEFF_TU_HITS);
6525 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
6526 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
6527 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
6528 // context offsets -- both of which now have rect forms
6529 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
6530 // The rect sets that carry no symbol at all still pass `None` here.
6531 let mut tx_type = default_tx_type;
6532 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6533 let len = tx_type_cdf.len();
6534 let t = dec.symbol(tx_type_cdf);
6535 crate::census::tx_type(len, t);
6536 tx_type = tx_type_from_symbol(len, t)
6537 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6538 if rect_trace {
6539 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
6540 }
6541 }
6542 let class = TxClass::of(tx_type);
6543 if class != TxClass::TwoD {
6544 hit!(TX_CLASS1_HITS);
6545 }
6546 let eob = read_eob(dec, coding, class);
6547 if rect_trace {
6548 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
6549 }
6550 let class_scan;
6551 let scan: &[u16] = if class == TxClass::TwoD {
6552 scan
6553 } else {
6554 class_scan = class_scan_table_wh(w, h, class);
6555 &class_scan
6556 };
6557 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
6558 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
6559 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
6560 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
6561 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
6562 // mask rather than a hardware divide.
6563 let stride = w + 4;
6564 let n = stride * (h + 4);
6565 debug_assert!(w.is_power_of_two() && n <= 36 * 36);
6566 let (mut b96, mut b256, mut b768);
6567 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
6568 let levels: &mut [u8] = if n <= 96 {
6569 b96 = [0u8; 96];
6570 &mut b96[..n]
6571 } else if n <= 256 {
6572 b256 = [0u8; 256];
6573 &mut b256[..n]
6574 } else {
6575 b768 = [0u8; 768];
6576 &mut b768[..n]
6577 };
6578 let wsh = w.trailing_zeros();
6579 let wmask = w - 1;
6580 // lane-coefread: the non-zero list [`read_coeffs`] documents.
6581 let mut nz_buf = [0u16; 1024];
6582 let mut nz_n = 0usize;
6583 let (base_taps, br_taps) = flat_taps(stride, class);
6584 let (wlt, wgt) = (w < h, w > h);
6585 for scan_idx in (0..eob).rev() {
6586 let pos = scan[scan_idx] as usize;
6587 let (row, col) = (pos >> wsh, pos & wmask);
6588 let idx = row * stride + col;
6589 // libaom's column-major `coeff_idx`, for ladder comparison.
6590 let _apos = col * h + row;
6591 let level = if scan_idx == eob - 1 {
6592 let ctx = eob_coeff_ctx(scan_idx, w * h);
6593 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6594 if rect_trace {
6595 eprintln!(
6596 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6597 dec.debug_state().0
6598 );
6599 }
6600 v
6601 } else {
6602 let ctx = if class == TxClass::TwoD {
6603 if row == 0 && col == 0 {
6604 0
6605 } else {
6606 let m = base_mag(levels, idx, &base_taps);
6607 if wlt && row < 2 {
6608 m + 11
6609 } else if wgt && col < 2 {
6610 m + 16
6611 } else {
6612 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6613 }
6614 }
6615 } else {
6616 base_ctx_rect(levels, stride, w, h, row, col, class)
6617 };
6618 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6619 if rect_trace {
6620 eprintln!(
6621 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6622 dec.debug_state().0
6623 );
6624 }
6625 v
6626 };
6627 let level = if level > NUM_BASE_LEVELS {
6628 let ctx = {
6629 let mag = br_mag(levels, idx, &br_taps);
6630 if row == 0 && col == 0 {
6631 mag
6632 } else {
6633 let near_origin = match class {
6634 TxClass::TwoD => row < 2 && col < 2,
6635 TxClass::Horiz => col == 0,
6636 TxClass::Vert => row == 0,
6637 };
6638 if near_origin { mag + 7 } else { mag + 14 }
6639 }
6640 };
6641 let mut level = level;
6642 let mut sent = 0;
6643 loop {
6644 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6645 if rect_trace {
6646 eprintln!(
6647 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
6648 dec.debug_state().0
6649 );
6650 }
6651 level += k;
6652 sent += BR_STEP;
6653 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6654 break;
6655 }
6656 }
6657 level
6658 } else {
6659 level
6660 };
6661 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6662 levels[idx] = level as u8;
6663 if level != 0 {
6664 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6665 nz_n += 1;
6666 }
6667 if rect_trace {
6668 let (rng, _) = dec.debug_state();
6669 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
6670 }
6671 }
6672 if rect_trace {
6673 let (rng, _) = dec.debug_state();
6674 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6675 }
6676 for &packed in nz_buf[..nz_n].iter().rev() {
6677 let pos = scan[(packed >> 4) as usize] as usize;
6678 let level = (packed & 15) as i32;
6679 let negative = if pos == 0 {
6680 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
6681 } else {
6682 dec.literal(1) == 1
6683 };
6684 if rect_trace {
6685 let (rng, _) = dec.debug_state();
6686 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
6687 }
6688 let level = if level > MAX_BR_LEVEL {
6689 let g = read_golomb(dec)?;
6690 level + g as i32
6691 } else {
6692 level
6693 };
6694 grid[pos] = if negative { -level } else { level };
6695 }
6696 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
6697 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
6698 // grids differ is a reader defect, one whose grids agree is a transform
6699 // defect.
6700 if crate::envflags::env_flag!("EC_DQCOEFF") {
6701 let nz: Vec<String> = grid
6702 .iter()
6703 .enumerate()
6704 .filter(|&(_, &v)| v != 0)
6705 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
6706 .collect();
6707 eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(","));
6708 }
6709 Ok((Grid::Own(grid), tx_type))
6710}
6711
6712/// What one coded block leaves behind for the blocks that read it as a
6713/// neighbour: whether it coded anything at all, and the sign of its DC —
6714/// [`crate::tile`]'s own private `Neighbour`.
6715#[derive(Clone, Copy, Default)]
6716struct Neighbour {
6717 /// The transform unit's cumulative coefficient level (spec `cul_level`,
6718 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
6719 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
6720 /// boolean (`level != 0`) is enough for every context this decoder read
6721 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
6722 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
6723 /// needs the actual magnitude tier of its above/left neighbours, not
6724 /// just whether they coded anything.
6725 level: u8,
6726 dc: Option<bool>,
6727}
6728
6729/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
6730/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
6731/// grid is dropped, never a panic. One `memset` per grid row instead of a
6732/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
6733/// is contiguous, so this writes exactly the cells the cell loop did,
6734/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
6735/// next row.
6736#[inline]
6737fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
6738 let end = (start + n).min(dst.len());
6739 if start < end {
6740 dst[start..end].fill(v);
6741 }
6742}
6743
6744fn neighbour_state(grid: &[i32]) -> Neighbour {
6745 // lane-coefgrid: the shared zero grid sums to zero by construction; this
6746 // sum has no early exit, so the 60% of units that code nothing used to
6747 // walk their whole grid here.
6748 if is_zero_grid(grid) {
6749 return Neighbour::default();
6750 }
6751 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
6752 Neighbour {
6753 level: cul.min(7) as u8,
6754 dc: (grid[0] != 0).then_some(grid[0] < 0),
6755 }
6756}
6757
6758/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6759/// transform unit smaller than the block it sits in): `top`/`left` are the
6760/// above/left neighbours' magnitude tiers, each already clamped to 4.
6761pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6762 [1, 2, 2, 2, 3],
6763 [2, 4, 4, 4, 5],
6764 [2, 4, 4, 4, 5],
6765 [2, 4, 4, 4, 5],
6766 [3, 5, 5, 5, 6],
6767];
6768
6769/// The `skip` flag, its written-instrument bit, and the covering coded
6770/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
6771/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
6772/// nothing else, so a block's row is one fill instead of four, and the
6773/// deblocker's `pu_edge` reads origin and dims off one cache line.
6774#[derive(Clone, Copy)]
6775struct BlkCell {
6776 skip: bool,
6777 written: bool,
6778 org: [u16; 2],
6779 dim: [u8; 2],
6780}
6781
6782/// The neighbour state a block's contexts are read from — a duplicate of
6783/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
6784/// territory this round), kept at the same two granularities the real writer
6785/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
6786/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
6787/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
6788/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
6789/// chroma transform straddling the true, odd-sized frame edge see its
6790/// neighbour's state clamped at its own subsampled edge rather than luma's.
6791#[derive(Clone)]
6792struct Neighbours {
6793 above: Vec<[Neighbour; 3]>,
6794 left: Vec<[Neighbour; 3]>,
6795 above_mode: Vec<usize>,
6796 left_mode: Vec<usize>,
6797 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
6798 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
6799 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
6800 /// luma one -- the same block can (and often does) code a different
6801 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
6802 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
6803 /// within-block neighbour finer than this grid) is luma-only -- a known,
6804 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
6805 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
6806 above_uv_mode: Vec<usize>,
6807 left_uv_mode: Vec<usize>,
6808 above_side: Vec<usize>,
6809 left_side: Vec<usize>,
6810 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
6811 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
6812 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
6813 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
6814 /// array cannot tell the second leaf's partition symbol that the first
6815 /// one was coded at 8x8.
6816 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
6817 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
6818 above_side_mi: Vec<u8>,
6819 left_side_mi: Vec<u8>,
6820 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
6821 /// / row, with the mi position it was written at
6822 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
6823 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
6824 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
6825 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
6826 /// leaf whose neighbour is another split group needs that group's leaf 3
6827 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
6828 /// and read only by [`decode_leaf_split4`]; the position guard makes it
6829 /// fall back to the coarse slot whenever the real neighbour was a block
6830 /// of 8x8 or larger (whose one mode is correct for every row it spans).
6831 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
6832 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
6833 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
6834 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
6835 /// frame is 65536 px = 16384 mi).
6836 sub8_mode_col: Vec<(u16, u8)>,
6837 sub8_mode_row: Vec<(u16, u8)>,
6838 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
6839 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
6840 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
6841 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
6842 /// the leaf above writes the same row slot the block to the left owns.
6843 uv_mode_col: Vec<(u16, u8)>,
6844 uv_mode_row: Vec<(u16, u8)>,
6845 /// Every mi cell's own `uv_mode`, the mi grid libaom's
6846 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
6847 /// blockd.h). lane-t900 r12: the one-slot-per-column
6848 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
6849 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
6850 /// overwrote the row the pair's chroma-ref half then wanted to read --
6851 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
6852 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
6853 uv_mode_grid: Vec<u8>,
6854 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
6855 /// every other band here).
6856 uv_grid_cols: usize,
6857 /// Whether the block above/left of this column/row was coded `skip` --
6858 /// an inter frame's own `skip` context (spec `SkipContext`), which the
6859 /// key-frame writer never tracks (its skip context is always zero); a
6860 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
6861 /// `left_skip`.
6862 above_skip: Vec<bool>,
6863 left_skip: Vec<bool>,
6864 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
6865 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
6866 /// pixels last written over each unit by `set_txfm_ctxs`/
6867 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
6868 /// symbol reads its context from (lane-txselect, spec 5.11.17).
6869 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
6870 /// array is exactly libaom's per-superblock-row reset, since each mi row
6871 /// is only ever visited inside one superblock row.
6872 above_txfm: Vec<u8>,
6873 left_txfm: Vec<u8>,
6874 /// Whether the block above/left of this column/row coded `skip_mode`
6875 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
6876 /// lane-av1comp round 14.
6877 above_skip_mode: Vec<bool>,
6878 left_skip_mode: Vec<bool>,
6879 /// Whether the block above/left was coded inter -- the `is_inter`
6880 /// context (spec `av1_get_intra_inter_context`), a duplicate of
6881 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
6882 above_inter: Vec<bool>,
6883 left_inter: Vec<bool>,
6884 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
6885 /// alphabet) the block above/left of this column/row coded, or `-1` for
6886 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
6887 /// functions (`mvstack::ref_ctx` family) need the real reference, not
6888 /// just "was it inter" (lane-av1refs: every inter block used to be
6889 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
6890 /// enough).
6891 above_ref: Vec<i8>,
6892 left_ref: Vec<i8>,
6893 /// The block above/left's *second* reference frame when it was coded
6894 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
6895 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
6896 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
6897 /// `i8`, once a compound `read_ref_frames` lands.
6898 /// lane-publish2 audit: the "always `None` today" note this doc used to
6899 /// carry is long stale -- compound blocks do occur, and
6900 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
6901 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
6902 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
6903 /// [`crate::mvstack::NeighbourRef`] construction (class
6904 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
6905 above_ref1: Vec<Option<i8>>,
6906 left_ref1: Vec<Option<i8>>,
6907 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
6908 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
6909 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
6910 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
6911 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
6912 above_comp_group_idx: Vec<u8>,
6913 left_comp_group_idx: Vec<u8>,
6914 above_compound_idx: Vec<u8>,
6915 left_compound_idx: Vec<u8>,
6916 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
6917 /// `3` = "no info": an intra neighbour or the frame's own border) of the
6918 /// block above/left of this column/row -- spec
6919 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
6920 above_filter: Vec<[u8; 2]>,
6921 left_filter: Vec<[u8; 2]>,
6922 mi_cols: usize,
6923 mi_rows: usize,
6924 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
6925 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
6926 /// 7.15) never filters an 8x8 luma block whose covering coded block read
6927 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
6928 /// grain [`Self::record_mi`] already writes at), read back at 8x8
6929 /// granularity by [`apply_cdef`] since `skip` is constant across every
6930 /// mi cell one coded block covers.
6931 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
6932 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
6933 /// the `skip` bit at this mi cell during this frame. A fresh
6934 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
6935 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
6936 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
6937 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
6938 /// unobservable from the pixels alone. Counted by
6939 /// [`cdef_unwritten_skip_units`].
6940 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
6941 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
6942 /// which re-enables the loop filter at a prediction boundary between two
6943 /// skipped inter blocks (lane-mergefix r4). Written by
6944 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
6945 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
6946 /// that cell -- the other half of `pu_edge`: libaom tests the edge
6947 /// coordinate against the block's size in the FILTERED plane's own
6948 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
6949 blk_grid: Vec<BlkCell>,
6950 skip_grid_cols_mi: usize,
6951 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
6952 /// never splits a coded block's transform below its own size (round 2:
6953 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
6954 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
6955 /// edge-length lookup (`apply_deblock`).
6956 tx_grid: Vec<u8>,
6957 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
6958 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
6959 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
6960 tx_h_grid: Vec<u8>,
6961 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
6962 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
6963 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
6964 /// does NOT follow luma's `tx_depth` split, so deriving it as
6965 /// `tx_grid / 2` invented chroma transform edges the deblocker then
6966 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
6967 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
6968 /// every caller routes through.
6969 uv_tx_grid: Vec<u8>,
6970 uv_tx_h_grid: Vec<u8>,
6971 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
6972 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
6973 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
6974 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
6975 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
6976 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
6977 /// reference onto `LAST_FRAME`'s own delta).
6978 ref_grid: Vec<i8>,
6979 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
6980 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
6981 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
6982 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
6983 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
6984 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
6985 /// to know which mode produced the value.
6986 delta_lf_grid: Vec<[i8; 4]>,
6987 /// The block above/left's own palette-Y size (0 = not a palette block)
6988 /// and its base colours -- `av1_get_palette_mode_ctx`/
6989 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
6990 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
6991 above_palette_size: Vec<u8>,
6992 left_palette_size: Vec<u8>,
6993 above_palette_colors: Vec<[u16; 8]>,
6994 left_palette_colors: Vec<[u16; 8]>,
6995 /// As the four fields above, for the neighbour's own chroma (U-channel
6996 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
6997 /// palette size/colours (lane-palette2 r1).
6998 above_palette_uv_size: Vec<u8>,
6999 left_palette_uv_size: Vec<u8>,
7000 above_palette_uv_colors: Vec<[u16; 8]>,
7001 left_palette_uv_colors: Vec<[u16; 8]>,
7002 /// This tile's own top-left corner, in 4x4 mode-info units (spec
7003 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
7004 /// neighbour" check compares against this instead of literal `0`, since a
7005 /// block at the tile's own top/left edge has no usable neighbour even
7006 /// though a decoded block sits there in the picture (spec `decode_tile`'s
7007 /// per-tile `clear_above_context`/`left_available`/`up_available`).
7008 /// `0` for a single-tile frame, matching every existing caller exactly.
7009 tile_row0_mi: usize,
7010 tile_col0_mi: usize,
7011}
7012
7013#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7014impl Neighbours {
7015 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
7016 /// true (unpadded) size in 4x4 mode-info units.
7017 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
7018 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
7019 // neighbour state over the whole 64-row extent, past the frame's last
7020 // mi row (mi_rows 198, block rows 192..208). libaom's own context
7021 // buffers are superblock-aligned for exactly that reason
7022 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
7023 // side arrays to a superblock multiple and leave those cells unread --
7024 // every availability check uses the true `mi_rows`/`mi_cols` below.
7025 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
7026 let (cols, rows) = (
7027 cols.next_multiple_of(sb_sub),
7028 rows.next_multiple_of(sb_sub),
7029 );
7030 Self {
7031 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
7032 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
7033 above_mode: vec![DC_PRED; cols],
7034 left_mode: vec![DC_PRED; rows],
7035 above_uv_mode: vec![DC_PRED; cols],
7036 left_uv_mode: vec![DC_PRED; rows],
7037 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
7038 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
7039 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
7040 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
7041 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7042 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7043 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7044 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7045 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
7046 uv_grid_cols: cols * (SUB / MI),
7047 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
7048 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
7049 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
7050 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
7051 // 16x16 block beside it, which a SUB-grid slot cannot name
7052 // (class context-read-from-one-cell).
7053 above_skip: vec![false; cols * (SUB / MI)],
7054 left_skip: vec![false; rows * (SUB / MI)],
7055 above_skip_mode: vec![false; cols * (SUB / MI)],
7056 left_skip_mode: vec![false; rows * (SUB / MI)],
7057 above_inter: vec![false; cols * (SUB / MI)],
7058 left_inter: vec![false; rows * (SUB / MI)],
7059 above_ref: vec![-1; cols * (SUB / MI)],
7060 left_ref: vec![-1; rows * (SUB / MI)],
7061 above_ref1: vec![None; cols * (SUB / MI)],
7062 left_ref1: vec![None; rows * (SUB / MI)],
7063 above_comp_group_idx: vec![0; cols * (SUB / MI)],
7064 left_comp_group_idx: vec![0; rows * (SUB / MI)],
7065 above_compound_idx: vec![0; cols * (SUB / MI)],
7066 left_compound_idx: vec![0; rows * (SUB / MI)],
7067 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
7068 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
7069 mi_cols,
7070 mi_rows,
7071 blk_grid: vec![
7072 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
7073 cols * (SUB / MI) * rows * (SUB / MI)
7074 ],
7075 skip_grid_cols_mi: cols * (SUB / MI),
7076 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7077 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7078 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7079 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7080 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
7081 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
7082 above_palette_size: vec![0; cols * (SUB / MI)],
7083 left_palette_size: vec![0; rows * (SUB / MI)],
7084 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7085 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7086 above_palette_uv_size: vec![0; cols * (SUB / MI)],
7087 left_palette_uv_size: vec![0; rows * (SUB / MI)],
7088 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7089 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7090 tile_row0_mi: 0,
7091 tile_col0_mi: 0,
7092 }
7093 }
7094
7095 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
7096 /// tile's own column span (`col1_mi` exclusive), plus recording
7097 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
7098 /// availability check below. Left context resets every superblock row
7099 /// regardless of tile ([`Self::start_row`], already called once per SB
7100 /// row by every caller) so it needs no tile-specific reset here.
7101 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
7102 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
7103 // are tile-relative, same as every other neighbour lookup here.
7104 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
7105 self.tile_row0_mi = row0_mi;
7106 self.tile_col0_mi = col0_mi;
7107 let end = col1_mi.min(self.above.len());
7108 for i in col0_mi.min(end)..end {
7109 self.above[i] = Default::default();
7110 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
7111 }
7112 let (sc0, sc1) = (
7113 col0_mi / (SUB / MI),
7114 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
7115 );
7116 for i in sc0.min(sc1)..sc1 {
7117 self.above_mode[i] = DC_PRED;
7118 self.above_side[i] = NO_NEIGHBOUR_SIDE;
7119 }
7120 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
7121 // the tile's own mi column span directly.
7122 let mend = col1_mi.min(self.above_skip.len());
7123 for i in col0_mi.min(mend)..mend {
7124 self.above_skip[i] = false;
7125 self.above_skip_mode[i] = false;
7126 self.above_inter[i] = false;
7127 self.above_ref[i] = -1;
7128 self.above_ref1[i] = None;
7129 self.above_comp_group_idx[i] = 0;
7130 self.above_compound_idx[i] = 0;
7131 self.above_filter[i] = [3u8; 2];
7132 }
7133 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
7134 // stale `(row, mode)` from the tile to the LEFT names an mi row this
7135 // tile's first block would read as its own above neighbour.
7136 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
7137 for i in col0_mi.min(mcol_end)..mcol_end {
7138 self.sub8_mode_col[i] = (u16::MAX, 0);
7139 self.uv_mode_col[i] = (u16::MAX, 0);
7140 }
7141 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
7142 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
7143 // not zero) -- without it a second tile column reads the first one's
7144 // resolved transform sizes as its own above context.
7145 let tend = col1_mi.min(self.above_txfm.len());
7146 for i in col0_mi.min(tend)..tend {
7147 self.above_txfm[i] = TXFM_CTX_INIT;
7148 }
7149 }
7150
7151 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
7152 /// for a non-palette block, clearing any stale neighbour state) into every
7153 /// [`SUB`]-grid cell it covers on both the above and left edges --
7154 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
7155 /// call sites are all square blocks).
7156 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7157 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
7158 }
7159
7160 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
7161 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
7162 /// [`Self::record`]): a true rect strip's above/left neighbour spans
7163 /// differ.
7164 fn record_palette_y_rect(
7165 &mut self,
7166 mi: (usize, usize),
7167 w: usize,
7168 h: usize,
7169 size: usize,
7170 colors: [u16; 8],
7171 ) {
7172 let (r, c) = mi;
7173 if crate::envflags::env_flag!("EC_PALPUB") {
7174 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7175 }
7176 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7177 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7178 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7179 // old SUB grid let a 16x8 strip pair share one slot, so the second
7180 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7181 // cache came out one entry short (class [[context-read-from-one-cell]]).
7182 for cell in 0..(w / MI).max(1) {
7183 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7184 *e = size as u8;
7185 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7186 // neighbour's colours only where its palette size > 0, so a
7187 // non-palette block need not stamp 16 bytes of zeroes here.
7188 if size > 0 {
7189 self.above_palette_colors[c + cell] = colors;
7190 }
7191 }
7192 }
7193 for cell in 0..(h / MI).max(1) {
7194 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7195 *e = size as u8;
7196 if size > 0 {
7197 self.left_palette_colors[r + cell] = colors;
7198 }
7199 }
7200 }
7201 }
7202
7203 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7204 /// neighbours that are themselves a palette-Y block, plus
7205 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7206 /// cache (pred_common.c:73).
7207 ///
7208 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7209 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7210 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7211 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7212 /// the ctx too made every superblock in the frame's second SB row read
7213 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7214 /// palette block decoded as "no palette" and the tile desynced from
7215 /// there (class [[cdf-row-held-constant]]).
7216 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7217 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7218 }
7219
7220 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7221 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7222 /// drops the above neighbour on a 64-px superblock boundary
7223 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7224 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7225 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7226 /// every strip in an SB's top cell row, which libaom does not do.
7227 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7228 let (r, c) = mi;
7229 let above_ok = r % 16 != 0;
7230 // `xd->above_mbmi` exists for every row but the tile's own first.
7231 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7232 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7233 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7234 } else {
7235 (0, [0u16; 8])
7236 };
7237 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7238 // is NULL whenever the block sits at its TILE's own left column
7239 // (`left_available`), not the frame's -- without this guard a second
7240 // tile column reads the previous tile's palette colours into its cache
7241 // and its `palette_y_mode` ctx.
7242 let left_ok = c > self.tile_col0_mi;
7243 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7244 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7245 } else {
7246 (0, [0u16; 8])
7247 };
7248 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7249 let mut cache = Vec::with_capacity(16);
7250 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7251 if cache.last() != Some(&v) {
7252 cache.push(v);
7253 }
7254 };
7255 let (mut ai, mut li) = (0usize, 0usize);
7256 while ai < above_n && li < left_n {
7257 let (va, vl) = (above_colors[ai], left_colors[li]);
7258 if vl < va {
7259 push_dedup(&mut cache, vl);
7260 li += 1;
7261 } else {
7262 push_dedup(&mut cache, va);
7263 ai += 1;
7264 if vl == va {
7265 li += 1;
7266 }
7267 }
7268 }
7269 while ai < above_n {
7270 push_dedup(&mut cache, above_colors[ai]);
7271 ai += 1;
7272 }
7273 while li < left_n {
7274 push_dedup(&mut cache, left_colors[li]);
7275 li += 1;
7276 }
7277 (ctx, cache)
7278 }
7279
7280 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7281 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7282 /// same way (lane-palette2 r1).
7283 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7284 self.record_palette_uv_rect(
7285 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7286 side,
7287 side,
7288 size,
7289 colors,
7290 );
7291 }
7292
7293 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7294 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7295 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7296 /// luma resolution regardless of which plane the recorded state is for).
7297 fn record_palette_uv_rect(
7298 &mut self,
7299 mi: (usize, usize),
7300 w: usize,
7301 h: usize,
7302 size: usize,
7303 colors: [u16; 8],
7304 ) {
7305 let (r, c) = mi;
7306 // mi granularity, see [`Self::record_palette_y_rect`].
7307 for cell in 0..(w / MI).max(1) {
7308 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7309 *e = size as u8;
7310 if size > 0 {
7311 self.above_palette_uv_colors[c + cell] = colors;
7312 }
7313 }
7314 }
7315 for cell in 0..(h / MI).max(1) {
7316 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7317 *e = size as u8;
7318 if size > 0 {
7319 self.left_palette_uv_colors[r + cell] = colors;
7320 }
7321 }
7322 }
7323 }
7324
7325 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7326 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7327 /// no neighbour lookup at all (it is this block's own just-decided Y
7328 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7329 /// so only the cache is wanted here.
7330 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7331 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7332 }
7333
7334 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7335 /// [`Self::palette_ctx_and_cache_mi`].
7336 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7337 let (r, c) = mi;
7338 let above_ok = r % 16 != 0;
7339 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7340 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7341 } else {
7342 (0, [0u16; 8])
7343 };
7344 // Same tile-relative left availability as the luma cache above.
7345 let left_ok = c > self.tile_col0_mi;
7346 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7347 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7348 } else {
7349 (0, [0u16; 8])
7350 };
7351 let mut cache = Vec::with_capacity(16);
7352 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7353 if cache.last() != Some(&v) {
7354 cache.push(v);
7355 }
7356 };
7357 let (mut ai, mut li) = (0usize, 0usize);
7358 while ai < above_n && li < left_n {
7359 let (va, vl) = (above_colors[ai], left_colors[li]);
7360 if vl < va {
7361 push_dedup(&mut cache, vl);
7362 li += 1;
7363 } else {
7364 push_dedup(&mut cache, va);
7365 ai += 1;
7366 if vl == va {
7367 li += 1;
7368 }
7369 }
7370 }
7371 while ai < above_n {
7372 push_dedup(&mut cache, above_colors[ai]);
7373 ai += 1;
7374 }
7375 while li < left_n {
7376 push_dedup(&mut cache, left_colors[li]);
7377 li += 1;
7378 }
7379 cache
7380 }
7381
7382 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7383 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7384 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7385 /// units as [`Self::fill_skip_grid`].
7386 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7387 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7388 }
7389
7390 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7391 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7392 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7393 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
7394 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
7395 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
7396 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
7397 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
7398 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
7399 /// block's published transform extent to its own size is exactly that
7400 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
7401 /// that needs it is the 128 root, whose chroma extent (64) is the one
7402 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
7403 /// never suppressed (libaom's `is_inter_block` term), so this is called
7404 /// only from the skipped-inter branch.
7405 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
7406 let (mi_r, mi_c) = at_mi;
7407 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
7408 for rr in 0..h_mi {
7409 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7410 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
7411 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
7412 }
7413 }
7414
7415 fn fill_lf_grid_rect(
7416 &mut self,
7417 at_mi: (usize, usize),
7418 w_mi: usize,
7419 h_mi: usize,
7420 tx_px: u8,
7421 tx_h_px: u8,
7422 ref_frame: i8, fctx: &crate::decode::FrameCtx,
7423 ) {
7424 let (mi_r, mi_c) = at_mi;
7425 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
7426 // half its luma one (min 4 px, the smallest transform), capped at
7427 // TX_32X32 -- independent of this block's luma `tx_depth`.
7428 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
7429 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
7430 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7431 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}");
7432 }
7433 crate::census::tx(tx_px, tx_h_px);
7434 let cur = fctx.current_delta_lf.with(|c| c.get());
7435 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
7436 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
7437 } else {
7438 [cur[0].clamp(-63, 63) as i8; 4]
7439 };
7440 for rr in 0..h_mi {
7441 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7442 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7443 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7444 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
7445 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
7446 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
7447 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
7448 }
7449 }
7450
7451 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
7452 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
7453 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
7454 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
7455 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
7456 /// dims from the LEAF span and so invented chroma transform edges the
7457 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
7458 /// are already correct from the block's own fill over the same span.
7459 fn fill_lf_grid_leaf_luma(
7460 &mut self,
7461 at_mi: (usize, usize),
7462 w_mi: usize,
7463 h_mi: usize,
7464 tx_px: u8,
7465 tx_h_px: u8,
7466 ) {
7467 let (mi_r, mi_c) = at_mi;
7468 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7469 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}");
7470 }
7471 for rr in 0..h_mi {
7472 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7473 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7474 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7475 }
7476 }
7477
7478 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
7479 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
7480 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
7481 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
7482 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
7483 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
7484 }
7485
7486 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
7487 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
7488 let (mi_r, mi_c) = at_mi;
7489 if skip && w_mi != h_mi {
7490 hit!(RECT_SKIP_BAND_HITS);
7491 }
7492 // lane-census: an INTRA frame's blocks never reach the inter
7493 // publisher, and this one is what every coded block writes.
7494 crate::census::block_intra_frame(w_mi, h_mi, skip);
7495 for rr in 0..h_mi {
7496 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7497 fill_span(
7498 &mut self.blk_grid,
7499 start,
7500 w_mi,
7501 BlkCell {
7502 skip,
7503 written: true,
7504 org: [mi_r as u16, mi_c as u16],
7505 dim: [w_mi as u8, h_mi as u8],
7506 },
7507 );
7508 }
7509 }
7510
7511 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
7512 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
7513 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
7514 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
7515 /// straddle the region with a mix of skip/non-skip blocks).
7516 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
7517 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
7518 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
7519 /// filtered edge's two sides are each exactly one coded block wide.
7520 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
7521 self.blk_grid
7522 .get(mi_r * self.skip_grid_cols_mi + mi_c)
7523 .is_some_and(|c| c.skip)
7524 }
7525
7526 /// The `skip_txfm` context of a block whose top-left mi cell is
7527 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
7528 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
7529 /// with an absent neighbour contributing 0. The mi grid is per tile, so
7530 /// row/column 0 is a tile edge and has no neighbour on that axis.
7531 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
7532 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
7533 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
7534 }
7535
7536 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
7537 (0..2).all(|rr| {
7538 (0..2).all(|cc| {
7539 self.blk_grid
7540 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
7541 .is_some_and(|c| c.skip)
7542 })
7543 })
7544 }
7545
7546 fn start_row(&mut self) {
7547 self.left.iter_mut().for_each(|l| *l = Default::default());
7548 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
7549 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
7550 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
7551 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
7552 self.left_skip.iter_mut().for_each(|s| *s = false);
7553 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
7554 self.left_inter.iter_mut().for_each(|i| *i = false);
7555 self.left_ref.iter_mut().for_each(|r| *r = -1);
7556 self.left_ref1.iter_mut().for_each(|r| *r = None);
7557 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
7558 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
7559 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
7560 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
7561 // context (a tile/SB-row boundary has no left neighbour).
7562 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7563 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7564 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
7565 // are per-mi maps like every other one here, so they reset with the
7566 // row too -- the left guard above is what actually stops a cross-tile
7567 // read, this keeps a stale colour out of the arrays at all.
7568 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
7569 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7570 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
7571 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7572 // lane-mergefix r2: `av1_zero_left_context` memsets
7573 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
7574 // every superblock row of every tile -- the var-tx left context does
7575 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
7576 // previous tile column's last block otherwise).
7577 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
7578 }
7579
7580 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
7581 /// block that reads it as a neighbour -- [`crate::tile`]'s
7582 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
7583 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
7584 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
7585 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
7586 /// the real value, not just `is_inter`).
7587 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7588 fn record_inter(
7589 &mut self,
7590 at: (usize, usize),
7591 side: usize,
7592 skip: bool,
7593 is_inter: bool,
7594 ref_frame: i8,
7595 filter: [u8; 2],
7596 skip_mode: bool,
7597 ) {
7598 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
7599 }
7600
7601 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
7602 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
7603 /// r1: a true rectangular strip's above-context span (its own width) and
7604 /// left-context span (its own height) differ, unlike every caller before
7605 /// this round (class neighbour-votes-all-its-fields).
7606 #[allow(clippy::too_many_arguments)]
7607 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7608 fn record_inter_rect(
7609 &mut self,
7610 at: (usize, usize),
7611 w_sub: usize,
7612 h_sub: usize,
7613 skip: bool,
7614 is_inter: bool,
7615 ref_frame: i8,
7616 filter: [u8; 2],
7617 skip_mode: bool,
7618 ) {
7619 let (r, c) = at;
7620 self.record_inter_rect_mi(
7621 (r * (SUB / MI), c * (SUB / MI)),
7622 w_sub / MI,
7623 h_sub / MI,
7624 skip,
7625 is_inter,
7626 ref_frame,
7627 filter,
7628 skip_mode,
7629 );
7630 }
7631
7632 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
7633 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
7634 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
7635 /// routes through the wrapper above.
7636 #[allow(clippy::too_many_arguments)]
7637 fn record_inter_rect_mi(
7638 &mut self,
7639 at_mi: (usize, usize),
7640 w_mi: usize,
7641 h_mi: usize,
7642 skip: bool,
7643 is_inter: bool,
7644 ref_frame: i8,
7645 filter: [u8; 2],
7646 skip_mode: bool,
7647 ) {
7648 let (r, c) = at_mi;
7649 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
7650 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
7651 // writes for a whole block class): an INTER block left the luma mode
7652 // map untouched, so a later intra block's `get_intra_edge_filter_type`
7653 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
7654 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
7655 // block in that pixel row -- the directional edge filter then ran at
7656 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
7657 // which for an inter block is an INTER mode (>= NEARESTMV) and is
7658 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
7659 // already stamped it).
7660 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
7661 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
7662 // uv map must read DC_PRED over an inter block's cells too.
7663 if is_inter {
7664 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7665 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7666 }
7667 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
7668 self.above_skip[c..c + w_mi].fill(skip);
7669 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
7670 self.above_inter[c..c + w_mi].fill(is_inter);
7671 self.above_ref[c..c + w_mi].fill(ref_frame);
7672 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
7673 // this with the block's real second reference for a compound block,
7674 // called right after this one (lane-publish2 audit).
7675 self.above_ref1[c..c + w_mi].fill(None);
7676 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
7677 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
7678 // as `3`/`1` even though this block has no second reference.
7679 // `record_compound_ctx` overwrites this with the real bit for an
7680 // actual compound block's cells, called right after this one.
7681 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
7682 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
7683 self.above_filter[c..c + w_mi].fill(filter);
7684 self.left_skip[r..r + h_mi].fill(skip);
7685 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
7686 self.left_inter[r..r + h_mi].fill(is_inter);
7687 self.left_ref[r..r + h_mi].fill(ref_frame);
7688 self.left_ref1[r..r + h_mi].fill(None);
7689 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
7690 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
7691 self.left_filter[r..r + h_mi].fill(filter);
7692 }
7693
7694 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
7695 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
7696 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
7697 /// `get_comp_index_context`) -- called right after `record_inter` for
7698 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
7699 /// stamps `above_ref1`/`left_ref1` with the block's real second
7700 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
7701 /// this is the one caller that actually knows it) -- so the next block's
7702 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
7703 /// neighbour instead of `record_inter`'s single-ref default.
7704 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7705 fn record_compound_ctx(
7706 &mut self,
7707 at: (usize, usize),
7708 side: usize,
7709 ref1: i8,
7710 comp_group_idx: u8,
7711 compound_idx: u8,
7712 ) {
7713 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
7714 }
7715
7716 /// [`Self::record_compound_ctx`] with independent above/left extents,
7717 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
7718 #[allow(clippy::too_many_arguments)]
7719 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7720 fn record_compound_ctx_rect(
7721 &mut self,
7722 at: (usize, usize),
7723 w_sub: usize,
7724 h_sub: usize,
7725 ref1: i8,
7726 comp_group_idx: u8,
7727 compound_idx: u8,
7728 ) {
7729 let (r, c) = at;
7730 self.record_compound_ctx_rect_mi(
7731 (r * (SUB / MI), c * (SUB / MI)),
7732 w_sub / MI,
7733 h_sub / MI,
7734 ref1,
7735 comp_group_idx,
7736 compound_idx,
7737 );
7738 }
7739
7740 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
7741 /// [`Self::record_inter_rect_mi`]).
7742 fn record_compound_ctx_rect_mi(
7743 &mut self,
7744 at_mi: (usize, usize),
7745 w_mi: usize,
7746 h_mi: usize,
7747 ref1: i8,
7748 comp_group_idx: u8,
7749 compound_idx: u8,
7750 ) {
7751 let (r, c) = at_mi;
7752 crate::census::compound();
7753 for cell in 0..w_mi {
7754 self.above_ref1[c + cell] = Some(ref1);
7755 self.above_comp_group_idx[c + cell] = comp_group_idx;
7756 self.above_compound_idx[c + cell] = compound_idx;
7757 }
7758 for cell in 0..h_mi {
7759 self.left_ref1[r + cell] = Some(ref1);
7760 self.left_comp_group_idx[r + cell] = comp_group_idx;
7761 self.left_compound_idx[r + cell] = compound_idx;
7762 }
7763 }
7764
7765 /// The context of a block's partition symbol: delegates to the mi-precise
7766 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
7767 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
7768 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
7769 /// only touches the finer mi arrays -- leaves them stale for the *next*
7770 /// sibling's own partition symbol.
7771 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
7772 let (r, c) = at;
7773 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
7774 }
7775
7776 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
7777 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
7778 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
7779 /// than the enclosing 16x16 slot's stale, shared state.
7780 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
7781 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
7782 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
7783 }
7784
7785 /// The gathered coded/DC-sign state of the blocks above and to the left
7786 /// of a block `side` samples across, per plane.
7787 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7788 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
7789 }
7790
7791 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
7792 /// units, for the same reason [`Self::record_mi`] does.
7793 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7794 let side_mi = side / MI;
7795 // One pass over the cells accumulating all three planes, not one pass
7796 // per plane: the three planes of a cell live in the same
7797 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
7798 // cache lines three times (lane-publish).
7799 let mut out = [(false, false, 0i32); 3];
7800 for cell in 0..side_mi {
7801 let above = &self.above[mi_c + cell];
7802 let left = &self.left[mi_r + cell];
7803 for (plane, o) in out.iter_mut().enumerate() {
7804 o.0 |= above[plane].level != 0;
7805 o.1 |= left[plane].level != 0;
7806 o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc);
7807 }
7808 }
7809 out
7810 }
7811
7812 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
7813 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
7814 /// extent pattern for a true rectangular strip's own coefficient context.
7815 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7816 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
7817 }
7818
7819 /// [`Self::around_rect`] taking the block's position directly in 4x4
7820 /// mode-info units, mirroring [`Self::around_mi`].
7821 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7822 let (w_mi, h_mi) = (w / MI, h / MI);
7823 // [`Self::around_mi`]'s single pass, with the two extents split.
7824 let mut out = [(false, false, 0i32); 3];
7825 for cell in 0..w_mi {
7826 let above = &self.above[mi_c + cell];
7827 for (plane, o) in out.iter_mut().enumerate() {
7828 o.0 |= above[plane].level != 0;
7829 o.2 += dc_vote(above[plane].dc);
7830 }
7831 }
7832 for cell in 0..h_mi {
7833 let left = &self.left[mi_r + cell];
7834 for (plane, o) in out.iter_mut().enumerate() {
7835 o.1 |= left[plane].level != 0;
7836 o.2 += dc_vote(left[plane].dc);
7837 }
7838 }
7839 if crate::envflags::env_flag!("EC_DCDUMP") {
7840 for (plane, o) in out.iter().enumerate() {
7841 let vote = o.2;
7842 let ab: Vec<String> = (0..w_mi)
7843 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
7844 .collect();
7845 let lf: Vec<String> = (0..h_mi)
7846 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
7847 .collect();
7848 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
7849 }
7850 }
7851 out
7852 }
7853
7854 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
7855 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
7856 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
7857 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
7858 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
7859 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
7860 /// is always 0, spec's `plane_bsize == tx_size` branch).
7861 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
7862 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
7863 }
7864
7865 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
7866 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
7867 /// context over `tx_size_wide` and the left one over `tx_size_high`.
7868 fn luma_skip_ctx_rect(
7869 &self,
7870 (mi_r, mi_c): (usize, usize),
7871 w_mi: usize,
7872 h_mi: usize,
7873 ) -> usize {
7874 let side_mi = w_mi;
7875 let mut top = 0u8;
7876 let mut left = 0u8;
7877 for cell in 0..w_mi {
7878 top |= self.above[mi_c + cell][0].level;
7879 }
7880 for cell in 0..h_mi {
7881 left |= self.left[mi_r + cell][0].level;
7882 }
7883 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
7884 if crate::envflags::env_flag!("EC_ECDUMP") {
7885 let ab: Vec<String> =
7886 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
7887 let lf: Vec<String> =
7888 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
7889 eprintln!(
7890 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
7891 ab.join(","), lf.join(",")
7892 );
7893 }
7894 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7895 eprintln!(
7896 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
7897 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
7898 );
7899 }
7900 ctx
7901 }
7902
7903 /// Writes one coded block into every cell it covers, on both grids: the
7904 /// mode/side arrays up to `side`'s own width, and the coefficient-context
7905 /// arrays up to the true frame edge — the units past it are left at their
7906 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
7907 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
7908 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
7909 /// not from this block's own side).
7910 fn record(
7911 &mut self,
7912 at: (usize, usize),
7913 side: usize,
7914 mode: usize,
7915 uv_mode: usize,
7916 grids: &[&[i32]; 3],
7917 ) {
7918 self.record_rect(at, side, side, mode, uv_mode, grids);
7919 }
7920
7921 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
7922 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
7923 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
7924 /// spec's per-edge partition-context rule, so a true rectangular block
7925 /// naturally wants two different values here rather than one.
7926 /// Writes this block's luma `mode` into the mi-granular
7927 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
7928 /// position a *later* neighbour would read it from: the block's LAST mi
7929 /// row for every column it spans (what the block below reads via
7930 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
7931 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
7932 /// read these back, and only when the recorded position is exactly their
7933 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
7934 fn record_mode_mi(
7935 &mut self,
7936 mi_r: usize,
7937 mi_c: usize,
7938 mi_w: usize,
7939 mi_h: usize,
7940 mode: usize,
7941 ) {
7942 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
7943 let mode = mode as u8;
7944 for cell in 0..mi_w {
7945 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
7946 *slot = (last_r, mode);
7947 }
7948 }
7949 for cell in 0..mi_h {
7950 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
7951 *slot = (last_c, mode);
7952 }
7953 }
7954 }
7955
7956 /// The mi-exact above/left neighbour luma mode for a block whose top-left
7957 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
7958 /// mi position (then the coarse [`SUB`]-grid slot is right by
7959 /// construction). See [`Self::record_mode_mi`].
7960 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7961 match self.sub8_mode_col.get(mi_c) {
7962 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
7963 _ => None,
7964 }
7965 }
7966
7967 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7968 match self.sub8_mode_row.get(mi_r) {
7969 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
7970 _ => None,
7971 }
7972 }
7973
7974 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
7975 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
7976 fn record_uv_mode_mi(
7977 &mut self,
7978 mi_r: usize,
7979 mi_c: usize,
7980 mi_w: usize,
7981 mi_h: usize,
7982 uv_mode: usize,
7983 ) {
7984 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
7985 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
7986 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
7987 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
7988 // covers, so the chroma neighbour read below is a plain grid read.
7989 let stride = self.uv_grid_cols;
7990 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
7991 for row in mi_r..=last_r {
7992 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
7993 }
7994 }
7995
7996 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
7997 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
7998 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
7999 /// block has recorded the exact neighbouring mi.
8000 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
8001 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
8002 // REFERENCE block, not off the mi that carries the chroma syntax.
8003 // `set_mi_row_col` (`blockd.h`) takes
8004 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
8005 // only then `chroma_above_mbmi = base_mi[-stride]` /
8006 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
8007 // the ODD mi, so without the snap we looked one mi row/column too far
8008 // down/right -- the mi-exact slot never matched and the coarse
8009 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
8010 // 8x4 at (688, 100) = mi (51, 344): libaom's
8011 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
8012 // `UV_SMOOTH_PRED`), ours was 0, which flips
8013 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
8014 // false for type 1, TRUE for type 0) and upsampled an edge libaom
8015 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
8016 // predicting from it (class `context-read-from-one-cell`).
8017 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
8018 }
8019
8020 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
8021 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
8022 /// counter wants this: it measures how often the snap CHANGES the answer,
8023 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
8024 /// decode path uses the snapping form.
8025 fn smooth_uv_neighbour_unsnapped(
8026 &self,
8027 mi_r: usize,
8028 mi_c: usize,
8029 r: usize,
8030 c: usize,
8031 ) -> bool {
8032 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
8033 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
8034 // array that `start_tile` does not clear, so a block on a tile's first
8035 // mi row used to read the uv_mode of the block above it in the tile
8036 // ABOVE and filter its chroma edge at that neighbour's strength
8037 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
8038 // at chroma (120, 32), the top-right tile's first block).
8039 let have_above = mi_r > self.tile_row0_mi;
8040 let have_left = mi_c > self.tile_col0_mi;
8041 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
8042 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
8043 {
8044 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
8045 }
8046 // The mi grid is libaom's own read; the two maps below stay as the
8047 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
8048 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
8049 (col < self.uv_grid_cols)
8050 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
8051 .flatten()
8052 .filter(|&m| m != u8::MAX)
8053 .map(usize::from)
8054 };
8055 let above = match self.uv_mode_col.get(mi_c) {
8056 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
8057 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
8058 _ if have_above => self.above_uv_mode[c],
8059 _ => DC_PRED,
8060 };
8061 let left = match self.uv_mode_row.get(mi_r) {
8062 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
8063 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
8064 _ if have_left => self.left_uv_mode[r],
8065 _ => DC_PRED,
8066 };
8067 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
8068 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
8069 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
8070 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
8071 }) {
8072 hit!(UV_MODE_GRID_OVERRIDE_HITS);
8073 }
8074 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
8075 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
8076 // have been filtered at the wrong strength by the coarse map alone.
8077 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
8078 hit!(UV_MODE_MI_OVERRIDE_HITS);
8079 }
8080 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
8081 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
8082 {
8083 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8084 }
8085 is_smooth_mode(above) || is_smooth_mode(left)
8086 }
8087
8088 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
8089 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
8090 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
8091 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
8092 /// holding an OLDER, larger block's mode -- it only ever recorded into the
8093 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
8094 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
8095 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
8096 /// a different CDF for the same mode value).
8097 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
8098 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
8099 /// only when `up_available` and `left_mbmi` only when `left_available`;
8100 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
8101 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
8102 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
8103 /// strip's mode as its "left neighbour" (measured on the band fixture at
8104 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
8105 fn modes_above_left_mi(
8106 &self,
8107 mi_r: usize,
8108 mi_c: usize,
8109 fallback: (usize, usize),
8110 ) -> (usize, usize) {
8111 let above = if mi_r > self.tile_row0_mi {
8112 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
8113 } else {
8114 DC_PRED
8115 };
8116 let left = if mi_c > self.tile_col0_mi {
8117 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
8118 } else {
8119 DC_PRED
8120 };
8121 (above, left)
8122 }
8123
8124 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
8125 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
8126 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
8127 /// per superblock row and never per tile, so the first block column of
8128 /// tile 2..N read the previous tile's mode as its left neighbour, and the
8129 /// above band survives across a tile ROW boundary the same way lane-mtfix's
8130 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
8131 /// `up_available`/`left_available` and uses DC_PRED otherwise
8132 /// ([`Self::modes_above_left_mi`]).
8133 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
8134 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8135 let (above, left) =
8136 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
8137 if above != self.above_mode[c] || left != self.left_mode[r] {
8138 hit!(MODE_MI_OVERRIDE_HITS);
8139 }
8140 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
8141 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
8142 {
8143 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8144 }
8145 // A neighbour the coarse band offered where the tile edge makes it
8146 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
8147 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
8148 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
8149 {
8150 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
8151 }
8152 (above, left)
8153 }
8154
8155 fn record_rect(
8156 &mut self,
8157 at: (usize, usize),
8158 w: usize,
8159 h: usize,
8160 mode: usize,
8161 uv_mode: usize,
8162 grids: &[&[i32]; 3],
8163 ) {
8164 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
8165 }
8166
8167 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
8168 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
8169 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
8170 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
8171 /// the [`SUB`]-unit path does).
8172 fn record_rect_mi(
8173 &mut self,
8174 at_mi: (usize, usize),
8175 w: usize,
8176 h: usize,
8177 mode: usize,
8178 uv_mode: usize,
8179 grids: &[&[i32]; 3],
8180 ) {
8181 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8182 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8183 // last 16-px column/row stamps only the cells that exist (libaom's
8184 // arrays are padded past the frame and those cells are never read).
8185 for cell in 0..w / SUB {
8186 if c + cell >= self.above_mode.len() {
8187 break;
8188 }
8189 self.above_mode[c + cell] = mode;
8190 self.above_uv_mode[c + cell] = uv_mode;
8191 self.above_side[c + cell] = w;
8192 }
8193 for cell in 0..h / SUB {
8194 if r + cell >= self.left_mode.len() {
8195 break;
8196 }
8197 self.left_mode[r + cell] = mode;
8198 self.left_uv_mode[r + cell] = uv_mode;
8199 self.left_side[r + cell] = h;
8200 }
8201 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8202 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8203 self.record_mi_rect(at_mi, w, h, grids);
8204 }
8205
8206 /// The coefficient-context half of [`Self::record`], taking the block's
8207 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8208 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8209 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8210 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8211 self.record_mi_rect(at_mi, side, side, grids);
8212 }
8213
8214 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8215 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8216 fn record_mi_rect(
8217 &mut self,
8218 at_mi: (usize, usize),
8219 w: usize,
8220 h: usize,
8221 grids: &[&[i32]; 3],
8222 ) {
8223 let (mi_r, mi_c) = at_mi;
8224 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8225 let (w_mi, h_mi) = (w / MI, h / MI);
8226 if crate::envflags::env_flag!("EC_ECPUB") {
8227 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8228 }
8229 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8230 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8231 // A chroma 4x4 unit straddling the true luma edge is still whole in
8232 // chroma's own halved grid, so libaom rounds the luma bound up to the
8233 // plane's own 4x4 unit before clamping a subsampled plane
8234 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8235 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8236 let bound_h = [
8237 self.mi_rows,
8238 round_up_even(self.mi_rows),
8239 round_up_even(self.mi_rows),
8240 ];
8241 let bound_w = [
8242 self.mi_cols,
8243 round_up_even(self.mi_cols),
8244 round_up_even(self.mi_cols),
8245 ];
8246 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8247 // past the padded side arrays (mi_rows 198, block rows 192..208);
8248 // libaom's own arrays are superblock-sized, so those cells simply
8249 // have no reader -- [`fill_span`] drops them, as the `break` did.
8250 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8251 // predicate is three contiguous runs: all planes, chroma only, none
8252 // (lane-mi).
8253 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8254 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8255 let uv_only = [Neighbour::default(), states[1], states[2]];
8256 fill_span(&mut self.left, mi_r, luma_h, states);
8257 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8258 fill_span(
8259 &mut self.left,
8260 mi_r + chroma_h,
8261 h_mi - chroma_h,
8262 [Neighbour::default(); 3],
8263 );
8264 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8265 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8266 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8267 fill_span(&mut self.above, mi_c, luma_w, states);
8268 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8269 fill_span(
8270 &mut self.above,
8271 mi_c + chroma_w,
8272 w_mi - chroma_w,
8273 [Neighbour::default(); 3],
8274 );
8275 }
8276
8277 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8278 /// inside a coded block whose luma transform is smaller than its own
8279 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8280 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8281 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8282 /// [`Self::record_split_luma`] still writes once for the whole block.
8283 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8284 /// the caller's own [`Self::record_split_luma`] call sets those once,
8285 /// at the block's own true side, not this TU's.
8286 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8287 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8288 }
8289
8290 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8291 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8292 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8293 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8294 /// coefficient-context arrays are indexed by luma mi, the convention
8295 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8296 /// clamp included.
8297 fn record_mi_chroma(
8298 &mut self,
8299 (mi_r, mi_c): (usize, usize),
8300 w_px: usize,
8301 h_px: usize,
8302 plane: usize,
8303 grid: &[i32],
8304 ) {
8305 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8306 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8307 let state = neighbour_state(grid);
8308 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8309 self.left[mi_r + cell][plane] = state;
8310 }
8311 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
8312 self.above[mi_c + cell][plane] = state;
8313 }
8314 }
8315
8316 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
8317 /// r1): the above context spans the unit's width, the left context its
8318 /// height, which for a square unit is the same loop it always was.
8319 fn record_mi_luma_rect(
8320 &mut self,
8321 (mi_r, mi_c): (usize, usize),
8322 w_px: usize,
8323 h_px: usize,
8324 grid: &[i32],
8325 ) {
8326 let state = neighbour_state(grid);
8327 if crate::envflags::env_flag!("EC_ECPUB") {
8328 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
8329 }
8330 for cell in 0..h_px / MI {
8331 if mi_r + cell < self.mi_rows {
8332 self.left[mi_r + cell][0] = state;
8333 }
8334 }
8335 for cell in 0..w_px / MI {
8336 if mi_c + cell < self.mi_cols {
8337 self.above[mi_c + cell][0] = state;
8338 }
8339 }
8340 }
8341
8342 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
8343 /// block whose luma was decoded as several transform units through
8344 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
8345 /// whole-block luma write -- everything [`Self::record`] does except
8346 /// plane 0, which is already correct per-TU by the time this runs.
8347 fn record_split_luma(
8348 &mut self,
8349 at: (usize, usize),
8350 side: usize,
8351 mode: usize,
8352 uv_mode: usize,
8353 chroma_grids: [&[i32]; 2],
8354 ) {
8355 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
8356 }
8357
8358 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
8359 /// extents in pixels (lane-rectsplit r1), the same relationship
8360 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
8361 /// luma transform split into several square units needs exactly this
8362 /// bookkeeping, at its own true rectangular extents.
8363 fn record_split_luma_rect(
8364 &mut self,
8365 at: (usize, usize),
8366 w: usize,
8367 h: usize,
8368 mode: usize,
8369 uv_mode: usize,
8370 chroma_grids: [&[i32]; 2],
8371 ) {
8372 let (r, c) = at;
8373 self.record_split_luma_rect_mi(
8374 (r * (SUB / MI), c * (SUB / MI)),
8375 w,
8376 h,
8377 mode,
8378 uv_mode,
8379 chroma_grids,
8380 );
8381 }
8382
8383 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
8384 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
8385 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
8386 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
8387 /// convention [`decode_block_rect4`] already established for 1:4 strips.
8388 fn record_split_luma_rect_mi(
8389 &mut self,
8390 at_mi: (usize, usize),
8391 w: usize,
8392 h: usize,
8393 mode: usize,
8394 uv_mode: usize,
8395 chroma_grids: [&[i32]; 2],
8396 ) {
8397 let (mi_r, mi_c) = at_mi;
8398 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8399 for cell in 0..w.div_ceil(SUB) {
8400 if c + cell >= self.above_mode.len() {
8401 break;
8402 }
8403 self.above_mode[c + cell] = mode;
8404 self.above_uv_mode[c + cell] = uv_mode;
8405 self.above_side[c + cell] = w;
8406 }
8407 for cell in 0..h.div_ceil(SUB) {
8408 if r + cell >= self.left_mode.len() {
8409 break;
8410 }
8411 self.left_mode[r + cell] = mode;
8412 self.left_uv_mode[r + cell] = uv_mode;
8413 self.left_side[r + cell] = h;
8414 }
8415
8416 let (w_mi, h_mi) = (w / MI, h / MI);
8417 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
8418 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
8419 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8420 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8421 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8422 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8423 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
8424 let plane = plane_idx + 1;
8425 let state = neighbour_state(grid);
8426 for cell in 0..h_mi {
8427 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
8428 self.left[mi_r + cell][plane] = state;
8429 }
8430 }
8431 for cell in 0..w_mi {
8432 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
8433 self.above[mi_c + cell][plane] = state;
8434 }
8435 }
8436 }
8437 }
8438}
8439
8440/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
8441/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
8442/// exactly — including its skip context, which the real key-frame writer
8443/// always writes at a fixed context of zero (it never tracks a neighbour-based
8444/// one for intra blocks; that is the inter-frame writer's rule instead).
8445/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
8446/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
8447/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
8448/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
8449/// plain DC chroma.
8450/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
8451/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
8452/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
8453/// instead (the defect commit 1a89ed9 fixed at the square sites).
8454pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
8455 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
8456 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
8457}
8458
8459/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
8460/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
8461/// bound (spec `filter_intra_mode_info` never reads a symbol there).
8462pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
8463 match side {
8464 4 => Some(0),
8465 8 => Some(1),
8466 16 => Some(2),
8467 32 => Some(3),
8468 _ => None,
8469 }
8470}
8471
8472/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
8473/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
8474/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
8475/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
8476fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8477 match (bw, bh) {
8478 (32, 16) => Some(4),
8479 (16, 32) => Some(5),
8480 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
8481 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
8482 // here dropped that symbol on every DC_PRED strip of that size and
8483 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
8484 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
8485 (16, 8) => Some(6),
8486 (8, 16) => Some(7),
8487 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
8488 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
8489 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
8490 (4, 8) => Some(8),
8491 (8, 4) => Some(9),
8492 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
8493 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
8494 // `use_filter_intra` symbol on those strips although aomenc writes
8495 // one for every DC_PRED block of that shape with
8496 // `--enable-filter-intra=1` (its default), silently desyncing the
8497 // tile (class symbol-consumption-gap).
8498 (32, 8) => Some(10),
8499 (8, 32) => Some(11),
8500 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
8501 // strips), rows 17/16 of `default_filter_intra_cdfs`.
8502 (16, 4) => Some(12),
8503 (4, 16) => Some(13),
8504 _ if bw == bh => filter_intra_size_class(bw),
8505 _ => None,
8506 }
8507}
8508
8509/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
8510/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
8511/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8512/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8513/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8514pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8515 palette_bsize_ctx_wh(side, side)
8516}
8517
8518/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
8519/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
8520/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
8521/// for ANY bsize, not just the square ones a hand-picked table happened to
8522/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
8523/// row breaks the moment its indexing field moves off the diagonal, and a
8524/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
8525/// block dimension is a power of two, so `bw*bh` always is too and
8526/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
8527/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
8528fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
8529 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
8530 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
8531 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
8532 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
8533 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
8534 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
8535 if bw > 64 || bh > 64 || bw * bh < 64 {
8536 return None;
8537 }
8538 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
8539}
8540
8541/// A just-decoded palette-Y block's own size, base colours (only the first
8542/// `size` entries are real), and per-pixel colour-index map (`side*side`,
8543/// row-major, each entry `< size`).
8544struct PaletteY {
8545 size: usize,
8546 colors: [u16; 8],
8547 map: Vec<u8>,
8548}
8549
8550/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
8551/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
8552/// shared between U and V, both co-located after 4:2:0 subsampling) plus
8553/// each plane's own base colours.
8554struct PaletteUv {
8555 size: usize,
8556 u_colors: [u16; 8],
8557 v_colors: [u16; 8],
8558 map: Vec<u8>,
8559}
8560
8561/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
8562/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8563/// `get_unsigned_bits`, which is the same formula): smallest `n` with
8564/// `2^n >= x`, `0` for `x <= 1`.
8565pub(crate) fn ceil_log2(x: u32) -> u32 {
8566 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8567}
8568
8569/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
8570/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
8571fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
8572 let l = ceil_log2(n as u32);
8573 let m = (1usize << l) - n;
8574 let v = dec.literal(l - 1) as usize;
8575 if v < m {
8576 v
8577 } else {
8578 (v << 1) - m + dec.literal(1) as usize
8579 }
8580}
8581
8582/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
8583/// colours (already-known, from the above/left neighbours) with the
8584/// ascending `transmitted` ones (delta-coded off the wire) back into one
8585/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
8586/// value picks the cached copy first, matching the C `<=`.
8587fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
8588 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
8589 let (mut ci, mut ti) = (0, 0);
8590 while ci < cached.len() && ti < transmitted.len() {
8591 if cached[ci] <= transmitted[ti] {
8592 out.push(cached[ci]);
8593 ci += 1;
8594 } else {
8595 out.push(transmitted[ti]);
8596 ti += 1;
8597 }
8598 }
8599 out.extend_from_slice(&cached[ci..]);
8600 out.extend_from_slice(&transmitted[ti..]);
8601 out
8602}
8603
8604/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
8605/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
8606/// each delta's width, the `range` bound and the clamp) is sized by
8607/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
8608/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
8609/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
8610/// the msac range, so a cross-decoder range ladder stays bit-identical
8611/// through the whole miscount -- only the decoded VALUE differs (class
8612/// `compare-range-not-tell`'s blind spot). (this
8613/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
8614/// (one flag bit each, in cache order), then delta-codes the remainder
8615/// (first value raw, each following delta `>= 1` off a shrinking bit width),
8616/// and merges the two ascending lists back together.
8617fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
8618 let mut cached = Vec::with_capacity(n);
8619 for &c in cache {
8620 if cached.len() >= n {
8621 break;
8622 }
8623 if dec.literal(1) == 1 {
8624 cached.push(c);
8625 }
8626 }
8627 let bd = u32::from(bit_depth(fctx));
8628 let max_val = (1i32 << bd) - 1;
8629 let mut colors = [0u16; 8];
8630 let n_cached = cached.len();
8631 if n_cached < n {
8632 let mut transmitted = Vec::with_capacity(n - n_cached);
8633 let first = dec.literal(bd) as u16;
8634 transmitted.push(first);
8635 if n_cached + 1 < n {
8636 let min_bits = bd - 3;
8637 let mut bits = min_bits + dec.literal(2);
8638 let mut range = (1i32 << bd) - i32::from(first) - 1;
8639 for _ in (n_cached + 1)..n {
8640 let delta = dec.literal(bits) as i32 + 1;
8641 let prev = *transmitted.last().unwrap();
8642 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
8643 range -= i32::from(val) - i32::from(prev);
8644 bits = bits.min(ceil_log2(range.max(0) as u32));
8645 transmitted.push(val);
8646 }
8647 }
8648 let merged = merge_colors(&transmitted, &cached);
8649 colors[..n].copy_from_slice(&merged);
8650 } else {
8651 colors[..n].copy_from_slice(&cached[..n]);
8652 }
8653 colors
8654}
8655
8656/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
8657/// `bit_depth` (see [`read_palette_colors_y`]): U reads
8658/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
8659/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
8660/// unbiased by `+1` -- both differences from Y's own reader, matching the C
8661/// side by side). V never uses a cache: a leading bit picks either `n` raw
8662/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
8663/// rather than clamp.
8664fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
8665 let mut cached = Vec::with_capacity(n);
8666 for &c in cache {
8667 if cached.len() >= n {
8668 break;
8669 }
8670 if dec.literal(1) == 1 {
8671 cached.push(c);
8672 }
8673 }
8674 let bd = u32::from(bit_depth(fctx));
8675 let max_val = 1i32 << bd;
8676 let mut u_colors = [0u16; 8];
8677 let n_cached = cached.len();
8678 if n_cached < n {
8679 let mut transmitted = Vec::with_capacity(n - n_cached);
8680 let first = dec.literal(bd) as u16;
8681 transmitted.push(first);
8682 if n_cached + 1 < n {
8683 let min_bits = bd - 3;
8684 let mut bits = min_bits + dec.literal(2);
8685 let mut range = max_val - i32::from(first);
8686 for _ in (n_cached + 1)..n {
8687 let delta = dec.literal(bits) as i32;
8688 let prev = *transmitted.last().unwrap();
8689 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
8690 range -= i32::from(val) - i32::from(prev);
8691 bits = bits.min(ceil_log2(range.max(0) as u32));
8692 transmitted.push(val);
8693 }
8694 }
8695 let merged = merge_colors(&transmitted, &cached);
8696 u_colors[..n].copy_from_slice(&merged);
8697 } else {
8698 u_colors[..n].copy_from_slice(&cached[..n]);
8699 }
8700 let mut v_colors = [0u16; 8];
8701 if dec.literal(1) == 1 {
8702 let min_bits_v = bd - 4;
8703 let bits = min_bits_v + dec.literal(2);
8704 v_colors[0] = dec.literal(bd) as u16;
8705 for i in 1..n {
8706 let mut delta = dec.literal(bits) as i32;
8707 if delta != 0 && dec.literal(1) == 1 {
8708 delta = -delta;
8709 }
8710 let mut val = i32::from(v_colors[i - 1]) + delta;
8711 if val < 0 {
8712 val += max_val;
8713 }
8714 if val >= max_val {
8715 val -= max_val;
8716 }
8717 v_colors[i] = val as u16;
8718 }
8719 } else {
8720 for i in 0..n {
8721 v_colors[i] = dec.literal(bd) as u16;
8722 }
8723 }
8724 (u_colors, v_colors)
8725}
8726
8727/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
8728/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
8729/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
8730const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
8731
8732/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
8733/// map's own per-pixel context and colour-order permutation, from the
8734/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
8735/// selection sort). `map`'s stride is `side` (this decoder never crops a
8736/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
8737/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
8738/// actual colour index to store.
8739pub(crate) fn palette_color_index_context(
8740 map: &[u8],
8741 side: usize,
8742 row: usize,
8743 col: usize,
8744 n: usize,
8745) -> (usize, [u8; 8]) {
8746 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
8747 let up_left = if col >= 1 && row >= 1 {
8748 Some(map[(row - 1) * side + col - 1])
8749 } else {
8750 None
8751 };
8752 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
8753 let mut scores = [0i32; 8];
8754 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
8755 if let Some(v) = neighbour {
8756 scores[v as usize] += weight;
8757 }
8758 }
8759 let mut color_order = [0u8; 8];
8760 for i in 0..8 {
8761 color_order[i] = i as u8;
8762 }
8763 for i in 0..3 {
8764 let mut max = scores[i];
8765 let mut max_idx = i;
8766 for j in (i + 1)..n {
8767 if scores[j] > max {
8768 max = scores[j];
8769 max_idx = j;
8770 }
8771 }
8772 if max_idx != i {
8773 let max_score = scores[max_idx];
8774 let max_color = color_order[max_idx];
8775 for k in (i + 1..=max_idx).rev() {
8776 scores[k] = scores[k - 1];
8777 color_order[k] = color_order[k - 1];
8778 }
8779 scores[i] = max_score;
8780 color_order[i] = max_color;
8781 }
8782 }
8783 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
8784 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
8785 (ctx as usize, color_order)
8786}
8787
8788/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
8789/// map's wavefront decode over a `side x side` grid -- this decoder's
8790/// palette blocks are always square and never straddle the frame's true
8791/// (possibly odd) edge without already allocating the full `side*side`
8792/// region (every other skip/residual path here does the same), so no
8793/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
8794/// libaom's own non-block-aligned split.
8795fn decode_color_index_map(
8796 dec: &mut SymbolDecoder,
8797 cdfs: &mut Cdfs,
8798 n: usize,
8799 side: usize,
8800 uv: bool,
8801) -> Vec<u8> {
8802 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
8803}
8804
8805/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
8806/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
8807/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
8808/// independently rather than one shared `side` -- the square call above is
8809/// just `bw == bh`.
8810fn decode_color_index_map_wh(
8811 dec: &mut SymbolDecoder,
8812 cdfs: &mut Cdfs,
8813 n: usize,
8814 bw: usize,
8815 bh: usize,
8816 uv: bool,
8817) -> Vec<u8> {
8818 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8819 let mut map = vec![0u8; bw * bh];
8820 if trace {
8821 let (rng, _) = dec.debug_state();
8822 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
8823 }
8824 map[0] = read_uniform(dec, n) as u8;
8825 if trace {
8826 let (rng, _) = dec.debug_state();
8827 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
8828 }
8829 for i in 1..(bw + bh - 1) {
8830 let j_hi = i.min(bw - 1);
8831 let j_lo = i.saturating_sub(bh - 1);
8832 for j in (j_lo..=j_hi).rev() {
8833 let row = i - j;
8834 let col = j;
8835 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
8836 if trace {
8837 let (rng, _) = dec.debug_state();
8838 let row_cdf = if uv {
8839 &cdfs.palette_uv_color_index[n - 2][ctx]
8840 } else {
8841 &cdfs.palette_y_color_index[n - 2][ctx]
8842 };
8843 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
8844 }
8845 let symbol = if uv {
8846 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
8847 } else {
8848 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
8849 };
8850 map[row * bw + col] = color_order[symbol];
8851 if trace {
8852 let (rng, _) = dec.debug_state();
8853 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
8854 }
8855 }
8856 }
8857 map
8858}
8859
8860/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
8861/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
8862/// size class comes from [`filter_intra_size_class_rect`] instead of the
8863/// square-only [`filter_intra_size_class`], and the palette read (when
8864/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
8865/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
8866/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
8867/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
8868#[allow(clippy::too_many_arguments)]
8869fn read_intra_mode_rect(
8870 dec: &mut SymbolDecoder,
8871 cdfs: &mut Cdfs,
8872 above_mode: usize,
8873 left_mode: usize,
8874 cfl: bool,
8875 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
8876 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
8877 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
8878 // chroma is coded once, on the closing strip). Every other caller is a
8879 // block big enough to own its chroma and passes `true`.
8880 has_chroma: bool,
8881 bw: usize,
8882 bh: usize,
8883 enable_filter_intra: bool,
8884 skip_ctx: usize,
8885 allow_screen_content_tools: bool,
8886 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
8887 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
8888 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
8889 palette: Option<(usize, &[u16])>,
8890 palette_uv_cache: &[u16],
8891 mi_r: usize,
8892 mi_c: usize, fctx: &crate::decode::FrameCtx,
8893) -> Result<(
8894 bool,
8895 usize,
8896 i32,
8897 usize,
8898 i32,
8899 Option<(i32, i32)>,
8900 Option<usize>,
8901 Option<PaletteY>,
8902 Option<PaletteUv>,
8903)> {
8904 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
8905 if ec_istep {
8906 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
8907 // (decodemv.c:818), printed at the same point: before the first
8908 // mode-info symbol of the block, so a cross-decoder range ladder can
8909 // be keyed on the BLOCK, not just on the symbol sequence.
8910 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);
8911 }
8912 macro_rules! istep {
8913 ($name:literal, $val:expr) => {
8914 if ec_istep {
8915 let (rng, _) = dec.debug_state();
8916 eprintln!(
8917 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
8918 $name, $val
8919 );
8920 }
8921 };
8922 }
8923 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
8924 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
8925 // the one point every rect caller routes through, so no call site can
8926 // offer the 14-symbol CFL alphabet on a 64-axis block (class
8927 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
8928 let cfl = if cfl && bw.max(bh) > 32 {
8929 hit!(NOCFL_UV_MODE_HITS);
8930 false
8931 } else {
8932 cfl
8933 };
8934 // lane-intra14 r1: on the INTER block path everything up to and including
8935 // `is_inter` was already read by [`decode_inter_block`], so this reader
8936 // starts at the mode syntax with the `skip` that caller read.
8937 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
8938 let skip = if let Some((_, skip)) = inter {
8939 skip
8940 } else {
8941 // Same `intra_segment_id` placement as the square reader above.
8942 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
8943 if seg_id_pre_skip(fctx) {
8944 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
8945 }
8946 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8947 istep!("skip", skip as i32);
8948 if !seg_id_pre_skip(fctx) {
8949 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
8950 }
8951 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
8952 istep!("cdef", 0);
8953 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
8954 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
8955 // `false`.
8956 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8957 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8958 istep!("dq", 0);
8959 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
8960 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
8961 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
8962 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
8963 // rect strips read it exactly like square leaves ([`read_intra_mode`],
8964 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
8965 // decoder at the FIRST symbol of the first rect block of every
8966 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
8967 // block at this shape is out of scope, so the flag is consumed and
8968 // refused by name when it fires.
8969 if allow_intrabc_frame(fctx) {
8970 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8971 hit!(RECT_INTRABC_READS);
8972 istep!("intrabc", use_intrabc as i32);
8973 if use_intrabc {
8974 hit!(INTRABC_HITS);
8975 return Err(unsupported(
8976 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
8977 ));
8978 }
8979 }
8980 skip
8981 };
8982 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
8983 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
8984 // off `kf_y_mode_cdf[above][left]`).
8985 let mode = if let Some((size_group, _)) = inter {
8986 dec.symbol(&mut cdfs.y_mode[size_group])
8987 } else {
8988 let above_ctx = INTRA_MODE_CTX[above_mode];
8989 let left_ctx = INTRA_MODE_CTX[left_mode];
8990 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
8991 };
8992 istep!("mode", mode as i32);
8993 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8994 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8995 } else {
8996 0
8997 };
8998 istep!("angle_y", angle_delta_y);
8999 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
9000 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
9001 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
9002 // here, from the block's own size, is the single point every caller routes
9003 // through -- a caller passing `true` for a >32 strip used to pick the
9004 // 14-symbol CFL CDF, same value but a different range (class
9005 // wrong-alphabet-same-value).
9006 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
9007 let uv_mode = if !has_chroma {
9008 DC_PRED
9009 } else if cfl {
9010 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9011 } else {
9012 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9013 };
9014 istep!("uv_mode", uv_mode as i32);
9015 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
9016 Some(read_cfl_alphas(dec, cdfs))
9017 } else {
9018 None
9019 };
9020 if has_chroma && (9..=12).contains(&uv_mode) {
9021 hit!(SMOOTH_UV_HITS);
9022 }
9023 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
9024 hit!(DIRECTIONAL_UV_HITS);
9025 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9026 } else {
9027 0
9028 };
9029 istep!("angle_uv", angle_delta_uv);
9030 if angle_delta_uv != 0 {
9031 hit!(UV_ANGLE_DELTA_HITS);
9032 }
9033 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
9034 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
9035 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
9036 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
9037 // colours only here, the colour-index maps deferred past `filter_intra`
9038 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
9039 // runs from the caller, after the whole mode-info read).
9040 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9041 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9042 if allow_screen_content_tools
9043 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
9044 {
9045 // r6: this is the exact site the removed blanket refusal used to
9046 // guard -- reached for EVERY rect strip in a screen-content frame,
9047 // independent of whether the block ends up using a palette.
9048 hit!(RECT_SCREEN_CONTENT_HITS);
9049 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
9050 let use_palette_y =
9051 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
9052 if use_palette_y {
9053 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9054 let colors = read_palette_colors_y(dec, n, cache, fctx);
9055 palette_y_pending = Some((n, colors));
9056 }
9057 let palette_uv_mode_ctx = usize::from(use_palette_y);
9058 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
9059 if has_chroma
9060 && uv_mode == DC_PRED
9061 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
9062 {
9063 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9064 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
9065 palette_uv_pending = Some((n, u_colors, v_colors));
9066 }
9067 }
9068 let mut filter_intra = None;
9069 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9070 let (rng, _) = dec.debug_state();
9071 eprintln!(
9072 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
9073 class={:?} rng={rng}",
9074 enable_filter_intra as i32,
9075 filter_intra_size_class_rect(bw, bh)
9076 );
9077 }
9078 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
9079 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
9080 if mode == DC_PRED
9081 && enable_filter_intra
9082 && palette_y_pending.is_none()
9083 && let Some(class) = filter_intra_size_class_rect(bw, bh)
9084 {
9085 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
9086 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9087 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
9088 }
9089 istep!("use_filter_intra", use_filter_intra as i32);
9090 if use_filter_intra {
9091 hit!(FILTER_INTRA_HITS);
9092 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9093 istep!("filter_intra_mode", fi_mode as i32);
9094 filter_intra = Some(fi_mode);
9095 }
9096 }
9097 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
9098 // same order as [`read_intra_mode`]'s own square path.
9099 let palette_y = palette_y_pending.map(|(n, colors)| {
9100 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
9101 hit!(PALETTE_HITS);
9102 hit!(PALETTE_RECT_HITS);
9103 PaletteY { size: n, colors, map }
9104 });
9105 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9106 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
9107 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
9108 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
9109 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
9110 // chroma palette and desynced the tile from there.
9111 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
9112 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
9113 hit!(PALETTE_UV_HITS);
9114 PaletteUv { size: n, u_colors, v_colors, map }
9115 });
9116 Ok((
9117 skip,
9118 mode,
9119 angle_delta_y,
9120 uv_mode,
9121 angle_delta_uv,
9122 alpha,
9123 filter_intra,
9124 palette_y,
9125 palette_uv,
9126 ))
9127}
9128
9129/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
9130/// at the strip's REAL mi position. `av1_get_palette_cache` reads
9131/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
9132/// block, so each strip owns its own rows and columns and no aliasing rule
9133/// is needed (lane-kf900 r6).
9134#[allow(clippy::too_many_arguments)]
9135fn record_strip_palette(
9136 n: &mut Neighbours,
9137 mi: (usize, usize),
9138 bw: usize,
9139 bh: usize,
9140 y_size: usize,
9141 y_colors: [u16; 8],
9142 uv_size: usize,
9143 uv_colors: [u16; 8],
9144) {
9145 let (r, c) = mi;
9146 // lane-t900 r23 rung: every publication of a block's palette state into
9147 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
9148 // path left a stale `left_palette_size` behind when
9149 // `av1_get_palette_mode_ctx` disagrees with libaom's.
9150 if crate::envflags::env_flag!("EC_PALPUB") {
9151 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
9152 }
9153 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
9154 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
9155 // existed because the 16px [`SUB`] cell held one slot for all the strips
9156 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
9157 // real neighbour leaf 1 reads.
9158 {
9159 for cell in 0..(bw / MI).max(1) {
9160 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
9161 *e = y_size as u8;
9162 n.above_palette_uv_size[c + cell] = uv_size as u8;
9163 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
9164 // colours of a size-0 neighbour are never read.
9165 if y_size > 0 {
9166 n.above_palette_colors[c + cell] = y_colors;
9167 }
9168 if uv_size > 0 {
9169 n.above_palette_uv_colors[c + cell] = uv_colors;
9170 }
9171 }
9172 }
9173 }
9174 {
9175 for cell in 0..(bh / MI).max(1) {
9176 if n.left_palette_size.get(r + cell).is_none() {
9177 break;
9178 }
9179 n.left_palette_size[r + cell] = y_size as u8;
9180 n.left_palette_uv_size[r + cell] = uv_size as u8;
9181 if y_size > 0 {
9182 n.left_palette_colors[r + cell] = y_colors;
9183 }
9184 if uv_size > 0 {
9185 n.left_palette_uv_colors[r + cell] = uv_colors;
9186 }
9187 }
9188 }
9189}
9190
9191/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
9192/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
9193/// above against this block's own *width* and the neighbour to the left
9194/// against its own *height* -- for a square block those are the same value,
9195/// which is why the square-only version can get away with one `own_side`.
9196fn tx_size_context_rect(
9197 n: &Neighbours,
9198 (mi_r, mi_c): (usize, usize),
9199 own_w: usize,
9200 own_h: usize,
9201) -> usize {
9202 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
9203 // not the block's own side: no transform is wider or taller than 64, so a
9204 // block with a 128 side resolves against 64 (the square path already caps
9205 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
9206 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
9207 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
9208 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
9209 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
9210 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9211 eprintln!(
9212 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
9213 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
9214 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
9215 usize::from(above) + usize::from(left)
9216 );
9217 }
9218 usize::from(above) + usize::from(left)
9219}
9220
9221/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9222fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9223 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9224}
9225
9226/// Everything a rect strip already read out of the stream before its luma
9227/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9228/// (nine values that would otherwise be nine more parameters).
9229struct RectStripModes {
9230 skip: bool,
9231 mode: usize,
9232 angle_delta_y: i32,
9233 uv_predict_mode: usize,
9234 angle_delta_uv: i32,
9235 alpha: Option<(i32, i32)>,
9236 filter_intra: Option<usize>,
9237 smooth_neighbor: bool,
9238 smooth_neighbor_uv: bool,
9239 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9240 /// mapped through the colour table), sliced per transform unit below --
9241 /// palette prediction reads no edge pixels, so a unit's slice of the
9242 /// whole-block map IS its prediction. Without this a palette strip whose
9243 /// transform splits predicted DC and came out flat grey while the entropy
9244 /// stream stayed in sync (the coefficients are read either way).
9245 palette_y: Option<Vec<u16>>,
9246 /// As `palette_y`, for the un-split chroma transform (U, V).
9247 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9248}
9249
9250/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9251/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9252/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9253/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9254/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9255/// TX_32X16`) and only the second reaches a square -- the reason
9256/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9257/// already square) mis-tiled 1:4 strips.
9258fn depth_to_tx_wh(
9259 bw: usize,
9260 bh: usize,
9261 depth: usize,
9262 fctx: &crate::decode::FrameCtx,
9263) -> (usize, usize) {
9264 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
9265 // `read_tx_size`: the lossless early return comes before
9266 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
9267 if lossless(fctx) {
9268 return (4, 4);
9269 }
9270 let (mut w, mut h) = (bw.min(64), bh.min(64));
9271 for _ in 0..depth {
9272 match w.cmp(&h) {
9273 std::cmp::Ordering::Greater => w /= 2,
9274 std::cmp::Ordering::Less => h /= 2,
9275 std::cmp::Ordering::Equal => {
9276 w /= 2;
9277 h /= 2;
9278 }
9279 }
9280 }
9281 (w, h)
9282}
9283
9284/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9285/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9286/// rect path here refused by name until now ("per-unit rect prediction is not
9287/// ported").
9288///
9289/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9290/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9291/// strip the very first step already lands on a SQUARE transform
9292/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9293/// every further step halves a square) -- so each unit is square and reads
9294/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9295/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9296/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9297/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9298/// split by luma's depth.
9299///
9300/// Each unit predicts off whatever the earlier units of this same block
9301/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9302/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9303/// what predicting the whole strip in one shot got wrong.
9304#[allow(clippy::too_many_arguments)]
9305fn decode_rect_split(
9306 dec: &mut SymbolDecoder,
9307 cdfs: &mut Cdfs,
9308 neighbours: &mut Neighbours,
9309 at_mi: (usize, usize),
9310 bw: usize,
9311 bh: usize,
9312 // The transform unit's own width and height in pixels. Square for every
9313 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9314 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9315 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9316 tx_w: usize,
9317 tx_h: usize,
9318 m: &RectStripModes,
9319 y: &mut PlaneBuf<'static>,
9320 u: &mut PlaneBuf<'static>,
9321 v: &mut PlaneBuf<'static>,
9322 base_q_idx: u8,
9323 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9324) -> Result<()> {
9325 let (mi_r, mi_c) = at_mi;
9326 let (px, py) = (mi_c * MI, mi_r * MI);
9327 let (cpx, cpy) = (px / 2, py / 2);
9328 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9329 // The chroma transform is picked before any symbol is read, so an
9330 // unsupported chroma shape refuses before this strip desyncs the tile.
9331 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9332 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9333 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9334 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9335 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9336 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9337 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9338 // squares a rect transform down to a CDF set by
9339 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9340 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9341 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9342 // paths already prove for these same shapes.
9343 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9344 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9345 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9346 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9347 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9348 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9349 _ => None,
9350 };
9351 if !m.skip {
9352 if let Some(i) = match (chroma_w, chroma_h) {
9353 (32, 8) => Some(0),
9354 (8, 32) => Some(1),
9355 (8, 4) => Some(2),
9356 (4, 8) => Some(3),
9357 _ => None,
9358 } {
9359 hit_do! {
9360 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9361 let mut hits = c.get();
9362 hits[i] += 1;
9363 c.set(hits);
9364 });
9365 }
9366 }
9367 if chroma.is_none() {
9368 // Diagnostic for the next caller that lands here (class
9369 // refusal-names-a-correlate: the message names the tool, not the
9370 // shape); the refusal below keeps its inventory-pinned wording.
9371 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9372 }
9373 }
9374 // lane-rectsplit r2 (verifier finding): with both callers wired
9375 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9376 // 64x32/32x64) every shape that reaches here has a table above, so this
9377 // arm is UNREACHABLE today. It stays as the shape guard for the next
9378 // caller -- a new strip size would otherwise hit the `expect` below and
9379 // panic instead of refusing by name -- and so stays in
9380 // `refusal_inventory::REFUSALS`.
9381 if !m.skip && chroma.is_none() {
9382 return Err(unsupported(
9383 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9384 ));
9385 }
9386 hit!(RECT_SPLIT_TX_HITS);
9387 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9388 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9389 }
9390 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9391 // A square unit reads through the ordinary square [`read_plane`]; a rect
9392 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9393 // the very tables the unsplit 16x8/32x16 paths use.
9394 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9395 (w, h) if w == h => None,
9396 (16, 8) | (8, 16) => Some((
9397 if reduced_tx_set {
9398 TxbSet::LumaRect16x8
9399 } else {
9400 TxbSet::LumaRect16x8Set1
9401 },
9402 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9403 )),
9404 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9405 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9406 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9407 // strip, read through the `luma_64corner` arm below instead of a rect
9408 // table -- a 64-length axis codes only its low 32 coefficients
9409 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9410 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9411 // depth-0 arm already reads on the key-frame path.
9412 //
9413 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9414 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9415 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9416 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9417 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9418 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9419 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9420 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9421 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9422 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9423 (64, 32) | (32, 64) => None,
9424 _ => {
9425 return Err(unsupported(format!(
9426 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9427 coefficient tables for that shape here)"
9428 )))
9429 }
9430 };
9431 // The `None` above that is NOT the square arm.
9432 let luma_64corner = tx_w != tx_h;
9433 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9434 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9435 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9436 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9437 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9438 // per-unit rect walk stay wired above/below; the round that finds that
9439 // defect deletes this refusal and nothing else.
9440 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9441 let luma_scan = default_scan(tx_w.min(tx_h));
9442 let zero_tu = vec![0i32; tx_w * tx_h];
9443 // The strip's OWN edge availability, the fallback for a transform unit
9444 // whose top-right/bottom-left pixels fall outside the strip.
9445 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9446 for tu_row in 0..bh / tx_h {
9447 for tu_col in 0..bw / tx_w {
9448 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9449 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9450 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9451 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9452 // libaom clips `av1_foreach_transformed_block_in_plane` to
9453 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9454 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9455 // TOP-LEFT sample falls outside the frame is never coded. We read
9456 // coefficients for those phantom units and desynced the stream at
9457 // the very next symbol.
9458 if tu_px >= y.true_width || tu_py >= y.true_height {
9459 continue;
9460 }
9461 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9462 // transform unit INSIDE a block, which is a different rule from
9463 // the standalone-block table [`Reach::of`] applies -- and the
9464 // reason a depth-2 superblock strip came out one sample off
9465 // before this: `Reach::of(tx, ..)` answered as if the unit were
9466 // its own block at that superblock position.
9467 // * top-right: if the unit's right neighbour is still inside the
9468 // strip the pixels are already reconstructed (`col_off +
9469 // tx_wide < plane_bw`); otherwise only the strip's own top row
9470 // of units can reach past it, through the block-level answer.
9471 // * bottom-left: a unit that is not in the strip's left column
9472 // has none (`col_off > 0` returns 0); inside the strip
9473 // (`row_off + tx_high < plane_bh`) they are the left
9474 // neighbour's, already reconstructed; the last row falls back
9475 // to the block-level answer.
9476 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9477 // The unit's own window on the block's palette prediction.
9478 if let Some(buf) = &m.palette_y {
9479 let tu_buf: Vec<u16> = (0..tx_h)
9480 .flat_map(|i| {
9481 let base = (row_off + i) * bw + col_off;
9482 buf[base..base + tx_w].iter().copied()
9483 })
9484 .collect();
9485 set_palette_pred(tu_buf, fctx);
9486 }
9487 if m.skip {
9488 push_intra_rect(0,
9489 tu_px,
9490 tu_py,
9491 tx_w,
9492 tx_h,
9493 m.mode,
9494 m.angle_delta_y,
9495 tu_reach,
9496 &zero_tu,
9497 None,
9498 m.filter_intra,
9499 m.smooth_neighbor, fctx,
9500 );
9501 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9502 } else if luma_64corner && luma_rect.is_none() {
9503 // The un-split 64-level luma transform: `read_coeffs` on the
9504 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9505 // and the real rect shape passed through for
9506 // `av1_nz_map_ctx_offset` -- byte for byte
9507 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9508 // 64-level strip gate already proves. `tx_type` is not coded
9509 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9510 // the square-up size is TX_64X64), and this unit covers its
9511 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9512 if crate::envflags::env_flag!("EC_RECT64TU") {
9513 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9514 }
9515 hit_do! {
9516 RECT64_CORNER_TU_HITS.with(|c| {
9517 let mut v = c.get();
9518 v[usize::from(tx_h > tx_w)] += 1;
9519 c.set(v);
9520 });
9521 }
9522 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9523 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
9524 let (corner, tu_tx_type) = read_coeffs(
9525 dec,
9526 &mut coding,
9527 default_scan(TX32),
9528 0,
9529 dc_sign_ctx(tu_around.2),
9530 TxType::DctDct,
9531 Some((tx_w, tx_h)),
9532 )?;
9533 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
9534 let mut tu_grid = vec![0i32; tx_w * tx_h];
9535 for row in 0..ch {
9536 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
9537 }
9538 let residual = dequant_and_inverse_typed_wh(
9539 &tu_grid,
9540 tx_w,
9541 tx_h,
9542 crate::decode::bit_depth(fctx),
9543 block_q_idx(fctx),
9544 plane_q_delta(0, fctx).0,
9545 plane_q_delta(0, fctx).1,
9546 tu_tx_type,
9547 );
9548 push_intra_rect(0,
9549 tu_px,
9550 tu_py,
9551 tx_w,
9552 tx_h,
9553 m.mode,
9554 m.angle_delta_y,
9555 tu_reach,
9556 &residual,
9557 None,
9558 m.filter_intra,
9559 m.smooth_neighbor, fctx,
9560 );
9561 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9562 } else if let Some((rect_set, rect_scan)) = luma_rect {
9563 // The rect-unit twin of the square arm below: same contexts,
9564 // same order, through the rect coefficient reader. The
9565 // `tx_type` CDF row of a filter-intra block is
9566 // `fimode_to_intradir[filter_intra_mode]`, never the block's
9567 // own (always DC_PRED) mode -- [`read_plane`] applies that
9568 // for the square arm, so this one must too.
9569 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9570 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
9571 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
9572 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
9573 // neighbour-magnitude table is for a unit SMALLER than its
9574 // block. [`decode_block_rect`]'s own unsplit read passes a
9575 // literal 0 for the same reason; this arm applied the table
9576 // unconditionally and desynced every depth-0 rect strip that
9577 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
9578 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
9579 0
9580 } else {
9581 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
9582 };
9583 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
9584 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9585 dec,
9586 &mut coding,
9587 rect_scan,
9588 tx_w,
9589 tx_h,
9590 tu_skip_ctx,
9591 dc_sign_ctx(tu_around.2),
9592 TxType::DctDct,
9593 )?;
9594 let residual = dequant_and_inverse_typed_wh(
9595 &tu_grid,
9596 tx_w,
9597 tx_h,
9598 crate::decode::bit_depth(fctx),
9599 block_q_idx(fctx),
9600 plane_q_delta(0, fctx).0,
9601 plane_q_delta(0, fctx).1,
9602 tu_tx_type,
9603 );
9604 push_intra_rect(0,
9605 tu_px,
9606 tu_py,
9607 tx_w,
9608 tx_h,
9609 m.mode,
9610 m.angle_delta_y,
9611 tu_reach,
9612 &residual,
9613 None,
9614 m.filter_intra,
9615 m.smooth_neighbor, fctx,
9616 );
9617 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9618 } else {
9619 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9620 // This unit is smaller than the block it sits in, so
9621 // `txb_skip_ctx` is the neighbour-magnitude table, not the
9622 // lone-TU 0 (spec `get_txb_ctx_general`).
9623 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9624 let tu_grid = read_plane(
9625 dec,
9626 cdfs,
9627 luma_set,
9628 &luma_scan,
9629 0,
9630 tu_around,
9631 m.mode,
9632 m.mode,
9633 m.angle_delta_y,
9634 tu_reach,
9635 y,
9636 tu_px,
9637 tu_py,
9638 tx_w,
9639 tx_w,
9640 base_q_idx,
9641 None,
9642 m.filter_intra,
9643 Some(tu_skip_ctx),
9644 m.smooth_neighbor, fctx,
9645 )?;
9646 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9647 }
9648 }
9649 }
9650 // CHROMA: one un-split rect transform for the whole strip.
9651 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
9652 // units -- each stamps its own neighbour context as it is read, and the
9653 // whole-block `record_split_luma_rect_mi` below would overwrite all of
9654 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
9655 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
9656 // collected here and replayed after that record.
9657 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new();
9658 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9659 let reach = block_reach;
9660 let (u_grid, v_grid) = if m.skip {
9661 let zero = Grid::Zero(chroma_w * chroma_h);
9662 if let Some((ub, _)) = &m.palette_uv {
9663 set_palette_pred(ub.clone(), fctx);
9664 }
9665 push_intra_rect(1,
9666 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9667 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
9668 );
9669 if let Some((_, vb)) = &m.palette_uv {
9670 set_palette_pred(vb.clone(), fctx);
9671 }
9672 push_intra_rect(2,
9673 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9674 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
9675 );
9676 (zero.clone(), zero)
9677 } else if lossless(fctx) {
9678 // lane-lossless: the strip's chroma plane block is coded as 4x4
9679 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
9680 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
9681 // (`decode_token_recon_block`'s mu-chunk loop, measured against
9682 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
9683 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
9684 // offset (our `+3` row base) whenever the plane block is bigger than
9685 // the transform.
9686 let scan4 = default_scan(4);
9687 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
9688 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
9689 let mut last = [Grid::Zero(16), Grid::Zero(16)];
9690 for plane_idx in 1..=2 {
9691 for cu_row in 0..ch_n {
9692 for cu_col in 0..cw_n {
9693 let luma_span = 8;
9694 let cu_mi = (
9695 mi_r + cu_row * (luma_span / MI),
9696 mi_c + cu_col * (luma_span / MI),
9697 );
9698 let cu_around = neighbours.around_mi(cu_mi, luma_span);
9699 let cu_reach = tu_reach(
9700 bw, bh,
9701 cu_col * luma_span, cu_row * luma_span, luma_span,
9702 block_reach, px, py, y.width, y.height, fctx,
9703 );
9704 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
9705 if let Some((ub, vb)) = &m.palette_uv {
9706 let pbuf = if plane_idx == 1 { ub } else { vb };
9707 set_palette_pred(
9708 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
9709 fctx,
9710 );
9711 }
9712 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9713 let grid = read_plane(
9714 dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
9715 cu_around[plane_idx], m.mode, m.uv_predict_mode,
9716 m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
9717 base_q_idx,
9718 m.alpha.zip(ac).map(|((au, av), ac)| {
9719 (if plane_idx == 1 { au } else { av }, ac)
9720 }),
9721 None, offset, m.smooth_neighbor_uv, fctx,
9722 )?;
9723 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid);
9724 ll_chroma_units.push((cu_mi, plane_idx, grid.clone()));
9725 last[plane_idx - 1] = grid;
9726 }
9727 }
9728 }
9729 let [ug, vg] = last;
9730 (ug, vg)
9731 } else {
9732 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
9733 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
9734 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
9735 // so only the 16x8/8x16 pair takes the mode-indexed default.
9736 let default_tx = if chroma_w.max(chroma_h) >= 32 {
9737 TxType::DctDct
9738 } else {
9739 default_intra_tx_type(m.uv_predict_mode as u8)
9740 };
9741 let around = neighbours.around_mi_rect(at_mi, bw, bh);
9742 let mut grids: Vec<Grid> = Vec::with_capacity(2);
9743 for plane_idx in 1..=2 {
9744 let skip_ctx =
9745 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
9746 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
9747 let (levels, tx_type) = read_coeffs_rect(
9748 dec,
9749 &mut coding,
9750 chroma_scan,
9751 chroma_w,
9752 chroma_h,
9753 skip_ctx,
9754 dc_sign_ctx(around[plane_idx].2),
9755 default_tx,
9756 )?;
9757 // The same delta_q proof the unsplit rect64 path records
9758 // (lane-rectsplit r4: lifting the split-transform refusal moved
9759 // superblock strips onto this path, so only counting there would
9760 // leave the delta_q gate's counter silent for them).
9761 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
9762 hit!(RECT64_QIDX_DRIFT_HITS);
9763 }
9764 let residual = dequant_and_inverse_typed_wh(
9765 &levels,
9766 chroma_w,
9767 chroma_h,
9768 crate::decode::bit_depth(fctx),
9769 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
9770 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
9771 // reading `current_q_idx` here dropped the segment feature
9772 // that every other dequant site applies (class
9773 // `parsed-then-discarded`).
9774 block_q_idx(fctx),
9775 plane_q_delta(plane_idx, fctx).0,
9776 plane_q_delta(plane_idx, fctx).1,
9777 tx_type,
9778 );
9779 let cfl = m
9780 .alpha
9781 .zip(ac)
9782 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
9783 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9784 if let Some((ub, vb)) = &m.palette_uv {
9785 let buf = if plane_idx == 1 { ub } else { vb };
9786 set_palette_pred(buf.clone(), fctx);
9787 }
9788 push_intra_rect(plane_idx,
9789 cpx,
9790 cpy,
9791 chroma_w,
9792 chroma_h,
9793 m.uv_predict_mode,
9794 m.angle_delta_uv,
9795 reach,
9796 &residual,
9797 cfl,
9798 None,
9799 m.smooth_neighbor_uv, fctx,
9800 );
9801 grids.push(levels);
9802 }
9803 let mut it = grids.into_iter();
9804 (it.next().unwrap(), it.next().unwrap())
9805 };
9806 neighbours.record_split_luma_rect_mi(
9807 at_mi,
9808 bw,
9809 bh,
9810 m.mode,
9811 m.uv_predict_mode,
9812 [&u_grid, &v_grid],
9813 );
9814 for (cu_mi, plane, unit) in &ll_chroma_units {
9815 neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit);
9816 }
9817 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
9818 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
9819 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9820 let (rng, _) = dec.debug_state();
9821 eprintln!(
9822 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
9823 tx={tx_w}x{tx_h} rng={rng}"
9824 );
9825 }
9826 Ok(())
9827}
9828
9829/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
9830/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
9831/// because it predicts squares only. Every pixel here goes through the rect
9832/// machinery the key-frame paths already prove: [`decode_rect_split`], which
9833/// at `depth == 0` is the unsplit strip as a single transform unit and
9834/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9835///
9836/// What is genuinely different from [`decode_block_rect`] is the mode
9837/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9838/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9839/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9840/// intra-in-inter arm's own reads at the rect footprint, including its
9841/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9842/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9843/// square and this arm) and a nonzero luma angle delta refused by name.
9844///
9845/// The strip's own neighbour records (luma per transform unit, chroma, skip
9846/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9847/// inter-side bands and the mi map.
9848#[allow(clippy::too_many_arguments)]
9849/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9850/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9851/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9852/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9853/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9854/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
9855/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
9856/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
9857/// table here rather than a shift of `bw.min(bh)`.
9858fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
9859 Some(match (bw.min(bh), bw.max(bh)) {
9860 (8, 16) => (1usize, 1usize),
9861 (16, 32) => (2, 2),
9862 (32, 64) => (3, 3),
9863 (8, 32) => (1, 2),
9864 (16, 64) => (2, 3),
9865 _ => return None,
9866 })
9867}
9868
9869/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
9870/// block path"): the shapes that can reach that arm, enumerated against the
9871/// MEASURED domain of the inter block path
9872/// ([`INTER_BLOCK_SHAPES`], the census the gate
9873/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
9874/// fills from three real streams).
9875///
9876/// [`decode_intra_rect_in_inter`] is called from one site, under
9877/// `write_w != side || write_h != side`, and only after two earlier arms have
9878/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
9879/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
9880/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
9881/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
9882/// and each of those has a row, so the refusal names a shape no measured
9883/// stream can present.
9884#[test]
9885fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
9886 let mut checked = 0;
9887 for &(side, w, h) in &INTER_BLOCK_SHAPES {
9888 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
9889 continue;
9890 }
9891 assert!(
9892 intra_in_inter_size_row(w, h).is_some(),
9893 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
9894 the \"no size-group/tx-category row\" refusal"
9895 );
9896 checked += 1;
9897 }
9898 assert_eq!(
9899 checked, 10,
9900 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
9901 lookup, not the 10 this claim was measured over"
9902 );
9903}
9904
9905/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
9906/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
9907/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
9908/// matched before the square arm's `log2` shortcut).
9909///
9910/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
9911/// row here"; the enumeration below is what proves no conformant block can
9912/// reach it.
9913pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
9914 Some(match (write_w, write_h) {
9915 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
9916 // below maps 128 to row 4 (BLOCK_16X32).
9917 (64, 128) => 14,
9918 (128, 64) => 15,
9919 (128, 128) => 16,
9920 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
9921 (16, 32) => 4,
9922 (32, 16) => 5,
9923 (32, 64) => 6,
9924 (64, 32) => 7,
9925 (8, 32) => 8,
9926 (32, 8) => 9,
9927 (16, 64) => 10,
9928 (64, 16) => 11,
9929 // lane-inter4 r3: the 16x16-level rect inter leaves.
9930 (8, 16) => 12,
9931 (16, 8) => 13,
9932 _ => return None,
9933 })
9934}
9935
9936/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
9937/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
9938/// `block_size_wide`/`block_size_high`).
9939#[cfg(test)]
9940const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
9941 (4, 4),
9942 (4, 8),
9943 (8, 4),
9944 (8, 8),
9945 (8, 16),
9946 (16, 8),
9947 (16, 16),
9948 (16, 32),
9949 (32, 16),
9950 (32, 32),
9951 (32, 64),
9952 (64, 32),
9953 (64, 64),
9954 (64, 128),
9955 (128, 64),
9956 (128, 128),
9957 (4, 16),
9958 (16, 4),
9959 (8, 32),
9960 (32, 8),
9961 (16, 64),
9962 (64, 16),
9963];
9964
9965/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
9966/// shape with no CDF row here" names a shape no conformant stream can present.
9967///
9968/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
9969/// whose `write_w.min(write_h) >= 8` clause is libaom's
9970/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
9971/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
9972/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
9973/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
9974/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
9975/// clause rejects before the lookup.
9976#[test]
9977fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
9978 let mut rows = std::collections::BTreeSet::new();
9979 let mut excluded = 0;
9980 for (w, h) in BLOCK_SIZES_ALL_WH {
9981 if w.min(h) < 8 {
9982 excluded += 1;
9983 assert!(
9984 w == 4 || h == 4,
9985 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
9986 );
9987 continue;
9988 }
9989 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
9990 panic!(
9991 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
9992 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
9993 )
9994 });
9995 assert!(
9996 row < 17,
9997 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
9998 );
9999 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
10000 }
10001 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
10002 assert_eq!(
10003 rows.len(),
10004 17,
10005 "17 eligible footprints must fill all 17 rows of the motion_mode table"
10006 );
10007}
10008
10009fn decode_intra_rect_in_inter(
10010 dec: &mut SymbolDecoder,
10011 cdfs: &mut Cdfs,
10012 neighbours: &mut Neighbours,
10013 at: (usize, usize),
10014 bw: usize,
10015 bh: usize,
10016 skip: bool,
10017 allow_screen_content_tools: bool,
10018 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
10019 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
10020 strip16: Option<(bool, bool)>,
10021 y: &mut PlaneBuf<'static>,
10022 u: &mut PlaneBuf<'static>,
10023 v: &mut PlaneBuf<'static>,
10024 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
10025) -> Result<()> {
10026 // `at` is in MI units (the inter path's own unit since lane-inter4);
10027 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
10028 // below are still keyed by.
10029 let (mi_r, mi_c) = at;
10030 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10031 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
10032 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
10033 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
10034 // finding -- the category is NOT the same for every strip size).
10035 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
10036 // it is refused by name rather than read from the wrong CDF row.
10037 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
10038 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
10039 // tx-depth category is 1 -- but nothing here has to know either, because
10040 // the strip decodes through the very body the KEY FRAME path proves for
10041 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
10042 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
10043 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
10044 // inter-frame difference is the mode-info read, which
10045 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
10046 // `y_mode[0]` plus the `skip` this caller already read.
10047 if let Some((horz, has_chroma)) = strip16 {
10048 // lane-t900 r22: the screen-content refusal here was STALE (class
10049 // stale-premise): [`decode_rect4_16_strip`] takes
10050 // `allow_screen_content_tools` and reads the whole palette syntax
10051 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
10052 // pair) -- the key frame proves that body. Lifted with the 10-bit
10053 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
10054 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
10055 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
10056 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
10057 let res = decode_rect4_16_strip(
10058 dec,
10059 cdfs,
10060 neighbours,
10061 (mi_r, mi_c),
10062 horz,
10063 has_chroma,
10064 // The inter strips of the same partition publish their own
10065 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
10066 // has nothing to add here.
10067 None,
10068 y,
10069 u,
10070 v,
10071 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10072 allow_screen_content_tools,
10073 base_q_idx,
10074 fctx.tx_select_inter.with(std::cell::Cell::get),
10075 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10076 );
10077 fctx.intra_in_inter_mode.with(|c| c.set(None));
10078 let (mode, uv, (tx_w, tx_h)) = res?;
10079 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
10080 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
10081 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
10082 // block of an inter frame, intra ones included, and
10083 // `txfm_partition_update` for the var-tx context. The key-frame body
10084 // writes neither (a key frame has no var-tx tree and its own readers
10085 // use the deblock grid), so the block AFTER this strip read a stale
10086 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
10087 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
10088 // 16x16 row.
10089 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10090 for i in 0..bw / MI {
10091 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10092 *cell = tx_w as u8;
10093 }
10094 }
10095 for i in 0..bh / MI {
10096 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10097 *cell = tx_h as u8;
10098 }
10099 }
10100 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
10101 // coarse 16-px cell holds one entry for the whole 16x16 and the last
10102 // block to write it wins).
10103 neighbours.above_mode[c] = mode;
10104 neighbours.left_mode[r] = mode;
10105 if let Some(uvm) = uv {
10106 neighbours.above_uv_mode[c] = uvm;
10107 neighbours.left_uv_mode[r] = uvm;
10108 }
10109 neighbours.above_side[c] = bw;
10110 neighbours.left_side[r] = bh;
10111 if crate::envflags::env_flag!("EC_INTRA16X4") {
10112 eprintln!(
10113 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
10114 mi_c * MI,
10115 mi_r * MI
10116 );
10117 }
10118 hit_do! {
10119 INTRA16X4_IN_INTER_HITS.with(|h| {
10120 let mut v = h.get();
10121 v[usize::from(!horz)] += 1;
10122 v[2] += usize::from(has_chroma);
10123 h.set(v);
10124 });
10125 }
10126 return Ok(());
10127 }
10128 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
10129 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
10130 // puts BLOCK_128X64/64X128/128X128 in group 3 and
10131 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
10132 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
10133 // block decodes through the very body the KEY FRAME path proves for this
10134 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
10135 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
10136 // `Reach` rule and the frame-edge write clip). The only inter-frame
10137 // differences live inside that body: the mode-info read
10138 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
10139 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
10140 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
10141 // palette (>64) do not exist at this size and are refused by name there.
10142 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
10143 // `intra128_in_inter_witness2.obu` (gate
10144 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
10145 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
10146 // all 15 frames, so the hits are counted out of exact frames (class
10147 // `counter-from-refused-stream`). What r16/r17 could not find, and what
10148 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
10149 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
10150 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
10151 // where the frame EDGE forces it: a partial last superblock row has
10152 // `has_rows128 == false`, so the 128x64 top half is implied, and a
10153 // partial last column implies the 64x128 left half. Put content no
10154 // reference holds (a fresh smooth ramp) in exactly those two bands of an
10155 // inter frame and the encoder codes those forced halves INTRA.
10156 if bw.max(bh) == 128 {
10157 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
10158 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
10159 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
10160 // palette_syntax`), so a 128-root half consumes no palette syntax and
10161 // a screen-content frame's half is syntactically identical to the
10162 // non-screen one this arm already decodes byte-exact.
10163 if coeff_trace_on() {
10164 // lane-t900 r16: which decode-order frame this arm fires in --
10165 // interleaved with the `EC_COEFF_FRAME` markers, this is what
10166 // proves the hit is counted out of a frame that compares exact
10167 // (class `counter-from-refused-stream`).
10168 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
10169 }
10170 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
10171 let res = decode_block_128rect(
10172 dec,
10173 cdfs,
10174 neighbours,
10175 (r, c),
10176 bw,
10177 bh,
10178 y,
10179 u,
10180 v,
10181 base_q_idx,
10182 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10183 allow_screen_content_tools,
10184 fctx.tx_select_inter.with(std::cell::Cell::get),
10185 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10186 );
10187 fctx.intra_in_inter_mode.with(|c| c.set(None));
10188 return res;
10189 }
10190 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
10191 if crate::envflags::env_flag!("EC_OBMCREC") {
10192 eprintln!(
10193 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
10194 );
10195 }
10196 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
10197 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
10198 // can arrive here are enumerated against the measured block-shape
10199 // census ([`INTER_BLOCK_SHAPES`]) by
10200 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
10201 // -- every one of them has a row, so this arm names a shape no stream
10202 // has been able to present.
10203 return Err(unsupported(format!(
10204 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
10205 )));
10206 };
10207 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
10208 // screen-content frame ("palette syntax is consumed for square blocks
10209 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
10210 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
10211 // it, while the 2:1 reader inlined further down now codes the same syntax
10212 // itself. A real `--tune-content=screen` inter stream reached this refusal
10213 // on 8x16 / 16x8 strips (gate
10214 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
10215 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
10216 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
10217 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
10218 // luma/chroma transform tables, the per-unit split walk and the strip's
10219 // own neighbour records). The ONLY difference on an inter frame is the
10220 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
10221 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
10222 // this caller already read. `tx_cat` above is the same category those
10223 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
10224 // `decode_block_rect64`), asserted here so a future shape cannot drift.
10225 if bw.max(bh) == 4 * bw.min(bh) {
10226 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
10227 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
10228 let res = if bw.max(bh) == 64 {
10229 decode_block_rect64(
10230 dec,
10231 cdfs,
10232 neighbours,
10233 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
10234 bw,
10235 bh,
10236 y,
10237 u,
10238 v,
10239 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10240 allow_screen_content_tools,
10241 base_q_idx,
10242 fctx.tx_select_inter.with(std::cell::Cell::get),
10243 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10244 )
10245 } else {
10246 decode_block_rect4(
10247 dec,
10248 cdfs,
10249 neighbours,
10250 (mi_r, mi_c),
10251 bw,
10252 bh,
10253 None,
10254 y,
10255 u,
10256 v,
10257 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10258 allow_screen_content_tools,
10259 base_q_idx,
10260 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10261 )
10262 .map(|_| ())
10263 };
10264 fctx.intra_in_inter_mode.with(|c| c.set(None));
10265 res?;
10266 let shape = match (bw, bh) {
10267 (64, 16) => 0,
10268 (16, 64) => 1,
10269 (32, 8) => 2,
10270 _ => 3,
10271 };
10272 hit_do! {
10273 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10274 let mut v = h.get();
10275 v[shape] += 1;
10276 h.set(v);
10277 });
10278 }
10279 return Ok(());
10280 }
10281 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10282 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10283 // own, so a cross-decoder bisection could only see the block's first
10284 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10285 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10286 if step_trace {
10287 eprintln!(
10288 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10289 dec.debug_state().0
10290 );
10291 }
10292 if mode >= 13 {
10293 return Err(unsupported(
10294 "an intra mode this decoder does not code (round 2)",
10295 ));
10296 }
10297 // lane-angleinter (merged on main for the square intra-in-inter arm):
10298 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10299 // directional predictor; this arm refused a nonzero one before the merge.
10300 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10301 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10302 } else {
10303 0
10304 };
10305 if angle_delta_y != 0 {
10306 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10307 }
10308 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10309 // superblock-level strip reads the no-CFL alphabet -- the same split
10310 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10311 let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
10312 let uv_mode = if cfl_allowed {
10313 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10314 } else {
10315 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10316 };
10317 if step_trace {
10318 eprintln!(
10319 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10320 u8::from(cfl_allowed),
10321 dec.debug_state().0
10322 );
10323 }
10324 if (9..=12).contains(&uv_mode) {
10325 hit!(SMOOTH_UV_HITS);
10326 }
10327 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10328 Some(read_cfl_alphas(dec, cdfs))
10329 } else {
10330 None
10331 };
10332 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10333 DC_PRED
10334 } else {
10335 uv_mode
10336 };
10337 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10338 hit!(DIRECTIONAL_UV_HITS);
10339 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10340 } else {
10341 0
10342 };
10343 if angle_delta_uv != 0 {
10344 hit!(UV_ANGLE_DELTA_HITS);
10345 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10346 }
10347 // `read_palette_mode_info` (spec 5.11.13), in the position
10348 // `read_intra_block_mode_info` writes it: after the chroma mode and
10349 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10350 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10351 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10352 // skipping the syntax here desynced the tile at the strip's own symbol.
10353 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10354 // context and colour cache at its own mi position, and the two
10355 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10356 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10357 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10358 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10359 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10360 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10361 if allow_screen_content_tools
10362 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10363 {
10364 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10365 let use_palette_y =
10366 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10367 if use_palette_y {
10368 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10369 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10370 }
10371 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10372 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10373 let use_palette_uv =
10374 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10375 if crate::envflags::env_flag!("EC_PALSYN") {
10376 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);
10377 }
10378 if use_palette_uv {
10379 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10380 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10381 palette_uv_pending = Some((n, u_colors, v_colors));
10382 }
10383 }
10384 // lane-fiinter (merged on main for the square intra-in-inter arm):
10385 // `read_filter_intra_mode_info` is the tail of
10386 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10387 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10388 // 2:1 strips with both sides <= 32 -- their own CDF rows
10389 // ([`filter_intra_size_class_rect`]).
10390 let mut filter_intra = None;
10391 if mode == DC_PRED
10392 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10393 // `av1_filter_intra_allowed` excludes a palette-Y block.
10394 && palette_y_pending.is_none()
10395 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10396 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10397 {
10398 hit!(FILTER_INTRA_HITS);
10399 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10400 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10401 }
10402 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10403 let palette_y = palette_y_pending.map(|(n, colors)| {
10404 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
10405 hit!(PALETTE_HITS);
10406 hit!(PALETTE_RECT_HITS);
10407 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10408 PaletteY { size: n, colors, map }
10409 });
10410 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10411 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10412 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
10413 hit!(PALETTE_UV_HITS);
10414 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10415 PaletteUv { size: n, u_colors, v_colors, map }
10416 });
10417 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10418 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10419 // chroma ones -- [`decode_block_rect`]'s own pair.
10420 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10421 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10422 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10423 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10424 // one exactly as [`decode_leaf8`] already does (class
10425 // context-read-from-one-cell).
10426 let coarse_pair = neighbours.modes_above_left(r, c);
10427 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10428 if (nb_above_mode, nb_left_mode) != coarse_pair {
10429 hit!(EDGE_FILTER_MI_FIX_HITS);
10430 }
10431 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10432 if smooth_neighbor {
10433 hit!(SMOOTH_LUMA_HITS);
10434 }
10435 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10436 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10437 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
10438 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
10439 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10440 let d = match tx_cat {
10441 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10442 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10443 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10444 };
10445 if step_trace {
10446 eprintln!(
10447 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10448 dec.debug_state().0
10449 );
10450 }
10451 d
10452 } else {
10453 0
10454 };
10455 if depth != 0 || lossless(fctx) {
10456 hit!(TX_DEPTH_HITS);
10457 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10458 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10459 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10460 hit_do! {
10461 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10462 let mut v = h.get();
10463 v[depth.min(2)] += 1;
10464 h.set(v);
10465 });
10466 }
10467 }
10468 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10469 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10470 // the two are indistinguishable when the diagnostic fires on splits alone.
10471 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10472 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10473 }
10474 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10475 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10476 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10477 // of an inter frame, intra ones included -- with the skip term 0 it
10478 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10479 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10480 // wrote neither, so the next block's var-tx `txfm_partition` context read
10481 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10482 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10483 // mi(16,0) and desyncing the tile at that symbol.
10484 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10485 let modes = RectStripModes {
10486 skip,
10487 mode,
10488 angle_delta_y,
10489 uv_predict_mode,
10490 angle_delta_uv,
10491 alpha,
10492 filter_intra,
10493 smooth_neighbor,
10494 smooth_neighbor_uv,
10495 palette_y: palette_y
10496 .as_ref()
10497 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10498 palette_uv: palette_uv.as_ref().map(|p| {
10499 (
10500 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10501 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10502 )
10503 }),
10504 };
10505 decode_rect_split(
10506 dec,
10507 cdfs,
10508 neighbours,
10509 (mi_r, mi_c),
10510 bw,
10511 bh,
10512 tx_w,
10513 tx_h,
10514 &modes,
10515 y,
10516 u,
10517 v,
10518 base_q_idx,
10519 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10520 )?;
10521 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
10522 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
10523 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
10524 // left column over its height. This arm wrote neither before lane-intrasplit
10525 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
10526 // context across the strip's footprint.
10527 for i in 0..bw / MI {
10528 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10529 *cell = tx_w as u8;
10530 }
10531 }
10532 for i in 0..bh / MI {
10533 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10534 *cell = tx_h as u8;
10535 }
10536 }
10537 // The strip's own palette state into the mi-granular neighbour bands, so
10538 // the next block's colour cache and `palette_y_mode` context are libaom's.
10539 record_strip_palette(
10540 neighbours,
10541 (mi_r, mi_c),
10542 bw,
10543 bh,
10544 palette_y.as_ref().map_or(0, |p| p.size),
10545 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
10546 palette_uv.as_ref().map_or(0, |p| p.size),
10547 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
10548 );
10549 let class = match bw.max(bh) {
10550 64 => 0,
10551 32 => 1,
10552 _ => 2,
10553 };
10554 hit_do! {
10555 INTRA_RECT_IN_INTER_HITS.with(|h| {
10556 let mut v = h.get();
10557 v[class] += 1;
10558 h.set(v);
10559 });
10560 }
10561 Ok(())
10562}
10563
10564/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
10565/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
10566/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
10567/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
10568/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
10569/// has no rectangular-transform coefficient reader, and a chroma plane here
10570/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
10571/// with no depth-based square-tiling escape the way luma's own resolved
10572/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
10573/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
10574#[allow(clippy::too_many_arguments)]
10575fn decode_block_rect(
10576 dec: &mut SymbolDecoder,
10577 cdfs: &mut Cdfs,
10578 neighbours: &mut Neighbours,
10579 at: (usize, usize),
10580 bw: usize,
10581 bh: usize,
10582 y: &mut PlaneBuf<'static>,
10583 u: &mut PlaneBuf<'static>,
10584 v: &mut PlaneBuf<'static>,
10585 enable_filter_intra: bool,
10586 allow_screen_content_tools: bool,
10587 base_q_idx: u8,
10588 tx_select: bool,
10589 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10590) -> Result<()> {
10591 let (r, c) = at;
10592 let (px, py) = (c * SUB, r * SUB);
10593 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10594 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10595 let palette_uv_cache = neighbours.palette_uv_cache(at);
10596 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10597 read_intra_mode_rect(
10598 dec,
10599 cdfs,
10600 nb_above_mode,
10601 nb_left_mode,
10602 true,
10603 true,
10604 bw,
10605 bh,
10606 enable_filter_intra,
10607 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10608 allow_screen_content_tools,
10609 Some((palette_ctx, &palette_cache)),
10610 &palette_uv_cache,
10611 r * (SUB / MI),
10612 c * (SUB / MI), fctx,
10613 )?;
10614 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10615 if smooth_neighbor {
10616 hit!(SMOOTH_LUMA_HITS);
10617 }
10618 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
10619 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
10620 // `uv_mode`, not the luma one.
10621 let smooth_neighbor_uv =
10622 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10623 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
10624 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
10625 // rectangle just as happily), so a `use_filter_intra` strip at this level
10626 // predicts instead of refusing. The below-16x16 leaf arm
10627 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
10628 if filter_intra.is_some() {
10629 hit!(FILTER_INTRA_RECT_HITS);
10630 }
10631 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10632 DC_PRED
10633 } else {
10634 uv_mode
10635 };
10636 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10637 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
10638 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
10639 // one did not, so with `--enable-tx-size-search=0` -- which several gate
10640 // recipes use -- the decoder consumed a symbol the encoder never wrote and
10641 // desynced the tile from that point on. That is why both strips of the
10642 // pinned HORZ quadrant were wrong from their very first pixel, and why our
10643 // range after the read equalled the oracle's range for the whole block.
10644 let depth = if tx_select {
10645 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10646 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10647 // the 16x4 intra-in-inter strips already do); the key frame's
10648 // deblock-grid approximation is only right where those bands were never
10649 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10650 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10651 // `tx_size_cat2` row 1 where libaom reads row 2.
10652 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10653 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10654 } else {
10655 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10656 };
10657 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10658 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10659 eprintln!(
10660 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10661 dec.debug_state().0
10662 );
10663 }
10664 d
10665 } else {
10666 0
10667 };
10668 if depth != 0 || lossless(fctx) {
10669 hit!(TX_DEPTH_HITS);
10670 // lane-rectsplit r1: a split transform is predicted and reconstructed
10671 // per transform unit, each unit taking its edges from the previous
10672 // unit's reconstruction inside this same strip (spec 5.11.36) --
10673 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10674 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10675 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10676 eprintln!(
10677 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10678 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10679 angle_y={angle_delta_y}"
10680 );
10681 }
10682 let modes = RectStripModes {
10683 skip,
10684 mode,
10685 angle_delta_y,
10686 uv_predict_mode,
10687 angle_delta_uv,
10688 alpha,
10689 filter_intra,
10690 smooth_neighbor,
10691 smooth_neighbor_uv,
10692 palette_y: palette_y
10693 .as_ref()
10694 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10695 palette_uv: palette_uv.as_ref().map(|p| {
10696 (
10697 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10698 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10699 )
10700 }),
10701 };
10702 if palette_y.is_some() || palette_uv.is_some() {
10703 hit!(PALETTE_SPLIT_TX_HITS);
10704 }
10705 decode_rect_split(
10706 dec,
10707 cdfs,
10708 neighbours,
10709 (mi_r, mi_c),
10710 bw,
10711 bh,
10712 tx_w,
10713 tx_h,
10714 &modes,
10715 y,
10716 u,
10717 v,
10718 base_q_idx,
10719 reduced_tx_set, fctx,
10720 )?;
10721 // This early return skips this fn's own tail, so the palette
10722 // neighbour state has to be stamped HERE too: without it a split-tx
10723 // strip left the above/left palette arrays holding a DEAD block's
10724 // colours, and the next block's colour cache
10725 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
10726 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
10727 // and only those pixels were wrong (lane-palette2 r10).
10728 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10729 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10730 let (puv_size, puv_colors) =
10731 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10732 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10733 hit!(RECT_PARTITION_HITS);
10734 return Ok(());
10735 }
10736 let (tx_w, tx_h) = (bw, bh);
10737 let (cpx, cpy) = (px / 2, py / 2);
10738 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10739 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10740 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10741 let (rng, _) = dec.debug_state();
10742 eprintln!(
10743 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
10744 skip={} tx={depth} rng={rng}",
10745 skip as i32
10746 );
10747 }
10748 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
10749 // block's prediction is the reconstructed colour-index map, set fresh
10750 // right before each `reconstruct_rect` call below (lane-palette2 r4).
10751 if let Some(ref pyv) = palette_y {
10752 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10753 set_palette_pred(buf, fctx);
10754 }
10755 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10756 (
10757 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10758 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10759 )
10760 });
10761 if skip {
10762 push_intra_rect(0,
10763 px,
10764 py,
10765 bw,
10766 bh,
10767 mode,
10768 angle_delta_y,
10769 reach,
10770 &ZERO_RESIDUAL[..bw * bh],
10771 None,
10772 filter_intra,
10773 smooth_neighbor, fctx,
10774 );
10775 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10776 if let Some((ub, _)) = &palette_uv_bufs {
10777 set_palette_pred(ub.clone(), fctx);
10778 }
10779 push_intra_rect(1,
10780 cpx,
10781 cpy,
10782 chroma_w,
10783 chroma_h,
10784 uv_predict_mode,
10785 angle_delta_uv,
10786 reach,
10787 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10788 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10789 None,
10790 smooth_neighbor_uv, fctx,
10791 );
10792 if let Some((_, vb)) = &palette_uv_bufs {
10793 set_palette_pred(vb.clone(), fctx);
10794 }
10795 push_intra_rect(2,
10796 cpx,
10797 cpy,
10798 chroma_w,
10799 chroma_h,
10800 uv_predict_mode,
10801 angle_delta_uv,
10802 reach,
10803 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10804 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10805 None,
10806 smooth_neighbor_uv, fctx,
10807 );
10808 neighbours.record_rect(
10809 at,
10810 bw,
10811 bh,
10812 mode,
10813 uv_predict_mode,
10814 &[
10815 &ZERO_RESIDUAL[..bw * bh],
10816 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10817 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10818 ],
10819 );
10820 } else {
10821 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
10822 // reduces both size pairs to their square-up CDF sets
10823 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
10824 // doc comments); the scan order and 2D context tables are the real
10825 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
10826 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
10827 (&SCAN_32X16, &SCAN_16X8)
10828 } else {
10829 (&SCAN_16X32, &SCAN_8X16)
10830 };
10831 // lane-rectwire r3: real coefficients desync a pixel-exact gate
10832 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
10833 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
10834 // pixel (not a subtle context-table off-by-one), while the sibling
10835 // non-rect quadrants of the same frame match. Range-ladder bisection
10836 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
10837 // but the intra key-frame path has no traced symbol between the
10838 // partition read and the first coefficient block (mode/skip/tx_depth
10839 // reads are all untraced in libaom's decodeframe.c intra path, unlike
10840 // the inter EC_TRACE_MODE this round added), so a same-length range
10841 // comparison wasn't reachable within budget -- see
10842 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10843 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10844 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10845 // libaom and match). lane-rectwire r4: range-ladder against the
10846 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10847 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10848 // both confirmed in sync -- rng=58692 on both sides right after
10849 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10850 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10851 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10852 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
10853 // its own tx_size read) unless oracle's tx symbol is a near-certainty
10854 // CDF that barely narrows the range -- i.e. this decoder's
10855 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
10856 // a 32x16/16x32 strip is the first diverging symbol, not the
10857 // coefficient-context math r3 already cleared. Not confirmed byte-
10858 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
10859 // `read_tx_size`'s own rng, not attempted this round -- budget), so
10860 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
10861 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
10862 // it unconditionally where both square paths gate on `tx_select`. With
10863 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
10864 // decoder consumed one that was never there.
10865 {
10866 let around = neighbours.around_rect(at, bw, bh);
10867 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
10868 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10869 dec,
10870 &mut luma_coding,
10871 luma_scan,
10872 bw,
10873 bh,
10874 0,
10875 dc_sign_ctx(around[0].2),
10876 TxType::DctDct,
10877 )?;
10878 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10879 let (rng, _) = dec.debug_state();
10880 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10881 }
10882 let luma_residual = dequant_and_inverse_typed_wh(
10883 &luma_levels,
10884 bw,
10885 bh,
10886 crate::decode::bit_depth(fctx),
10887 block_q_idx(fctx),
10888 plane_q_delta(0, fctx).0,
10889 plane_q_delta(0, fctx).1,
10890 luma_tx_type,
10891 );
10892 push_intra_rect(0,
10893 px,
10894 py,
10895 bw,
10896 bh,
10897 mode,
10898 angle_delta_y,
10899 reach,
10900 &luma_residual,
10901 None,
10902 filter_intra,
10903 smooth_neighbor, fctx,
10904 );
10905 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10906 if let Some((ub, _)) = &palette_uv_bufs {
10907 set_palette_pred(ub.clone(), fctx);
10908 }
10909 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10910 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10911 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10912 let (u_levels, u_tx_type) = read_coeffs_rect(
10913 dec,
10914 &mut u_coding,
10915 chroma_scan,
10916 chroma_w,
10917 chroma_h,
10918 u_skip_ctx,
10919 dc_sign_ctx(around[1].2),
10920 u_default_tx,
10921 )?;
10922 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10923 let (rng, _) = dec.debug_state();
10924 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10925 }
10926 let u_residual = dequant_and_inverse_typed_wh(
10927 &u_levels,
10928 chroma_w,
10929 chroma_h,
10930 crate::decode::bit_depth(fctx),
10931 block_q_idx(fctx),
10932 plane_q_delta(1, fctx).0,
10933 plane_q_delta(1, fctx).1,
10934 u_tx_type,
10935 );
10936 push_intra_rect(1,
10937 cpx,
10938 cpy,
10939 chroma_w,
10940 chroma_h,
10941 uv_predict_mode,
10942 angle_delta_uv,
10943 reach,
10944 &u_residual,
10945 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10946 None,
10947 smooth_neighbor_uv, fctx,
10948 );
10949 if let Some((_, vb)) = &palette_uv_bufs {
10950 set_palette_pred(vb.clone(), fctx);
10951 }
10952 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10953 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10954 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10955 let (v_levels, v_tx_type) = read_coeffs_rect(
10956 dec,
10957 &mut v_coding,
10958 chroma_scan,
10959 chroma_w,
10960 chroma_h,
10961 v_skip_ctx,
10962 dc_sign_ctx(around[2].2),
10963 v_default_tx,
10964 )?;
10965 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10966 let (rng, _) = dec.debug_state();
10967 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10968 }
10969 let v_residual = dequant_and_inverse_typed_wh(
10970 &v_levels,
10971 chroma_w,
10972 chroma_h,
10973 crate::decode::bit_depth(fctx),
10974 block_q_idx(fctx),
10975 plane_q_delta(2, fctx).0,
10976 plane_q_delta(2, fctx).1,
10977 v_tx_type,
10978 );
10979 push_intra_rect(2,
10980 cpx,
10981 cpy,
10982 chroma_w,
10983 chroma_h,
10984 uv_predict_mode,
10985 angle_delta_uv,
10986 reach,
10987 &v_residual,
10988 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10989 None,
10990 smooth_neighbor_uv, fctx,
10991 );
10992 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
10993 hit!(RECT_COEFF_HITS);
10994 }
10995 }
10996 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10997 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10998 let (puv_size, puv_colors) =
10999 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11000 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
11001 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
11002 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
11003 hit!(RECT_PARTITION_HITS);
11004 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11005 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
11006 }
11007 Ok(())
11008}
11009
11010/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
11011/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
11012/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
11013/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
11014/// the second strip of a HORZ/VERT split sits offset by half the 16x16
11015/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
11016/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
11017/// previous strip is directly above (same column, `mi_h` rows up) or
11018/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
11019/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
11020/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
11021/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
11022/// this strip's real position, never the coarse `record_rect` (which the
11023/// caller uses once, after both strips, exactly like the `VERT_B` arm next
11024/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
11025/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
11026/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
11027/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
11028#[allow(clippy::too_many_arguments)]
11029fn decode_leaf_rect(
11030 dec: &mut SymbolDecoder,
11031 cdfs: &mut Cdfs,
11032 neighbours: &mut Neighbours,
11033 outer_at: (usize, usize),
11034 leaf_mi: (usize, usize),
11035 bw: usize,
11036 bh: usize,
11037 prev_leaf: Option<((usize, usize), usize)>,
11038 y: &mut PlaneBuf<'static>,
11039 u: &mut PlaneBuf<'static>,
11040 v: &mut PlaneBuf<'static>,
11041 enable_filter_intra: bool,
11042 allow_screen_content_tools: bool,
11043 base_q_idx: u8,
11044 tx_select: bool,
11045 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11046) -> Result<usize> {
11047 let _ = base_q_idx;
11048 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11049 eprintln!(
11050 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
11051 dec.debug_state().0
11052 );
11053 }
11054 let (r, c) = outer_at;
11055 let mut above_mode = neighbours.above_mode[c];
11056 let mut left_mode = neighbours.left_mode[r];
11057 let (mi_w, mi_h) = (bw / MI, bh / MI);
11058 if let Some(((pr, pc), pmode)) = prev_leaf {
11059 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
11060 above_mode = pmode;
11061 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
11062 left_mode = pmode;
11063 }
11064 }
11065 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
11066 // cannot hold the modes a split (or a pair of strips) leaves behind, so
11067 // when the map holds the block at exactly this strip's above/left mi it
11068 // is the neighbour libaom's `above_mi`/`left_mi` reads.
11069 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
11070 // availability-correct -- four 16x8 strips share one coarse 16x16
11071 // `left_mode` cell too, so the fallback must not stand in for an absent
11072 // tile-edge neighbour.
11073 let (above_mode, left_mode) =
11074 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
11075 let smooth_neighbor =
11076 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11077 if smooth_neighbor {
11078 hit!(SMOOTH_LUMA_HITS);
11079 }
11080 // The palette-Y mode CDF row is picked by the neighbours' palette use
11081 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
11082 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
11083 // a palette narrows the wrong interval and desyncs the tile even when the
11084 // decoded bit is the same. The cell is the 16px-SUB cell containing the
11085 // leaf (the palette neighbour arrays have no finer granularity).
11086 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
11087 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
11088 // exclusion and the neighbour palette lookup itself are mi-granular
11089 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
11090 let pal_at = leaf_mi;
11091 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11092 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11093 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11094 read_intra_mode_rect(
11095 dec,
11096 cdfs,
11097 above_mode,
11098 left_mode,
11099 true,
11100 true,
11101 bw,
11102 bh,
11103 enable_filter_intra,
11104 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
11105 allow_screen_content_tools,
11106 Some((palette_ctx, &palette_cache)),
11107 &palette_uv_cache,
11108 leaf_mi.0,
11109 leaf_mi.1, fctx,
11110 )?;
11111 // lane-kf900 r4: palette prediction on this shape, the same colour-index
11112 // map -> base colours buffer [`decode_block_rect`] hands each
11113 // `reconstruct_rect` through [`set_palette_pred`].
11114 if palette_y.is_some() || palette_uv.is_some() {
11115 hit!(RECT4_PALETTE_HITS);
11116 }
11117 let palette_y_buf: Option<Vec<u16>> = palette_y
11118 .as_ref()
11119 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11120 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11121 (
11122 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11123 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11124 )
11125 });
11126 let (pal_y_size, pal_y_colors) =
11127 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11128 let (pal_uv_size, pal_uv_colors) =
11129 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11130 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11131 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
11132 }
11133 if filter_intra.is_some() {
11134 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
11135 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
11136 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
11137 // below already makes; this refusal was square-only prose.
11138 hit!(FILTER_INTRA_RECT_HITS);
11139 hit!(FILTER_INTRA_RECT_SUB16_HITS);
11140 }
11141 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11142 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
11143 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
11144 // a constant `false`.
11145 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
11146 let depth = if tx_select {
11147 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
11148 // every other rect reader now does -- a no-op on a key frame.
11149 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11150 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
11151 } else {
11152 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
11153 };
11154 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
11155 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
11156 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
11157 // count (3), different CDF row: a wrong-table read of a real symbol,
11158 // the class that cost lane-rectsplit r1 its 64x32 depth.
11159 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
11160 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
11161 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
11162 // function also decodes) sit at depth 2, so they read
11163 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
11164 // while `tx_size_cat2` belongs to the 32-level shapes
11165 // ([`decode_block_rect`]). Both tables carry three symbols, so the
11166 // wrong one decodes a plausible depth from the wrong probabilities:
11167 // the range diverges silently at the first such leaf and every later
11168 // symbol in the tile is read from the wrong place (class
11169 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
11170 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
11171 } else {
11172 0
11173 };
11174 if depth != 0 || lossless(fctx) {
11175 // The same per-transform-unit walk the bigger strips take
11176 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
11177 // depth 2), addressed at this leaf's own mi position.
11178 hit!(TX_DEPTH_HITS);
11179 hit!(SUB16_SPLIT_HITS);
11180 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11181 let modes = RectStripModes {
11182 skip,
11183 mode,
11184 angle_delta_y,
11185 uv_predict_mode,
11186 angle_delta_uv,
11187 alpha,
11188 filter_intra,
11189 smooth_neighbor,
11190 // lane-rectsplitx r3: the split arm hard-coded `false` here while
11191 // the unsplit arm below passes the real neighbour answer -- chroma
11192 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
11193 smooth_neighbor_uv,
11194 palette_y: palette_y_buf.clone(),
11195 palette_uv: palette_uv_bufs.clone(),
11196 };
11197 if palette_y.is_some() || palette_uv.is_some() {
11198 hit!(PALETTE_SPLIT_TX_HITS);
11199 }
11200 decode_rect_split(
11201 dec,
11202 cdfs,
11203 neighbours,
11204 leaf_mi,
11205 bw,
11206 bh,
11207 tx_w,
11208 tx_h,
11209 &modes,
11210 y,
11211 u,
11212 v,
11213 base_q_idx,
11214 reduced_tx_set, fctx,
11215 )?;
11216 record_strip_palette(
11217 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11218 );
11219 return Ok(mode);
11220 }
11221 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11222 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11223 let (cpx, cpy) = (px / 2, py / 2);
11224 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11225 let (luma_levels, u_levels, v_levels);
11226 if skip {
11227 luma_levels = Grid::Zero(bw * bh);
11228 u_levels = Grid::Zero(chroma_w * chroma_h);
11229 v_levels = Grid::Zero(chroma_w * chroma_h);
11230 if let Some(b) = &palette_y_buf {
11231 set_palette_pred(b.clone(), fctx);
11232 }
11233 push_intra_rect(0,
11234 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
11235 smooth_neighbor, fctx,
11236 );
11237 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11238 if let Some((ub, _)) = &palette_uv_bufs {
11239 set_palette_pred(ub.clone(), fctx);
11240 }
11241 push_intra_rect(1,
11242 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
11243 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11244 );
11245 if let Some((_, vb)) = &palette_uv_bufs {
11246 set_palette_pred(vb.clone(), fctx);
11247 }
11248 push_intra_rect(2,
11249 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
11250 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11251 );
11252 } else {
11253 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
11254 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
11255 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
11256 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
11257 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
11258 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
11259 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
11260 (&SCAN_16X8, &SCAN_8X4)
11261 } else {
11262 (&SCAN_8X16, &SCAN_4X8)
11263 };
11264 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
11265 let luma_set = if reduced_tx_set {
11266 TxbSet::LumaRect16x8
11267 } else {
11268 TxbSet::LumaRect16x8Set1
11269 };
11270 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
11271 let (l_levels, luma_tx_type) = read_coeffs_rect(
11272 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
11273 )?;
11274 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11275 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
11276 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
11277 }
11278 luma_levels = l_levels;
11279 let luma_residual = dequant_and_inverse_typed_wh(
11280 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
11281 block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
11282 );
11283 if let Some(b) = &palette_y_buf {
11284 set_palette_pred(b.clone(), fctx);
11285 }
11286 push_intra_rect(0,
11287 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
11288 smooth_neighbor, fctx,
11289 );
11290 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11291 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11292 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11293 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11294 let (u_l, u_tx_type) = read_coeffs_rect(
11295 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11296 dc_sign_ctx(around[1].2), u_default_tx,
11297 )?;
11298 u_levels = u_l;
11299 let u_residual = dequant_and_inverse_typed_wh(
11300 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11301 block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
11302 );
11303 if let Some((ub, _)) = &palette_uv_bufs {
11304 set_palette_pred(ub.clone(), fctx);
11305 }
11306 push_intra_rect(1,
11307 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
11308 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11309 );
11310 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11311 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11312 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11313 let (v_l, v_tx_type) = read_coeffs_rect(
11314 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11315 dc_sign_ctx(around[2].2), v_default_tx,
11316 )?;
11317 v_levels = v_l;
11318 let v_residual = dequant_and_inverse_typed_wh(
11319 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11320 block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
11321 );
11322 if let Some((_, vb)) = &palette_uv_bufs {
11323 set_palette_pred(vb.clone(), fctx);
11324 }
11325 push_intra_rect(2,
11326 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
11327 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11328 );
11329 hit!(RECT_LEAF_COEFF_HITS);
11330 }
11331 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11332 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
11333 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11334 // The leaf's own palette state (`0` clears, as this site always did
11335 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
11336 // AXIS only until the pair's closing leaf: the coarse cell holds one
11337 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
11338 // real left neighbour leaf 1 reads (lane-kf900 r4).
11339 record_strip_palette(
11340 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11341 );
11342 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
11343 // rows -- record the whole span, not one cell.
11344 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
11345 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
11346 Ok(mode)
11347}
11348
11349/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
11350/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
11351/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
11352/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
11353/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
11354/// strip's mode so this one's mode context sees its true above/left
11355/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
11356///
11357/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
11358/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
11359/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
11360/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
11361/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
11362/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
11363/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
11364///
11365/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
11366/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
11367/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
11368/// unexamined.
11369#[allow(clippy::too_many_arguments)]
11370fn decode_block_rect4(
11371 dec: &mut SymbolDecoder,
11372 cdfs: &mut Cdfs,
11373 neighbours: &mut Neighbours,
11374 strip_mi: (usize, usize),
11375 bw: usize,
11376 bh: usize,
11377 prev_strip: Option<((usize, usize), usize)>,
11378 y: &mut PlaneBuf<'static>,
11379 u: &mut PlaneBuf<'static>,
11380 v: &mut PlaneBuf<'static>,
11381 enable_filter_intra: bool,
11382 allow_screen_content_tools: bool,
11383 base_q_idx: u8,
11384 tx_select: bool, fctx: &crate::decode::FrameCtx,
11385) -> Result<(usize, usize)> {
11386 let _ = base_q_idx;
11387 let (mi_r, mi_c) = strip_mi;
11388 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11389 let (mi_w, mi_h) = (bw / MI, bh / MI);
11390 let mut above_mode = neighbours.above_mode[c];
11391 let mut left_mode = neighbours.left_mode[r];
11392 if let Some(((pr, pc), pmode)) = prev_strip {
11393 if pc == mi_c && mi_r == pr + mi_h {
11394 above_mode = pmode;
11395 } else if pr == mi_r && mi_c == pc + mi_w {
11396 left_mode = pmode;
11397 }
11398 }
11399 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
11400 // availability-correct neighbour modes (see
11401 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
11402 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
11403 let (above_mode, left_mode) =
11404 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
11405 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
11406 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
11407 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
11408 // wrong interval, so a screen-content tile desynced at the first strip
11409 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
11410 let pal_at = (mi_r, mi_c);
11411 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11412 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11413 let (
11414 skip,
11415 mode,
11416 angle_delta_y,
11417 uv_mode,
11418 angle_delta_uv,
11419 alpha,
11420 filter_intra,
11421 palette_y,
11422 palette_uv,
11423 ) = read_intra_mode_rect(
11424 dec,
11425 cdfs,
11426 above_mode,
11427 left_mode,
11428 true,
11429 true,
11430 bw,
11431 bh,
11432 enable_filter_intra,
11433 neighbours.skip_txfm_ctx(mi_r, mi_c),
11434 allow_screen_content_tools,
11435 Some((palette_ctx, &palette_cache)),
11436 &palette_uv_cache,
11437 mi_r,
11438 mi_c, fctx,
11439 )?;
11440 // lane-kf900 r4: palette prediction on this shape, exactly as
11441 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
11442 // mapped through the base colours IS the prediction (it reads no edge
11443 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
11444 if palette_y.is_some() || palette_uv.is_some() {
11445 hit!(RECT4_PALETTE_HITS);
11446 }
11447 let palette_y_buf: Option<Vec<u16>> = palette_y
11448 .as_ref()
11449 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11450 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11451 (
11452 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11453 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11454 )
11455 });
11456 let (pal_y_size, pal_y_colors) =
11457 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11458 let (pal_uv_size, pal_uv_colors) =
11459 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11460 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11461 if smooth_neighbor {
11462 hit!(SMOOTH_LUMA_HITS);
11463 }
11464 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
11465 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
11466 // `r * (SUB / MI)` names a different mi column and the chroma
11467 // edge-filter strength was read from the wrong neighbour (measured:
11468 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
11469 // with luma bit-exact).
11470 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11471 if filter_intra.is_some() {
11472 hit!(FILTER_INTRA_RECT_HITS);
11473 if bw > bh {
11474 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
11475 } else {
11476 hit!(FILTER_INTRA_RECT4_VERT_HITS);
11477 }
11478 }
11479 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11480 DC_PRED
11481 } else {
11482 uv_mode
11483 };
11484 let depth = if tx_select {
11485 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11486 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11487 // the 16x4 intra-in-inter strips already do); the key frame's
11488 // deblock-grid approximation is only right where those bands were never
11489 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11490 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11491 // `tx_size_cat2` row 1 where libaom reads row 2.
11492 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11493 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11494 } else {
11495 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11496 };
11497 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11498 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11499 eprintln!(
11500 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11501 dec.debug_state().0
11502 );
11503 }
11504 d
11505 } else {
11506 0
11507 };
11508 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11509 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11510 publish_txfm_bands_if_in_inter(
11511 neighbours,
11512 (mi_r, mi_c),
11513 depth_to_tx_wh(bw, bh, depth, fctx),
11514 (bw, bh), fctx,
11515 );
11516 if depth != 0 || lossless(fctx) {
11517 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
11518 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
11519 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
11520 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
11521 // both interleave in every real stream.
11522 hit!(TX_DEPTH_HITS);
11523 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11524 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
11525 // predicted -- depth 1 fires FIRST in every attempt that splits at
11526 // all, so a depth-2-only lift could never be gated. The r1 mismatch
11527 // was never the rect unit: it was the neighbour MODE the strip reads
11528 // (see `modes_above_left_mi`).
11529 let which = if depth == 1 {
11530 &RECT4_SPLIT_DEPTH1_HITS
11531 } else {
11532 &RECT4_SPLIT_DEPTH2_HITS
11533 };
11534 hit_do! { which.with(|c| c.set(c.get() + 1)); }
11535 let modes = RectStripModes {
11536 skip,
11537 mode,
11538 angle_delta_y,
11539 uv_predict_mode,
11540 angle_delta_uv,
11541 alpha,
11542 filter_intra,
11543 smooth_neighbor,
11544 smooth_neighbor_uv,
11545 palette_y: palette_y_buf.clone(),
11546 palette_uv: palette_uv_bufs.clone(),
11547 };
11548 if palette_y.is_some() || palette_uv.is_some() {
11549 hit!(PALETTE_SPLIT_TX_HITS);
11550 }
11551 decode_rect_split(
11552 dec,
11553 cdfs,
11554 neighbours,
11555 (mi_r, mi_c),
11556 bw,
11557 bh,
11558 tx_w,
11559 tx_h,
11560 &modes,
11561 y,
11562 u,
11563 v,
11564 base_q_idx,
11565 false, fctx,
11566 )?;
11567 record_strip_palette(
11568 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11569 pal_uv_colors,
11570 );
11571 if bw > bh {
11572 hit!(RECT4_32_HORZ_HITS);
11573 } else {
11574 hit!(RECT4_32_VERT_HITS);
11575 }
11576 if !skip {
11577 hit!(RECT4_COEFF_HITS);
11578 }
11579 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11580 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11581 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11582 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11583 // transform size in both TXFM_CONTEXT bands. Without it the next block
11584 // reads the row's stale value.
11585 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11586 return Ok((mode, uv_predict_mode));
11587 }
11588 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
11589 // that is 8 px tall, so each strip stamps every cell it touches and the
11590 // LAST strip wins -- which is the right answer for the block below/right
11591 // of the 32x32, the only reader outside it. Written after this strip's
11592 // own context read above, never before.
11593 for cell in 0..bw.div_ceil(SUB) {
11594 neighbours.above_mode[c + cell] = mode;
11595 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
11596 neighbours.above_side[c + cell] = bw;
11597 }
11598 for cell in 0..bh.div_ceil(SUB) {
11599 neighbours.left_mode[r + cell] = mode;
11600 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
11601 neighbours.left_side[r + cell] = bh;
11602 }
11603 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
11604 // [`decode_leaf_rect`] does (the split arm above records these through
11605 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
11606 // `sub8_mode_row` holding the previous block, and the next 32x32's
11607 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
11608 // fixture).
11609 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
11610 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
11611 let (px, py) = (mi_c * MI, mi_r * MI);
11612 let (cpx, cpy) = (px / 2, py / 2);
11613 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11614 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11615 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
11616 (&SCAN_32X8, &SCAN_16X4)
11617 } else {
11618 (&SCAN_8X32, &SCAN_4X16)
11619 };
11620 let (luma_levels, u_levels, v_levels) = if skip {
11621 (
11622 vec![0i32; bw * bh],
11623 vec![0i32; chroma_w * chroma_h],
11624 vec![0i32; chroma_w * chroma_h],
11625 )
11626 } else {
11627 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11628 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
11629 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11630 dec,
11631 &mut luma_coding,
11632 luma_scan,
11633 bw,
11634 bh,
11635 0,
11636 dc_sign_ctx(around[0].2),
11637 TxType::DctDct,
11638 )?;
11639 let mut planes = Vec::with_capacity(2);
11640 for plane in 1..3 {
11641 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11642 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11643 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11644 let (levels, tx_type) = read_coeffs_rect(
11645 dec,
11646 &mut coding,
11647 chroma_scan,
11648 chroma_w,
11649 chroma_h,
11650 skip_ctx,
11651 dc_sign_ctx(around[plane].2),
11652 default_tx,
11653 )?;
11654 planes.push((levels, tx_type));
11655 }
11656 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11657 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11658 hit!(RECT4_COEFF_HITS);
11659 let luma_residual = dequant_and_inverse_typed_wh(
11660 &luma_levels,
11661 bw,
11662 bh,
11663 crate::decode::bit_depth(fctx),
11664 block_q_idx(fctx),
11665 plane_q_delta(0, fctx).0,
11666 plane_q_delta(0, fctx).1,
11667 luma_tx_type,
11668 );
11669 if let Some(b) = &palette_y_buf {
11670 set_palette_pred(b.clone(), fctx);
11671 }
11672 push_intra_rect(0,
11673 px,
11674 py,
11675 bw,
11676 bh,
11677 mode,
11678 angle_delta_y,
11679 reach,
11680 &luma_residual,
11681 None,
11682 filter_intra,
11683 smooth_neighbor, fctx,
11684 );
11685 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11686 for (plane, _buf, levels, tx_type) in [
11687 (1usize, &mut *u, &u_levels, u_tx_type),
11688 (2, &mut *v, &v_levels, v_tx_type),
11689 ] {
11690 let residual = dequant_and_inverse_typed_wh(
11691 levels,
11692 chroma_w,
11693 chroma_h,
11694 crate::decode::bit_depth(fctx),
11695 block_q_idx(fctx),
11696 plane_q_delta(plane, fctx).0,
11697 plane_q_delta(plane, fctx).1,
11698 tx_type,
11699 );
11700 if let Some((ub, vb)) = &palette_uv_bufs {
11701 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11702 }
11703 push_intra_rect(plane,
11704 cpx,
11705 cpy,
11706 chroma_w,
11707 chroma_h,
11708 uv_predict_mode,
11709 angle_delta_uv,
11710 reach,
11711 &residual,
11712 alpha
11713 .zip(ac)
11714 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11715 None,
11716 smooth_neighbor_uv, fctx,
11717 );
11718 }
11719 neighbours.record_mi_rect(
11720 (mi_r, mi_c),
11721 bw,
11722 bh,
11723 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
11724 );
11725 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11726 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11727 record_strip_palette(
11728 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11729 pal_uv_colors,
11730 );
11731 if bw > bh {
11732 hit!(RECT4_32_HORZ_HITS);
11733 } else {
11734 hit!(RECT4_32_VERT_HITS);
11735 }
11736 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11737 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11738 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11739 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11740 // transform size in both TXFM_CONTEXT bands. Without it the next block
11741 // reads the row's stale value.
11742 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11743 return Ok((mode, uv_predict_mode));
11744 };
11745 if let Some(b) = &palette_y_buf {
11746 set_palette_pred(b.clone(), fctx);
11747 }
11748 push_intra_rect(0,
11749 px,
11750 py,
11751 bw,
11752 bh,
11753 mode,
11754 angle_delta_y,
11755 reach,
11756 &luma_levels,
11757 None,
11758 filter_intra,
11759 smooth_neighbor, fctx,
11760 );
11761 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11762 if let Some((ub, _)) = &palette_uv_bufs {
11763 set_palette_pred(ub.clone(), fctx);
11764 }
11765 push_intra_rect(1,
11766 cpx,
11767 cpy,
11768 chroma_w,
11769 chroma_h,
11770 uv_predict_mode,
11771 angle_delta_uv,
11772 reach,
11773 &u_levels,
11774 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11775 None,
11776 smooth_neighbor_uv, fctx,
11777 );
11778 if let Some((_, vb)) = &palette_uv_bufs {
11779 set_palette_pred(vb.clone(), fctx);
11780 }
11781 push_intra_rect(2,
11782 cpx,
11783 cpy,
11784 chroma_w,
11785 chroma_h,
11786 uv_predict_mode,
11787 angle_delta_uv,
11788 reach,
11789 &v_levels,
11790 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11791 None,
11792 smooth_neighbor_uv, fctx,
11793 );
11794 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11795 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11796 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11797 record_strip_palette(
11798 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11799 );
11800 if bw > bh {
11801 hit!(RECT4_32_HORZ_HITS);
11802 } else {
11803 hit!(RECT4_32_VERT_HITS);
11804 }
11805 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11806 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11807 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11808 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11809 // transform size in both TXFM_CONTEXT bands. Without it the next block
11810 // reads the row's stale value.
11811 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11812 Ok((mode, uv_predict_mode))
11813}
11814
11815/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
11816/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
11817/// down, and the first shape here whose luma block is a single mi row (or
11818/// column).
11819///
11820/// What is new at this size is CHROMA. `is_chroma_reference`
11821/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
11822/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
11823/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
11824/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
11825/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
11826/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
11827/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
11828///
11829/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
11830/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
11831/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
11832/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
11833/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
11834/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
11835/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
11836/// shape's own CDF row.
11837///
11838/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
11839/// refuses by name rather than guess-decode.
11840#[allow(clippy::too_many_arguments)]
11841fn decode_rect4_16(
11842 dec: &mut SymbolDecoder,
11843 cdfs: &mut Cdfs,
11844 neighbours: &mut Neighbours,
11845 at16: (usize, usize),
11846 horz: bool,
11847 y: &mut PlaneBuf<'static>,
11848 u: &mut PlaneBuf<'static>,
11849 v: &mut PlaneBuf<'static>,
11850 enable_filter_intra: bool,
11851 allow_screen_content_tools: bool,
11852 base_q_idx: u8,
11853 tx_select: bool,
11854 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11855) -> Result<()> {
11856 let (r, c) = at16;
11857 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
11858 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
11859 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
11860 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11861 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11862 let mut prev: Option<((usize, usize), usize)> = None;
11863 let mut last_mode = DC_PRED;
11864 let mut last_uv_mode = DC_PRED;
11865 for i in 0..4usize {
11866 let lmi = if horz {
11867 (mi_row0 + i, mi_col0)
11868 } else {
11869 (mi_row0, mi_col0 + i)
11870 };
11871 let has_chroma = i % 2 == 1;
11872 let (mode, uv, _tx) = decode_rect4_16_strip(
11873 dec,
11874 cdfs,
11875 neighbours,
11876 lmi,
11877 horz,
11878 has_chroma,
11879 prev,
11880 y,
11881 u,
11882 v,
11883 enable_filter_intra,
11884 allow_screen_content_tools,
11885 base_q_idx,
11886 tx_select,
11887 reduced_tx_set, fctx,
11888 )?;
11889 if let Some(m) = uv {
11890 last_uv_mode = m;
11891 }
11892 last_mode = mode;
11893 prev = Some((lmi, mode));
11894 }
11895 // The coarse 16-px cell holds one entry for the whole 16x16: the last
11896 // strip is what a block below (right) sees through it, the mi-exact maps
11897 // above answering everything finer.
11898 neighbours.above_mode[c] = last_mode;
11899 neighbours.left_mode[r] = last_mode;
11900 neighbours.above_uv_mode[c] = last_uv_mode;
11901 neighbours.left_uv_mode[r] = last_uv_mode;
11902 neighbours.above_side[c] = bw;
11903 neighbours.left_side[r] = bh;
11904 Ok(())
11905}
11906
11907/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
11908/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
11909/// block path can decode a SINGLE intra strip of a partition whose other
11910/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
11911/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
11912/// every strip publishes its own mi-exact mode). Returns
11913/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
11914#[allow(clippy::too_many_arguments)]
11915fn decode_rect4_16_strip(
11916 dec: &mut SymbolDecoder,
11917 cdfs: &mut Cdfs,
11918 neighbours: &mut Neighbours,
11919 lmi: (usize, usize),
11920 horz: bool,
11921 has_chroma: bool,
11922 prev: Option<((usize, usize), usize)>,
11923 y: &mut PlaneBuf<'static>,
11924 u: &mut PlaneBuf<'static>,
11925 v: &mut PlaneBuf<'static>,
11926 enable_filter_intra: bool,
11927 allow_screen_content_tools: bool,
11928 base_q_idx: u8,
11929 tx_select: bool,
11930 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11931) -> Result<(usize, Option<usize>, (usize, usize))> {
11932 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
11933 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
11934 let (mi_w, mi_h) = (bw / MI, bh / MI);
11935 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11936 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11937 let mut last_uv_mode: Option<usize> = None;
11938 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
11939 // aliases all four strips onto one entry, so the mi-exact map wins and
11940 // the previous strip stands in on the split axis.
11941 let mut above_mode = neighbours.above_mode[c];
11942 let mut left_mode = neighbours.left_mode[r];
11943 if let Some(((pr, pc), pmode)) = prev {
11944 if pc == lmi.1 && lmi.0 == pr + mi_h {
11945 above_mode = pmode;
11946 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
11947 left_mode = pmode;
11948 }
11949 }
11950 let (above_mode, left_mode) =
11951 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
11952 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
11953 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
11954 // off CDF row 0 and every cache hit off an empty cache.
11955 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
11956 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
11957 let (
11958 skip,
11959 mode,
11960 angle_delta_y,
11961 uv_mode,
11962 angle_delta_uv,
11963 alpha,
11964 filter_intra,
11965 palette_y,
11966 palette_uv,
11967 ) = read_intra_mode_rect(
11968 dec,
11969 cdfs,
11970 above_mode,
11971 left_mode,
11972 true,
11973 has_chroma,
11974 bw,
11975 bh,
11976 enable_filter_intra,
11977 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
11978 allow_screen_content_tools,
11979 Some((palette_ctx, &palette_cache)),
11980 &palette_uv_cache,
11981 lmi.0,
11982 lmi.1, fctx,
11983 )?;
11984 if palette_y.is_some() || palette_uv.is_some() {
11985 hit!(RECT4_PALETTE_HITS);
11986 }
11987 // The colour-index map through the base colours IS the prediction.
11988 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
11989 // chroma transform this closing strip codes.
11990 let palette_y_buf: Option<Vec<u16>> = palette_y
11991 .as_ref()
11992 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11993 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11994 (
11995 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11996 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11997 )
11998 });
11999 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12000 if smooth_neighbor {
12001 hit!(SMOOTH_LUMA_HITS);
12002 }
12003 if filter_intra.is_some() {
12004 hit!(FILTER_INTRA_RECT_HITS);
12005 }
12006 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
12007 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
12008 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
12009 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
12010 let depth = if tx_select {
12011 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
12012 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
12013 // the 2:1 intra-in-inter strip already does); the key frame's
12014 // deblock-grid approximation is only right where those bands were
12015 // never written.
12016 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12017 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
12018 } else {
12019 tx_size_context_rect(neighbours, lmi, bw, bh)
12020 };
12021 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
12022 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12023 eprintln!(
12024 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
12025 lmi.0,
12026 lmi.1,
12027 dec.debug_state().0
12028 );
12029 }
12030 d
12031 } else {
12032 0
12033 };
12034 if depth != 0 {
12035 hit!(TX_DEPTH_HITS);
12036 hit!(RECT4_16_SPLIT_HITS);
12037 }
12038 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12039 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
12040 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12041 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
12042 if depth != 0 || lossless(fctx) {
12043 // [`decode_rect_split`]'s per-unit walk, inlined because the
12044 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
12045 // the strip (that function codes one chroma transform per block).
12046 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
12047 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
12048 // unit predicts off the units before it in raster order.
12049 let rect_unit = tx_w != tx_h;
12050 let zero_tu = vec![0i32; tx_w * tx_h];
12051 for tu_row in 0..bh / tx_h {
12052 for tu_col in 0..bw / tx_w {
12053 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
12054 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12055 let tu_reach = Reach::of_tu(
12056 bw,
12057 bh,
12058 tu_col * tx_w,
12059 tu_row * tx_h,
12060 tx_w,
12061 tx_h,
12062 reach,
12063 );
12064 if let Some(b) = &palette_y_buf {
12065 let tu_buf: Vec<u16> = (0..tx_h)
12066 .flat_map(|i| {
12067 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
12068 b[base..base + tx_w].iter().copied()
12069 })
12070 .collect();
12071 set_palette_pred(tu_buf, fctx);
12072 }
12073 if skip {
12074 push_intra_rect(0,
12075 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
12076 None, filter_intra, smooth_neighbor, fctx,
12077 );
12078 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12079 } else if rect_unit {
12080 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
12081 // 32 coded positions and the `TX_4X4` `tx_type` row:
12082 // exactly [`TxbSet::LumaRect4x8`].
12083 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12084 let tu_skip_ctx =
12085 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
12086 let set = if reduced_tx_set {
12087 TxbSet::LumaRect4x8
12088 } else {
12089 TxbSet::LumaRect4x8Set1
12090 };
12091 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
12092 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
12093 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12094 dec,
12095 &mut coding,
12096 tu_scan,
12097 tx_w,
12098 tx_h,
12099 tu_skip_ctx,
12100 dc_sign_ctx(tu_around.2),
12101 TxType::DctDct,
12102 )?;
12103 let residual = dequant_and_inverse_typed_wh(
12104 &tu_grid,
12105 tx_w,
12106 tx_h,
12107 crate::decode::bit_depth(fctx),
12108 block_q_idx(fctx),
12109 plane_q_delta(0, fctx).0,
12110 plane_q_delta(0, fctx).1,
12111 tu_tx_type,
12112 );
12113 push_intra_rect(0,
12114 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
12115 None, filter_intra, smooth_neighbor, fctx,
12116 );
12117 if tu_grid.iter().any(|&l| l != 0) {
12118 hit!(RECT4_16_COEFF_HITS);
12119 }
12120 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12121 } else {
12122 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12123 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12124 let tu_grid = read_plane(
12125 dec,
12126 cdfs,
12127 txbset_for(tx_w, reduced_tx_set),
12128 default_scan(tx_w),
12129 0,
12130 tu_around,
12131 mode,
12132 mode,
12133 angle_delta_y,
12134 tu_reach,
12135 y,
12136 tu_px,
12137 tu_py,
12138 tx_w,
12139 tx_w,
12140 base_q_idx,
12141 None,
12142 filter_intra,
12143 Some(tu_skip_ctx),
12144 smooth_neighbor, fctx,
12145 )?;
12146 if tu_grid.iter().any(|&l| l != 0) {
12147 hit!(RECT4_16_COEFF_HITS);
12148 }
12149 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12150 }
12151 }
12152 }
12153 } else {
12154 let levels = if skip {
12155 let zeros = Grid::Zero(bw * bh);
12156 if let Some(b) = &palette_y_buf {
12157 set_palette_pred(b.clone(), fctx);
12158 }
12159 push_intra_rect(0,
12160 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
12161 smooth_neighbor, fctx,
12162 );
12163 zeros
12164 } else {
12165 // The strip's luma TU *is* the strip (`plane_bsize ==
12166 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
12167 // `txb_skip_ctx` at 0.
12168 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
12169 let set = if reduced_tx_set {
12170 TxbSet::LumaRect16x4
12171 } else {
12172 TxbSet::LumaRect16x4Set1
12173 };
12174 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
12175 let (levels, tx_type) = read_coeffs_rect(
12176 dec,
12177 &mut coding,
12178 scan,
12179 bw,
12180 bh,
12181 0,
12182 dc_sign_ctx(around.2),
12183 TxType::DctDct,
12184 )?;
12185 let residual = dequant_and_inverse_typed_wh(
12186 &levels,
12187 bw,
12188 bh,
12189 crate::decode::bit_depth(fctx),
12190 block_q_idx(fctx),
12191 plane_q_delta(0, fctx).0,
12192 plane_q_delta(0, fctx).1,
12193 tx_type,
12194 );
12195 if let Some(b) = &palette_y_buf {
12196 set_palette_pred(b.clone(), fctx);
12197 }
12198 push_intra_rect(0,
12199 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
12200 smooth_neighbor, fctx,
12201 );
12202 hit!(RECT4_16_COEFF_HITS);
12203 levels
12204 };
12205 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
12206 }
12207 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
12208 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
12209 // `update_partition_context` writes `partition_context_lookup[
12210 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
12211 // the left (mirrored under VERT_4).
12212 for cell in 0..mi_w {
12213 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
12214 *slot = bw as u8;
12215 }
12216 }
12217 for cell in 0..mi_h {
12218 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
12219 *slot = bh as u8;
12220 }
12221 }
12222 if has_chroma {
12223 hit!(RECT4_16_CHROMA_HITS);
12224 let pair_mi = if horz {
12225 (lmi.0 - 1, lmi.1)
12226 } else {
12227 (lmi.0, lmi.1 - 1)
12228 };
12229 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
12230 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
12231 let (cpx, cpy) = (ppx / 2, ppy / 2);
12232 let (cw, ch) = (pw / 2, ph / 2);
12233 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12234 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
12235 hit!(RECT4_16_CHROMA_DIR_HITS);
12236 }
12237 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
12238 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
12239 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
12240 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
12241 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
12242 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
12243 // the pair's top-left luma mi, never this leaf's odd row/column.
12244 // Reading `lmi` here named the leaf directly above (a non-chroma
12245 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
12246 // SMOOTH neighbour: filt_type 0 instead of 1 turned
12247 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
12248 // directional chroma strip, moving 4 samples by 1.
12249 let smooth_neighbor_uv =
12250 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
12251 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
12252 {
12253 hit!(RECT4_16_UV_PAIR_FILT_HITS);
12254 }
12255 let (u_levels, v_levels) = if skip {
12256 let zeros = Grid::Zero(cw * ch);
12257 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
12258 // ~1000) predicts EVERY plane and only guards the residual on
12259 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
12260 // DC + alpha * luma-AC. Dropping the CfL term here left a
12261 // chroma-only bounded box on ReelC's key frames.
12262 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12263 if alpha.is_some() {
12264 hit!(CHROMA_SKIP_CFL_HITS);
12265 }
12266 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
12267 if let Some((ub, vb)) = &palette_uv_bufs {
12268 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12269 }
12270 push_intra_rect(plane,
12271 cpx,
12272 cpy,
12273 cw,
12274 ch,
12275 uv_predict_mode,
12276 angle_delta_uv,
12277 pair_reach,
12278 &zeros,
12279 alpha
12280 .zip(ac)
12281 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12282 None,
12283 smooth_neighbor_uv, fctx,
12284 );
12285 }
12286 (zeros.clone(), zeros)
12287 } else {
12288 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
12289 let mut planes = Vec::with_capacity(2);
12290 for plane in 1..3 {
12291 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12292 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12293 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12294 let (levels, tx_type) = read_coeffs_rect(
12295 dec,
12296 &mut coding,
12297 chroma_scan,
12298 cw,
12299 ch,
12300 skip_ctx,
12301 dc_sign_ctx(around[plane].2),
12302 default_tx,
12303 )?;
12304 planes.push((levels, tx_type));
12305 }
12306 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12307 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12308 // CfL averages the luma of the WHOLE pair, the region this one
12309 // chroma transform covers.
12310 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12311 for (plane, _buf, levels, tx_type) in [
12312 (1usize, &mut *u, &u_levels, u_tx_type),
12313 (2, &mut *v, &v_levels, v_tx_type),
12314 ] {
12315 let residual = dequant_and_inverse_typed_wh(
12316 levels,
12317 cw,
12318 ch,
12319 crate::decode::bit_depth(fctx),
12320 block_q_idx(fctx),
12321 plane_q_delta(plane, fctx).0,
12322 plane_q_delta(plane, fctx).1,
12323 tx_type,
12324 );
12325 if let Some((ub, vb)) = &palette_uv_bufs {
12326 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12327 }
12328 push_intra_rect(plane,
12329 cpx,
12330 cpy,
12331 cw,
12332 ch,
12333 uv_predict_mode,
12334 angle_delta_uv,
12335 pair_reach,
12336 &residual,
12337 alpha
12338 .zip(ac)
12339 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12340 None,
12341 smooth_neighbor_uv, fctx,
12342 );
12343 }
12344 (u_levels, v_levels)
12345 };
12346 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
12347 // The chroma planes' coefficient context, over the PAIR's mi span
12348 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
12349 // the luma one rounded up to its 4x4 unit).
12350 let u_state = neighbour_state(&u_levels);
12351 let v_state = neighbour_state(&v_levels);
12352 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12353 let bound_h = round_up_even(neighbours.mi_rows);
12354 let bound_w = round_up_even(neighbours.mi_cols);
12355 for cell in 0..(ph / MI) {
12356 if pair_mi.0 + cell < bound_h
12357 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
12358 {
12359 slot[1] = u_state;
12360 slot[2] = v_state;
12361 }
12362 }
12363 for cell in 0..(pw / MI) {
12364 if pair_mi.1 + cell < bound_w
12365 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
12366 {
12367 slot[1] = u_state;
12368 slot[2] = v_state;
12369 }
12370 }
12371 last_uv_mode = Some(uv_predict_mode);
12372 }
12373 if horz {
12374 hit!(RECT4_16_HORZ_HITS);
12375 } else {
12376 hit!(RECT4_16_VERT_HITS);
12377 }
12378 let (pal_y_size, pal_y_colors) =
12379 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12380 let (pal_uv_size, pal_uv_colors) =
12381 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12382 record_strip_palette(
12383 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12384 );
12385 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12386 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12387 // frame): the above row records `tx_size_wide` over the block's width and
12388 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12389 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12390 // and it published neither band -- so the block after a 64x16 strip read
12391 // the row's init value 64 as its left transform height and took
12392 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12393 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12394 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12395 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
12396 Ok((mode, last_uv_mode, (tx_w, tx_h)))
12397}
12398
12399
12400/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
12401/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
12402/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
12403/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
12404/// cap, so LUMA needs the same corner truncation [`decode_block`] already
12405/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
12406/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
12407/// this function's own charter/report), so both strips read a real 32x32
12408/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
12409/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
12410/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
12411/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
12412/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
12413/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
12414/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
12415/// that function, only the single-transform-unit (`tx_depth == 0`) case is
12416/// supported: a split transform refuses by name rather than guess-decode.
12417#[allow(clippy::too_many_arguments)]
12418fn decode_block_rect64(
12419 dec: &mut SymbolDecoder,
12420 cdfs: &mut Cdfs,
12421 neighbours: &mut Neighbours,
12422 at: (usize, usize),
12423 bw: usize,
12424 bh: usize,
12425 y: &mut PlaneBuf<'static>,
12426 u: &mut PlaneBuf<'static>,
12427 v: &mut PlaneBuf<'static>,
12428 enable_filter_intra: bool,
12429 allow_screen_content_tools: bool,
12430 base_q_idx: u8,
12431 tx_select: bool,
12432 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12433) -> Result<()> {
12434 let (r, c) = at;
12435 let (px, py) = (c * SUB, r * SUB);
12436 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12437 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12438 let palette_uv_cache = neighbours.palette_uv_cache(at);
12439 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12440 read_intra_mode_rect(
12441 dec,
12442 cdfs,
12443 nb_above_mode,
12444 nb_left_mode,
12445 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
12446 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
12447 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
12448 // correct), CFL must never be offered here -- passing `true`
12449 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
12450 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
12451 // from this block's very first symbol (lane-sbpart r3 bisect).
12452 false,
12453 true,
12454 bw,
12455 bh,
12456 enable_filter_intra,
12457 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12458 allow_screen_content_tools,
12459 Some((palette_ctx, &palette_cache)),
12460 &palette_uv_cache,
12461 r * (SUB / MI),
12462 c * (SUB / MI), fctx,
12463 )?;
12464 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
12465 // lane-t900 r34: a non-skip palette block on a superblock-level strip
12466 // -- counted so its gate cannot go vacuous (this was a refusal until
12467 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
12468 // decodes_pixel_exact`).
12469 hit!(PALETTE_SB_STRIP_HITS);
12470 }
12471 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12472 if smooth_neighbor {
12473 hit!(SMOOTH_LUMA_HITS);
12474 }
12475 let smooth_neighbor_uv =
12476 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
12477 if filter_intra.is_some() {
12478 // `filter_intra_size_class_rect` already returns `None` for both
12479 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
12480 // 32 on both axes), so this symbol is never read at this level --
12481 // kept only as the same defensive refusal [`decode_block_rect`] has.
12482 return Err(unsupported(
12483 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
12484 av1_filter_intra_allowed_bsize caps at 32x32)",
12485 ));
12486 }
12487 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12488 DC_PRED
12489 } else {
12490 uv_mode
12491 };
12492 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12493 let depth = if tx_select {
12494 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
12495 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
12496 // the 16x4 intra-in-inter strips already do); the key frame's
12497 // deblock-grid approximation is only right where those bands were never
12498 // written. Measured on the 10-bit 1920x792 128-superblock stream,
12499 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12500 // `tx_size_cat2` row 1 where libaom reads row 2.
12501 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12502 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
12503 } else {
12504 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12505 };
12506 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
12507 // counts `sub_tx_size_map` steps from the block's own max rect
12508 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
12509 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
12510 // steps, so this level's category is 3 (the same one a 64x64 square
12511 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
12512 // here was a wrong-table read of a real symbol.
12513 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
12514 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12515 eprintln!(
12516 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
12517 dec.debug_state().0
12518 );
12519 }
12520 d
12521 } else {
12522 0
12523 };
12524 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12525 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12526 publish_txfm_bands_if_in_inter(
12527 neighbours,
12528 (mi_r, mi_c),
12529 depth_to_tx_wh(bw, bh, depth, fctx),
12530 (bw, bh), fctx,
12531 );
12532 if depth != 0 || lossless(fctx) {
12533 hit!(TX_DEPTH_HITS);
12534 // lane-rectsplit r1/r4: the superblock-level strip splits its
12535 // transform through the very same per-unit path as its 32x32-level
12536 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
12537 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
12538 // measured the old square formula mis-tiling exactly that strip).
12539 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12540 if bw.max(bh) / bw.min(bh) == 4 {
12541 let which = if depth == 1 {
12542 &RECT4_SPLIT_DEPTH1_HITS
12543 } else {
12544 &RECT4_SPLIT_DEPTH2_HITS
12545 };
12546 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12547 }
12548 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12549 eprintln!(
12550 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12551 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12552 angle_y={angle_delta_y}"
12553 );
12554 }
12555 let modes = RectStripModes {
12556 skip,
12557 mode,
12558 angle_delta_y,
12559 uv_predict_mode,
12560 angle_delta_uv,
12561 alpha,
12562 filter_intra,
12563 smooth_neighbor,
12564 smooth_neighbor_uv,
12565 palette_y: palette_y
12566 .as_ref()
12567 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12568 palette_uv: palette_uv.as_ref().map(|p| {
12569 (
12570 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12571 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12572 )
12573 }),
12574 };
12575 if palette_y.is_some() || palette_uv.is_some() {
12576 hit!(PALETTE_SPLIT_TX_HITS);
12577 }
12578 decode_rect_split(
12579 dec,
12580 cdfs,
12581 neighbours,
12582 (mi_r, mi_c),
12583 bw,
12584 bh,
12585 tx_w,
12586 tx_h,
12587 &modes,
12588 y,
12589 u,
12590 v,
12591 base_q_idx,
12592 reduced_tx_set, fctx,
12593 )?;
12594 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
12595 // (lane-palette2 r10): this return skips the fn's own tail, so a
12596 // split-tx superblock strip would otherwise leave the above/left
12597 // palette arrays holding a dead block's colours.
12598 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12599 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12600 let (puv_size, puv_colors) =
12601 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12602 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12603 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
12604 // return skips the fn's own tail, so a SPLIT superblock-level strip
12605 // published no TXFM_CONTEXT band and the next block read the row's init
12606 // value 64 as its left transform height. Measured on the 10-bit
12607 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
12608 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
12609 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
12610 // bands carry the SPLIT unit's size, not the block's.
12611 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12612 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
12613 hit!(RECT_PARTITION_HITS);
12614 return Ok(());
12615 }
12616 let (tx_w, tx_h) = (bw, bh);
12617 let (cpx, cpy) = (px / 2, py / 2);
12618 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12619 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12620 if let Some(ref pyv) = palette_y {
12621 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12622 set_palette_pred(buf, fctx);
12623 }
12624 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12625 (
12626 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12627 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12628 )
12629 });
12630 if skip {
12631 push_intra_rect(0,
12632 px,
12633 py,
12634 bw,
12635 bh,
12636 mode,
12637 angle_delta_y,
12638 reach,
12639 &ZERO_RESIDUAL[..bw * bh],
12640 None,
12641 filter_intra,
12642 smooth_neighbor, fctx,
12643 );
12644 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12645 if let Some((ub, _)) = &palette_uv_bufs {
12646 set_palette_pred(ub.clone(), fctx);
12647 }
12648 push_intra_rect(1,
12649 cpx,
12650 cpy,
12651 chroma_w,
12652 chroma_h,
12653 uv_predict_mode,
12654 angle_delta_uv,
12655 reach,
12656 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12657 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12658 None,
12659 smooth_neighbor_uv, fctx,
12660 );
12661 if let Some((_, vb)) = &palette_uv_bufs {
12662 set_palette_pred(vb.clone(), fctx);
12663 }
12664 push_intra_rect(2,
12665 cpx,
12666 cpy,
12667 chroma_w,
12668 chroma_h,
12669 uv_predict_mode,
12670 angle_delta_uv,
12671 reach,
12672 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12673 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12674 None,
12675 smooth_neighbor_uv, fctx,
12676 );
12677 neighbours.record_rect(
12678 at,
12679 bw,
12680 bh,
12681 mode,
12682 uv_predict_mode,
12683 &[
12684 &ZERO_RESIDUAL[..bw * bh],
12685 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12686 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12687 ],
12688 );
12689 } else {
12690 let around = neighbours.around_rect(at, bw, bh);
12691 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
12692 // (see this function's own doc comment). A 64-length axis codes only
12693 // its low 32 coefficients, so the corner is `min(bw, 32)` x
12694 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
12695 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
12696 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
12697 let scan32 = default_scan(TX32);
12698 if coeff_trace_on() {
12699 let (rng, _) = dec.debug_state();
12700 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
12701 }
12702 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
12703 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
12704 read_coeffs(
12705 dec,
12706 &mut luma_coding,
12707 &scan32,
12708 0,
12709 dc_sign_ctx(around[0].2),
12710 TxType::DctDct,
12711 Some((bw, bh)),
12712 )?
12713 } else {
12714 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
12715 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
12716 // (`scan.c`) gives both the very same `default_scan_32x16` /
12717 // `default_scan_16x32` the 2:1 sizes use ("Half of the
12718 // coefficients of tx64 at higher frequencies are set to zeros. So
12719 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
12720 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
12721 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
12722 // 512-position eob group) -- BOTH identical to TX_32X16, so the
12723 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
12724 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
12725 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
12726 // what `base_ctx_rect` computes at (32, 16).
12727 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
12728 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
12729 read_coeffs_rect(
12730 dec,
12731 &mut luma_coding,
12732 luma_scan,
12733 luma_cw,
12734 luma_ch,
12735 0,
12736 dc_sign_ctx(around[0].2),
12737 TxType::DctDct,
12738 )?
12739 };
12740 if coeff_trace_on() {
12741 let (rng, _) = dec.debug_state();
12742 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
12743 }
12744 let mut luma_levels = vec![0i32; bw * bh];
12745 for row in 0..luma_ch {
12746 luma_levels[row * bw..][..luma_cw]
12747 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
12748 }
12749 {
12750 let cur = block_q_idx(fctx);
12751 if cur != i32::from(base_q_idx) {
12752 hit!(RECT64_QIDX_DRIFT_HITS);
12753 }
12754 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12755 eprintln!(
12756 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
12757 );
12758 }
12759 }
12760 let luma_residual = dequant_and_inverse_typed_wh(
12761 &luma_levels,
12762 bw,
12763 bh,
12764 crate::decode::bit_depth(fctx),
12765 block_q_idx(fctx),
12766 plane_q_delta(0, fctx).0,
12767 plane_q_delta(0, fctx).1,
12768 luma_tx_type,
12769 );
12770 push_intra_rect(0,
12771 px,
12772 py,
12773 bw,
12774 bh,
12775 mode,
12776 angle_delta_y,
12777 reach,
12778 &luma_residual,
12779 None,
12780 filter_intra,
12781 smooth_neighbor, fctx,
12782 );
12783 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12784 let leftcol: Vec<u16> = if px > 0 {
12785 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
12786 } else {
12787 vec![]
12788 };
12789 eprintln!(
12790 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
12791 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
12792 luma_corner.iter().any(|&v| v != 0),
12793 &y.data[py * y.width + px..][..bw],
12794 leftcol,
12795 );
12796 }
12797 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
12798 // corner crop needed (see doc comment).
12799 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12800 // The chroma plane is never truncated (both axes <= 32 after
12801 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
12802 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
12803 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
12804 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
12805 // set, and only the scan is new (lane-tx64x16).
12806 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
12807 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
12808 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
12809 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12810 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12811 };
12812 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12813 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12814 if coeff_trace_on() {
12815 let (rng, _) = dec.debug_state();
12816 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12817 }
12818 let (u_levels, u_tx_type) = read_coeffs_rect(
12819 dec,
12820 &mut u_coding,
12821 chroma_scan,
12822 chroma_w,
12823 chroma_h,
12824 u_skip_ctx,
12825 dc_sign_ctx(around[1].2),
12826 TxType::DctDct,
12827 )?;
12828 if coeff_trace_on() {
12829 let (rng, _) = dec.debug_state();
12830 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
12831 }
12832 {
12833 let cur = block_q_idx(fctx);
12834 if cur != i32::from(base_q_idx) {
12835 hit!(RECT64_QIDX_DRIFT_HITS);
12836 }
12837 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12838 eprintln!(
12839 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
12840 );
12841 }
12842 }
12843 let u_residual = dequant_and_inverse_typed_wh(
12844 &u_levels,
12845 chroma_w,
12846 chroma_h,
12847 crate::decode::bit_depth(fctx),
12848 block_q_idx(fctx),
12849 plane_q_delta(1, fctx).0,
12850 plane_q_delta(1, fctx).1,
12851 u_tx_type,
12852 );
12853 // lane-t900 r34: the UV-palette prediction override, exactly as the
12854 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
12855 // set-then-take, so it must be filled again right before each plane's
12856 // own reconstruct; leaving this out of the non-skip arm predicted a
12857 // palette block's chroma off its block edges (measured: testsrc2
12858 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
12859 // luma exact, both chroma planes wrong over its whole 16x32).
12860 if let Some((ub, _)) = &palette_uv_bufs {
12861 set_palette_pred(ub.clone(), fctx);
12862 }
12863 push_intra_rect(1,
12864 cpx,
12865 cpy,
12866 chroma_w,
12867 chroma_h,
12868 uv_predict_mode,
12869 angle_delta_uv,
12870 reach,
12871 &u_residual,
12872 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12873 None,
12874 smooth_neighbor_uv, fctx,
12875 );
12876 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12877 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12878 if coeff_trace_on() {
12879 let (rng, _) = dec.debug_state();
12880 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12881 }
12882 let (v_levels, v_tx_type) = read_coeffs_rect(
12883 dec,
12884 &mut v_coding,
12885 chroma_scan,
12886 chroma_w,
12887 chroma_h,
12888 v_skip_ctx,
12889 dc_sign_ctx(around[2].2),
12890 TxType::DctDct,
12891 )?;
12892 if coeff_trace_on() {
12893 let (rng, _) = dec.debug_state();
12894 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
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=2 base_q_idx={base_q_idx} current_q_idx={cur}"
12904 );
12905 }
12906 }
12907 let v_residual = dequant_and_inverse_typed_wh(
12908 &v_levels,
12909 chroma_w,
12910 chroma_h,
12911 crate::decode::bit_depth(fctx),
12912 block_q_idx(fctx),
12913 plane_q_delta(2, fctx).0,
12914 plane_q_delta(2, fctx).1,
12915 v_tx_type,
12916 );
12917 if let Some((_, vb)) = &palette_uv_bufs {
12918 set_palette_pred(vb.clone(), fctx);
12919 }
12920 push_intra_rect(2,
12921 cpx,
12922 cpy,
12923 chroma_w,
12924 chroma_h,
12925 uv_predict_mode,
12926 angle_delta_uv,
12927 reach,
12928 &v_residual,
12929 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12930 None,
12931 smooth_neighbor_uv, fctx,
12932 );
12933 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12934 hit!(RECT_COEFF_HITS);
12935 }
12936 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12937 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12938 let (puv_size, puv_colors) =
12939 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12940 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12941 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12942 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12943 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12944 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12945 // frame): the above row records `tx_size_wide` over the block's width and
12946 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12947 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12948 // and it published neither band -- so the block after a 64x16 strip read
12949 // the row's init value 64 as its left transform height and took
12950 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12951 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12952 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12953 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12954 hit!(SB_RECT_HITS);
12955 match (bw, bh) {
12956 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
12957 (16, 64) => hit!(SB_RECT4_VERT_HITS),
12958 _ => {}
12959 }
12960 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12961 let (rng, _) = dec.debug_state();
12962 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
12963 }
12964 Ok(())
12965}
12966
12967/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
12968/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
12969/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
12970/// it lands away from zero, for gate tests to prove a real stream fired one.
12971fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
12972 let symbol = dec.symbol(cdf);
12973 if symbol != ANGLE_DELTA_ZERO {
12974 hit!(ANGLE_DELTA_HITS);
12975 }
12976 symbol as i32 - ANGLE_DELTA_ZERO as i32
12977}
12978
12979#[allow(clippy::too_many_arguments)]
12980fn read_intra_mode(
12981 dec: &mut SymbolDecoder,
12982 cdfs: &mut Cdfs,
12983 above_mode: usize,
12984 left_mode: usize,
12985 cfl: bool,
12986 side: usize,
12987 enable_filter_intra: bool,
12988 skip_ctx: usize,
12989 allow_screen_content_tools: bool,
12990 allow_intrabc: bool,
12991 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
12992 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
12993 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
12994 // `None` at the excluded call sites (the 8x8-leaf path), which still read
12995 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
12996 // decoder reads either way -- but refuse by name the moment it fires,
12997 // exactly the old behaviour.
12998 palette: Option<(usize, &[u16])>,
12999 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
13000 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
13001 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
13002 // `use_palette_y`, not a neighbour lookup).
13003 palette_uv_cache: &[u16],
13004 mi_r: usize,
13005 mi_c: usize, fctx: &crate::decode::FrameCtx,
13006) -> Result<(
13007 bool,
13008 usize,
13009 i32,
13010 usize,
13011 i32,
13012 Option<(i32, i32)>,
13013 Option<usize>,
13014 Option<PaletteY>,
13015 Option<PaletteUv>,
13016)> {
13017 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
13018 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
13019 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
13020 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
13021 // line against the instrumented aomdec, not just `tell()`.
13022 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13023 if ec_istep {
13024 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
13025 // (decodemv.c:818), printed at the same point: before the first
13026 // mode-info symbol of the block, so a cross-decoder range ladder can
13027 // be keyed on the BLOCK, not just on the symbol sequence.
13028 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
13029 }
13030 macro_rules! istep {
13031 ($name:literal, $val:expr) => {
13032 if ec_istep {
13033 let (rng, _) = dec.debug_state();
13034 eprintln!(
13035 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
13036 $name, $val
13037 );
13038 }
13039 };
13040 }
13041 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
13042 // point every square caller routes through (see `read_intra_mode_rect`).
13043 let cfl = if cfl && side > 32 {
13044 hit!(NOCFL_UV_MODE_HITS);
13045 false
13046 } else {
13047 cfl
13048 };
13049 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
13050 // `skip` when `SegIdPreSkip`, and after it otherwise.
13051 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
13052 if seg_id_pre_skip(fctx) {
13053 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
13054 }
13055 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
13056 if trace {
13057 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
13058 }
13059 istep!("skip", skip as i32);
13060 if !seg_id_pre_skip(fctx) {
13061 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
13062 }
13063 // spec order (see the comment below on `read_intrabc_info`): `skip`,
13064 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
13065 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
13066 istep!("cdef", 0);
13067 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
13068 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
13069 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
13070 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
13071 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
13072 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
13073 istep!("dq", 0);
13074 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
13075 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
13076 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
13077 // intra frame whose header set `allow_intrabc`. Actual intra block copy
13078 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
13079 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
13080 // draws the line at consuming this one flag symbol and refusing by name
13081 // when it fires, so the arithmetic decoder still resyncs for a stream
13082 // that merely allows (but never uses) intrabc.
13083 if allow_intrabc {
13084 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
13085 if trace {
13086 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
13087 }
13088 if use_intrabc {
13089 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
13090 if trace {
13091 eprintln!("TRACE intrabc dv={dv:?}");
13092 }
13093 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
13094 hit!(INTRABC_HITS);
13095 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
13096 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
13097 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
13098 // `DC_PRED` (which is also what the neighbour mode contexts and
13099 // the loop filter then see).
13100 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
13101 }
13102 }
13103 let above_ctx = INTRA_MODE_CTX[above_mode];
13104 let left_ctx = INTRA_MODE_CTX[left_mode];
13105 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
13106 if trace {
13107 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
13108 }
13109 istep!("mode", mode as i32);
13110 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13111 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
13112 if trace {
13113 eprintln!(
13114 "TRACE angle_delta value={}",
13115 delta + ANGLE_DELTA_ZERO as i32
13116 );
13117 }
13118 delta
13119 } else {
13120 0
13121 };
13122 istep!("angle_y", angle_delta_y);
13123 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
13124 // here so every `decode_block` caller (64x64 and 128x128 roots included)
13125 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
13126 let cfl = cfl && cfl_allowed_px(side, side, fctx);
13127 let uv_mode = if cfl {
13128 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13129 } else {
13130 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13131 };
13132 if trace {
13133 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
13134 }
13135 istep!("uv_mode", uv_mode as i32);
13136 let alpha = if cfl && uv_mode == UV_CFL_PRED {
13137 Some(read_cfl_alphas(dec, cdfs))
13138 } else {
13139 None
13140 };
13141 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
13142 // from this lane's directional chroma: a corner block with neither
13143 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
13144 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
13145 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
13146 // bug in that fallback this lane's own scope does not cover. Keep it
13147 // refused here rather than ship a silently-wrong decode.
13148 if (9..=12).contains(&uv_mode) {
13149 hit!(SMOOTH_UV_HITS);
13150 }
13151 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
13152 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
13153 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
13154 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
13155 // the `else` branch below and never reads one either way.
13156 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13157 hit!(DIRECTIONAL_UV_HITS);
13158 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13159 } else {
13160 0
13161 };
13162 istep!("angle_uv", angle_delta_uv);
13163 if angle_delta_uv != 0 {
13164 hit!(UV_ANGLE_DELTA_HITS);
13165 }
13166 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
13167 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
13168 // gated by `av1_allow_palette` (blockd.h -- size bound only,
13169 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
13170 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
13171 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
13172 // read the same CDF row whenever every neighbour really is non-palette).
13173 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
13174 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
13175 // neighbour lookup at all), so it is exact even at the excluded call
13176 // sites once Y decodes real syntax there too.
13177 //
13178 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
13179 // inline from `read_palette_mode_info` -- it runs later, from
13180 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
13181 // after the WHOLE mode-info read for the block, including UV palette
13182 // mode_info (`read_palette_mode_info`'s own second half, right below)
13183 // and `read_filter_intra_mode_info`. So this branch now only reads
13184 // mode/size/colours for both planes (deferring the two colour-index-map
13185 // decodes to after `filter_intra`, below) -- r6's range trace pinned
13186 // this exact ordering bug (`compare-range-not-tell`: ranges matched
13187 // bit-for-bit through the Y colours, diverged only at the old inline
13188 // `decode_color_index_map` call).
13189 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13190 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13191 if allow_screen_content_tools
13192 && let Some(bsize_ctx) = palette_bsize_ctx(side)
13193 {
13194 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
13195 if mode == DC_PRED {
13196 if trace {
13197 let (rng, _) = dec.debug_state();
13198 eprintln!(
13199 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
13200 );
13201 }
13202 }
13203 let use_palette_y =
13204 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
13205 if mode == DC_PRED && trace {
13206 let (rng, _) = dec.debug_state();
13207 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
13208 }
13209 if use_palette_y {
13210 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13211 if trace {
13212 let (rng, _) = dec.debug_state();
13213 eprintln!("TRACE palette_y_size n={n} rng={rng}");
13214 }
13215 let colors = read_palette_colors_y(dec, n, cache, fctx);
13216 if trace {
13217 let (rng, _) = dec.debug_state();
13218 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
13219 }
13220 palette_y_pending = Some((n, colors));
13221 }
13222 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
13223 // unconditionally at this bit position whenever `uv_mode ==
13224 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
13225 // scope always reconstructs chroma alongside luma (`decode_block`
13226 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
13227 // is always true here and does not need threading in.
13228 let palette_uv_mode_ctx = usize::from(use_palette_y);
13229 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
13230 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13231 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
13232 palette_uv_pending = Some((n, u_colors, v_colors));
13233 }
13234 }
13235 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
13236 // `use_filter_intra` symbol this decoder never read at all until
13237 // lane-av1real r10 -- silently skipping it left every bit past a
13238 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
13239 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
13240 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
13241 // symbol's bits were never consumed).
13242 let mut filter_intra = None;
13243 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
13244 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
13245 // `use_filter_intra` symbol for a Y-palette block, and reading one here
13246 // desynced every screen-content stream from the first palette block on
13247 // (it surfaced as a bogus "partition below 8x8" refusal further down the
13248 // tile).
13249 if mode == DC_PRED
13250 && enable_filter_intra
13251 && palette_y_pending.is_none()
13252 && let Some(class) = filter_intra_size_class(side)
13253 {
13254 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
13255 if trace {
13256 eprintln!(
13257 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
13258 use_filter_intra as i32
13259 );
13260 }
13261 istep!("use_filter_intra", use_filter_intra as i32);
13262 if use_filter_intra {
13263 hit!(FILTER_INTRA_HITS);
13264 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13265 if trace {
13266 eprintln!("TRACE filter_intra_mode value={fi_mode}");
13267 }
13268 istep!("filter_intra_mode", fi_mode as i32);
13269 filter_intra = Some(fi_mode);
13270 }
13271 }
13272 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
13273 // shared U/V map) -- the same order libaom's own loop visits them in.
13274 let palette_y = palette_y_pending.map(|(n, colors)| {
13275 let map = decode_color_index_map(dec, cdfs, n, side, false);
13276 hit!(PALETTE_HITS);
13277 if trace {
13278 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
13279 }
13280 PaletteY { size: n, colors, map }
13281 });
13282 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13283 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
13284 hit!(PALETTE_UV_HITS);
13285 if trace {
13286 eprintln!(
13287 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
13288 &u_colors[..n],
13289 &v_colors[..n]
13290 );
13291 }
13292 PaletteUv { size: n, u_colors, v_colors, map }
13293 });
13294 Ok((
13295 skip,
13296 mode,
13297 angle_delta_y,
13298 uv_mode,
13299 angle_delta_uv,
13300 alpha,
13301 filter_intra,
13302 palette_y,
13303 palette_uv,
13304 ))
13305}
13306
13307/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
13308/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
13309/// intra modes.
13310const UV_CFL_PRED: usize = 13;
13311
13312/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
13313/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
13314/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
13315/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
13316/// joint sign the same way. Returns each plane's final signed `alpha_q3`
13317/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
13318fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
13319 hit!(CFL_BLOCK_HITS);
13320 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
13321 let sign_u = ((joint_sign + 1) * 11) >> 5;
13322 let sign_v = (joint_sign + 1) - 3 * sign_u;
13323 let alpha_u = if sign_u == 0 {
13324 0
13325 } else {
13326 let ctx_u = (joint_sign + 1 - 3) as usize;
13327 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
13328 if sign_u == 2 { mag } else { -mag }
13329 };
13330 let alpha_v = if sign_v == 0 {
13331 0
13332 } else {
13333 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
13334 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
13335 if sign_v == 2 { mag } else { -mag }
13336 };
13337 (alpha_u, alpha_v)
13338}
13339
13340/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
13341/// the reconstructed luma samples under a `side`-square block, subsampled
13342/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
13343/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13344/// to give the AC values [`cfl_scaled`] scales by alpha.
13345fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13346 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13347}
13348
13349/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
13350/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
13351/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
13352/// reconstruction through THIS function rather than a second transcription of
13353/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
13354pub(crate) fn cfl_ac_q3_at(
13355 px: usize,
13356 py: usize,
13357 bw: usize,
13358 bh: usize,
13359 sample: impl Fn(usize, usize) -> i32,
13360) -> Vec<i32> {
13361 let (cw, ch) = (bw / 2, bh / 2);
13362 let mut ac = vec![0i32; cw * ch];
13363 let mut sum = 0i32;
13364 for cy in 0..ch {
13365 for cx in 0..cw {
13366 let (lx, ly) = (px + cx * 2, py + cy * 2);
13367 let q3 = (sample(lx, ly)
13368 + sample(lx + 1, ly)
13369 + sample(lx, ly + 1)
13370 + sample(lx + 1, ly + 1))
13371 << 1;
13372 ac[cy * cw + cx] = q3;
13373 sum += q3;
13374 }
13375 }
13376 let num_pel = (cw * ch) as i32;
13377 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13378 ac.iter_mut().for_each(|v| *v -= avg);
13379 ac
13380}
13381
13382/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13383/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13384/// ties away from zero on the shifted-out sign).
13385pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13386 let v = alpha_q3 * ac_q3;
13387 if v >= 0 {
13388 (v + 32) >> 6
13389 } else {
13390 -((-v + 32) >> 6)
13391 }
13392}
13393
13394/// One plane's reconstruction buffer, `width * height` samples, and the
13395/// prediction/residual reads and writes into it — the decode-side twin of
13396/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
13397/// (own-edge and reach clamps both), passing what it gathers straight to
13398/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
13399/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
13400/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
13401/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
13402/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
13403/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
13404/// lane-mc64 r1: the decode-order index the stage dumps below key their file
13405/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
13406/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
13407/// without this every frame overwrote `.f0` and a per-frame bisection silently
13408/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
13409#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
13410fn stage_dump_idx() -> usize {
13411 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
13412}
13413
13414fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
13415 use std::io::Write;
13416 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
13417 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
13418 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
13419 // not be read out at all.
13420 if let Ok(path) = crate::envflags::var(var)
13421 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13422 {
13423 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))] {
13424 for row in 0..h {
13425 let mut bytes = Vec::with_capacity(w * 2);
13426 for &s in &p.data[row * p.width..][..w] {
13427 bytes.extend_from_slice(&s.to_le_bytes());
13428 }
13429 let _ = f.write_all(&bytes);
13430 }
13431 }
13432 }
13433}
13434
13435/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
13436/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
13437/// every frame overwrote the previous one and only the LAST frame survived,
13438/// which silently defeats any per-frame filter-stage bisection.
13439fn dump_stage_idx(var: &str) -> usize {
13440 use std::collections::HashMap;
13441 use std::sync::{Mutex, OnceLock};
13442 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
13443 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
13444 let e = m.entry(var.to_string()).or_insert(0);
13445 let i = *e;
13446 *e += 1;
13447 i
13448}
13449
13450fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
13451 use std::io::Write;
13452 if let Ok(path) = crate::envflags::var(var)
13453 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13454 {
13455 for p in [y, u, v] {
13456 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
13457 let _ = f.write_all(&narrow);
13458 }
13459 }
13460}
13461
13462/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
13463/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
13464/// at most 4095), so a decode that hashes identically under the flag proves
13465/// the output does not depend on the plane buffer's initial content.
13466const PLANE_SENTINEL: u16 = 0xDEAD;
13467
13468/// A frame plane's own backing store, `n` samples, UNINITIALISED.
13469///
13470/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
13471/// by the tile walk's reconstruction before anything reads it, so the
13472/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
13473/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
13474/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
13475/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
13476/// ways (see the lane report) and the two agree, which is the proof that no
13477/// unwritten sample reaches the output.
13478fn fresh_plane(n: usize) -> Vec<u16> {
13479 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
13480 return vec![PLANE_SENTINEL; n];
13481 }
13482 let mut v: Vec<u16> = Vec::with_capacity(n);
13483 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
13484 // capacity was just reserved, so the vector owns `n` initialised-or-not
13485 // `u16` slots. Every one is written by reconstruction before it is read
13486 // (proven by the sentinel gate above).
13487 #[allow(unsafe_code)]
13488 unsafe {
13489 v.set_len(n);
13490 }
13491 v
13492}
13493
13494#[derive(Clone)]
13495struct PlaneBuf<'a> {
13496 data: std::borrow::Cow<'a, [u16]>,
13497 width: usize,
13498 height: usize,
13499 /// The frame's true, decodable extent in this plane's own units — past
13500 /// this, samples are the padded coding surface's invented tail, never a
13501 /// real decoder's edge or reach reads.
13502 true_width: usize,
13503 true_height: usize,
13504 /// This plane's own tile's top-left pixel origin (spec: intra prediction
13505 /// never reaches across a tile boundary even though an earlier-decoded
13506 /// tile's real pixels sit right there in the shared buffer) — set via
13507 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
13508 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
13509 /// is threaded (the two-tile column-split stage 1 fixture's tile always
13510 /// ends at the frame's own right/bottom edge); a non-last tile's own
13511 /// right/bottom reach bound is still open, tracked in the report.
13512 tile_x0: usize,
13513 tile_y0: usize,
13514 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
13515 /// (exclusive) -- a non-last tile column/row's own reach must stop at
13516 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
13517 /// full padded extent) for the single-tile/last-tile case, matching the
13518 /// old unclipped behaviour exactly.
13519 tile_x1: usize,
13520 tile_y1: usize,
13521}
13522
13523/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
13524/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
13525/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
13526/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13527/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13528/// `ALTREF2`/`ALTREF`).
13529
13530impl PlaneBuf<'_> {
13531 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
13532 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
13533 /// are already in this plane's own units (luma pixels for `y`, chroma
13534 /// pixels — halved — for `u`/`v`).
13535 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
13536 self.tile_x0 = x0;
13537 self.tile_y0 = y0;
13538 self.tile_x1 = x1;
13539 self.tile_y1 = y1;
13540 }
13541
13542 fn edges(
13543 &self,
13544 x: usize,
13545 y: usize,
13546 side: usize,
13547 reach: Reach,
13548 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13549 let own_across = x + side.min(self.true_width.saturating_sub(x));
13550 let across = if reach.above_right {
13551 own_across + side.min(self.true_width.saturating_sub(own_across))
13552 } else {
13553 own_across
13554 }
13555 .min(self.width)
13556 .min(self.tile_x1);
13557 let own_down = y + side.min(self.true_height.saturating_sub(y));
13558 let down = if reach.below_left {
13559 own_down + side.min(self.true_height.saturating_sub(own_down))
13560 } else {
13561 own_down
13562 }
13563 .min(self.height)
13564 .min(self.tile_y1);
13565 let above = (y > self.tile_y0 && across > x)
13566 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13567 let left = (x > self.tile_x0 && down > y).then(|| {
13568 (y..down)
13569 .map(|row| self.data[row * self.width + x - 1])
13570 .collect::<Vec<_>>()
13571 });
13572 let corner =
13573 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13574 (above, left, corner)
13575 }
13576
13577 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
13578 /// the above/left reach each extend by their OWN axis (`bw` across,
13579 /// `bh` down), not one shared `side`.
13580 fn edges_rect(
13581 &self,
13582 x: usize,
13583 y: usize,
13584 bw: usize,
13585 bh: usize,
13586 reach: Reach,
13587 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13588 let own_across = x + bw.min(self.true_width.saturating_sub(x));
13589 let across = if reach.above_right {
13590 own_across + bw.min(self.true_width.saturating_sub(own_across))
13591 } else {
13592 own_across
13593 }
13594 .min(self.width)
13595 .min(self.tile_x1);
13596 let own_down = y + bh.min(self.true_height.saturating_sub(y));
13597 let down = if reach.below_left {
13598 own_down + bh.min(self.true_height.saturating_sub(own_down))
13599 } else {
13600 own_down
13601 }
13602 .min(self.height)
13603 .min(self.tile_y1);
13604 let above = (y > self.tile_y0 && across > x)
13605 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13606 let left = (x > self.tile_x0 && down > y).then(|| {
13607 (y..down)
13608 .map(|row| self.data[row * self.width + x - 1])
13609 .collect::<Vec<_>>()
13610 });
13611 let corner =
13612 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13613 if matches!((bw, bh), (16, 8) | (8, 16)) {
13614 hit!(RECT_STRIP_PRED_HITS);
13615 if across > own_across || down > own_down {
13616 hit!(RECT_STRIP_REACH_HITS);
13617 }
13618 }
13619 (above, left, corner)
13620 }
13621
13622 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
13623 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
13624 /// already-rect-capable `(bw, bh)` pair.
13625 #[allow(clippy::too_many_arguments)]
13626 #[track_caller]
13627 fn reconstruct_rect(
13628 &mut self,
13629 x: usize,
13630 y: usize,
13631 bw: usize,
13632 bh: usize,
13633 mode: usize,
13634 angle_delta: i32,
13635 reach: Reach,
13636 residual: &[i32],
13637 cfl: Option<(i32, &[i32])>,
13638 filter_intra: Option<usize>,
13639 smooth_neighbor: bool,
13640 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13641 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13642 // than by this replay.
13643 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13644 ) {
13645 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
13646 // (lane-palette2 r4): a palette block's prediction is the
13647 // reconstructed colour-index map, needing no edge pixels at all.
13648 let prediction = if let Some(buf) = pred {
13649 buf
13650 } else {
13651 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
13652 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
13653 eprintln!(
13654 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
13655 above.as_ref().map(|a| (a.len(), a[0])),
13656 left.as_ref().map(|l| l.len()),
13657 left.as_ref().map(|l| l[0]),
13658 self.tile_x0, self.tile_y0, self.true_width, self.true_height
13659 );
13660 }
13661 let mut prediction = vec![0u16; bw * bh];
13662 if let Some(fi_mode) = filter_intra {
13663 crate::intra::predict_filter_intra(
13664 fi_mode,
13665 above.as_deref(),
13666 left.as_deref(),
13667 corner,
13668 bw,
13669 bh,
13670 &mut prediction, fctx,
13671 );
13672 } else {
13673 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13674 predict(
13675 mode as u8,
13676 angle_delta,
13677 above.as_deref(),
13678 left.as_deref(),
13679 corner,
13680 bw,
13681 bh,
13682 enable_edge_filter,
13683 smooth_neighbor,
13684 &mut prediction, fctx,
13685 );
13686 }
13687 prediction
13688 };
13689 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13690 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13691 if crate::envflags::env_flag!("EC_PRED") {
13692 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13693 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
13694 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
13695 eprintln!(
13696 "@{} 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)
13697 );
13698 }
13699 let residual = dense_residual(residual, bw * bh);
13700 for row in 0..bh {
13701 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
13702 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
13703 // whose padded width is not superblock aligned hangs past it.
13704 if y + row >= self.height {
13705 break;
13706 }
13707 for col in 0..bw {
13708 if x + col >= self.width {
13709 break;
13710 }
13711 let idx = row * bw + col;
13712 let mut base = i32::from(prediction[idx]);
13713 if let Some((alpha_q3, ac_q3)) = cfl {
13714 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13715 }
13716 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13717 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13718 }
13719 }
13720 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
13721 // -- a block whose prediction matches the oracle's but whose written
13722 // samples do not is either a residual defect or a later overwrite, and
13723 // only this print separates the two.
13724 if crate::envflags::env_flag!("EC_PRED") {
13725 let row0: Vec<u16> =
13726 (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect();
13727 let col0: Vec<u16> =
13728 (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect();
13729 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
13730 }
13731 }
13732
13733 /// Predicts under `mode` then adds `residual` (side*side, raster),
13734 /// writing the clamped reconstruction back into the plane at `(x, y)`.
13735 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
13736 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
13737 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
13738 /// order (cfl.c).
13739 #[track_caller]
13740 fn reconstruct(
13741 &mut self,
13742 x: usize,
13743 y: usize,
13744 side: usize,
13745 mode: usize,
13746 angle_delta: i32,
13747 reach: Reach,
13748 residual: &[i32],
13749 cfl: Option<(i32, &[i32])>,
13750 filter_intra: Option<usize>,
13751 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
13752 // libaom `get_filt_type`): true when the block's above OR left
13753 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
13754 // Callers pass their own plane's neighbour-mode check
13755 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
13756 // callers until a smooth/paeth `uv_mode` can reach this call at all
13757 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
13758 // keeps `false` exact for chroma without this fn needing to know why.
13759 smooth_neighbor: bool,
13760 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13761 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13762 // than by this replay.
13763 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13764 ) {
13765 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
13766 // takes priority over `predict()`/`predict_filter_intra` entirely --
13767 // palette prediction needs no edge pixels at all.
13768 let prediction = if let Some(buf) = pred {
13769 buf
13770 } else {
13771 let (above, left, corner) = self.edges(x, y, side, reach);
13772 let mut prediction = vec![0u16; side * side];
13773 if let Some(fi_mode) = filter_intra {
13774 crate::intra::predict_filter_intra(
13775 fi_mode,
13776 above.as_deref(),
13777 left.as_deref(),
13778 corner,
13779 side,
13780 side,
13781 &mut prediction, fctx,
13782 );
13783 } else {
13784 // `enable_intra_edge_filter` is the sequence header's own flag
13785 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
13786 // call, never per-block) -- threading it through every
13787 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
13788 // dozen sites for a value that never changes mid-decode, so it
13789 // rides a thread-local instead (this decoder is single-threaded
13790 // per stream).
13791 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13792 predict(
13793 mode as u8,
13794 angle_delta,
13795 above.as_deref(),
13796 left.as_deref(),
13797 corner,
13798 side,
13799 side,
13800 enable_edge_filter,
13801 smooth_neighbor,
13802 &mut prediction, fctx,
13803 );
13804 }
13805 prediction
13806 };
13807 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13808 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13809 if crate::envflags::env_flag!("EC_PRED") {
13810 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13811 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
13812 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
13813 eprintln!(
13814 "@{} 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)
13815 );
13816 }
13817 let residual = dense_residual(residual, side * side);
13818 for row in 0..side {
13819 // lane-sb128c r8: libaom's frame buffer is superblock
13820 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
13821 // transform unit of a 128x64 block at the BOTTOM frame edge
13822 // can hang past the last padded row (1920x792: a unit at
13823 // y=768 wants 832 rows of an 800-row buffer, which panicked
13824 // the film's key frames). Those samples are outside the
13825 // frame: never output, and no block below ever references
13826 // them.
13827 if y + row >= self.height {
13828 break;
13829 }
13830 for col in 0..side {
13831 if x + col >= self.width {
13832 break;
13833 }
13834 let idx = row * side + col;
13835 let mut base = i32::from(prediction[idx]);
13836 if let Some((alpha_q3, ac_q3)) = cfl {
13837 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13838 }
13839 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13840 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13841 }
13842 }
13843 }
13844}
13845
13846/// Reads one plane's transform block, reconstructs it into `plane` at
13847/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
13848#[allow(clippy::too_many_arguments)]
13849fn read_plane(
13850 dec: &mut SymbolDecoder,
13851 cdfs: &mut Cdfs,
13852 set: TxbSet,
13853 scan: &[u16],
13854 plane_idx: usize,
13855 around: (bool, bool, i32),
13856 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
13857 // it for every plane's `txb` lookup (it is what an intra transform type's
13858 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
13859 tx_mode: usize,
13860 predict_mode: usize,
13861 angle_delta: i32,
13862 reach: Reach,
13863 // lane-wave1 step (i): unread -- this reader records its write
13864 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
13865 // stays in the signature so every call site still proves the plane is
13866 // exclusively held while its coefficients are parsed.
13867 _plane: &mut PlaneBuf<'static>,
13868 x: usize,
13869 y: usize,
13870 side: usize,
13871 tx_side: usize,
13872 base_q_idx: u8,
13873 cfl: Option<(i32, CflSrc)>,
13874 filter_intra: Option<usize>,
13875 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
13876 // smaller than its own block (spec `get_txb_ctx_general`'s
13877 // `plane_bsize != tx_size` branch), carrying the already-looked-up
13878 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
13879 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
13880 // formula below.
13881 luma_skip_ctx: Option<usize>,
13882 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
13883 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
13884) -> Result<Grid> {
13885 let skip_ctx = if plane_idx == 0 {
13886 luma_skip_ctx.unwrap_or(0)
13887 } else {
13888 // libaom `get_txb_ctx`: a chroma unit's context is
13889 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
13890 // plane block is bigger than the transform. Our chroma tables hold the
13891 // offset-7 rows first, so the caller adds 3 for the bigger-block case
13892 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
13893 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
13894 };
13895 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
13896 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
13897 // not by the block's ordinary `mode` (which is always DC_PRED whenever
13898 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
13899 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
13900 // filter-intra in AV1).
13901 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
13902 let mut coding = cdfs.txb(set, tx_mode);
13903 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
13904 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
13905 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
13906 // plane of a lossless block (the residual then goes through the WHT, so
13907 // the type only picks the scan, which is the default one).
13908 if lossless(fctx) {
13909 coding.tx_type = None;
13910 }
13911 // Luma's `default_tx_type` is only a fallback for the sizes whose
13912 // `TxbSet` carries no symbol at all (32-point and up), which the spec
13913 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
13914 // *never* its own coded symbol (`coding.tx_type` is always `None` for
13915 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
13916 // the plane's own predicted mode (`default_intra_tx_type`) -- except
13917 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
13918 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
13919 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
13920 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
13921 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
13922 // narrows there — only `Chroma32` and up do).
13923 let default_tx_type = if plane_idx == 0 || side >= 32 {
13924 TxType::DctDct
13925 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
13926 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
13927 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
13928 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
13929 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
13930 // [`read_inter_plane`]'s own `side < 32` guard).
13931 inherited
13932 } else {
13933 default_intra_tx_type(predict_mode as u8)
13934 };
13935 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
13936 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
13937 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
13938 let (grid, tx_type) = read_coeffs(
13939 dec,
13940 &mut coding,
13941 scan,
13942 skip_ctx,
13943 dc_sign_ctx(around.2),
13944 default_tx_type,
13945 None,
13946 )?;
13947 note_chroma_class1(plane_idx, tx_type);
13948 if plane_idx == 0 {
13949 fctx.luma_tx_type.with(|c| c.set(tx_type));
13950 }
13951 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
13952 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
13953 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
13954 // guard also assumes.
13955 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
13956 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
13957 // keyed by that true size, not the coded corner's -- so the corner
13958 // goes into the top-left of a `side`-sized grid, not the reverse.
13959 let levels = extend_corner(grid, tx_side, tx_side, side, side);
13960 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
13961 let tx = TxParams {
13962 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13963 ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
13964 };
13965 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13966 let residual = tx.run(&levels);
13967 eprintln!(
13968 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
13969 );
13970 }
13971 push_intra_tx(
13972 plane_idx,
13973 x,
13974 y,
13975 side,
13976 side,
13977 false,
13978 predict_mode,
13979 angle_delta,
13980 reach,
13981 tx,
13982 &levels,
13983 cfl,
13984 filter_intra,
13985 smooth_neighbor, fctx,
13986 );
13987 // `record`'s neighbour state only reads whether *the coded grid* (not the
13988 // residual) has nonzero entries, so the levels this function already
13989 // built are what it wants back -- both arms of the old `tx_side == side`
13990 // branch returned exactly that, one of them through a full `to_vec` copy
13991 // of the grid per intra transform unit (lane-coefbuf).
13992 Ok(levels)
13993}
13994
13995/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
13996/// three planes, reconstructing them into `y`/`u`/`v` and updating
13997/// `neighbours`.
13998#[allow(clippy::too_many_arguments)]
13999fn decode_block(
14000 dec: &mut SymbolDecoder,
14001 cdfs: &mut Cdfs,
14002 neighbours: &mut Neighbours,
14003 at: (usize, usize),
14004 side: usize,
14005 luma_set: TxbSet,
14006 chroma_set: TxbSet,
14007 luma_tx: usize,
14008 chroma_tx: usize,
14009 scans: (&[u16], &[u16]),
14010 cfl: bool,
14011 y: &mut PlaneBuf<'static>,
14012 u: &mut PlaneBuf<'static>,
14013 v: &mut PlaneBuf<'static>,
14014 base_q_idx: u8,
14015 enable_filter_intra: bool,
14016 allow_screen_content_tools: bool,
14017 allow_intrabc: bool,
14018 scan32: &[u16],
14019 scan16: &[u16],
14020 scan8: &[u16],
14021 scan4: &[u16],
14022 tx_select: bool,
14023 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14024) -> Result<()> {
14025 // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
14026 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
14027 // tables/scans are replaced by the 4x4 ones and the block always takes the
14028 // multi-transform-unit path below.
14029 let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
14030 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
14031 } else {
14032 (luma_set, chroma_set, luma_tx, chroma_tx, scans)
14033 };
14034 let (r, c) = at;
14035 let (px, py) = (c * SUB, r * SUB);
14036 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14037 let palette_uv_cache = neighbours.palette_uv_cache(at);
14038 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14039 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
14040 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14041 read_intra_mode(
14042 dec,
14043 cdfs,
14044 nb_above_mode,
14045 nb_left_mode,
14046 cfl,
14047 side,
14048 enable_filter_intra,
14049 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14050 allow_screen_content_tools,
14051 allow_intrabc,
14052 Some((palette_ctx, &palette_cache)),
14053 &palette_uv_cache,
14054 r * (SUB / MI),
14055 c * (SUB / MI), fctx,
14056 )?;
14057 if at_tile_left && palette_y.is_some() {
14058 hit!(PALETTE_TILE_LEFT_HITS);
14059 }
14060 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
14061 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
14062 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
14063 // actual chroma-from-luma correlation, same as this decoder always did.
14064 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14065 DC_PRED
14066 } else {
14067 uv_mode
14068 };
14069 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14070 if smooth_neighbor {
14071 hit!(SMOOTH_LUMA_HITS);
14072 }
14073 let smooth_neighbor_uv =
14074 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
14075 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14076 eprintln!(
14077 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
14078 angle_delta_uv={angle_delta_uv}"
14079 );
14080 }
14081 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14082 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
14083 // block, skipped or not. `logical_tx` is what the loop filter's edge
14084 // lookup and the next block's own `tx_size_context` want (the *nominal*
14085 // transform size -- 64 even for the 64x64 corner-scanned case, spec
14086 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
14087 // which only differs from it at that one corner case.
14088 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
14089 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
14090 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
14091 // intrabc block reads NO tx-size symbol at all -- it takes
14092 // `maxRectTxSize` -- while every ordinary skipped intra block does read
14093 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
14094 // the tile from that block on (class `equal-range-means-unread`).
14095 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
14096 // tree instead (`read_var_tx_size`), the same syntax the inter block path
14097 // has always read -- libaom's `parse_decode_block` dispatches on
14098 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
14099 // intrabc block as inter.
14100 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
14101 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
14102 let intrabc_leaves = if intrabc_vartx {
14103 let max_tx = side.min(64);
14104 // `max_block_wide`/`max_block_high`: the frame's own mi grid
14105 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
14106 // right/bottom edge reads no split symbol for the units outside it.
14107 let mi_cols = 2 * y.true_width.div_ceil(8);
14108 let mi_rows = 2 * y.true_height.div_ceil(8);
14109 let side_mi = side / MI;
14110 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
14111 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
14112 let mut leaves = Vec::new();
14113 for row in (0..side_mi).step_by(max_tx / MI) {
14114 for col in (0..side_mi).step_by(max_tx / MI) {
14115 read_var_tx_size(
14116 dec, cdfs, neighbours, (mi_r, mi_c), side,
14117 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
14118 );
14119 }
14120 }
14121 hit!(INTRABC_VARTX_HITS);
14122 // The luma reconstruct loop below is a UNIFORM grid of one square
14123 // transform (the intra `tx_depth` shape), so a tree that resolved to
14124 // mixed leaf sizes is refused by name rather than reconstructed at the
14125 // wrong stride.
14126 let uniform = leaves
14127 .first()
14128 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
14129 if !uniform {
14130 return Err(unsupported(
14131 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
14132 ));
14133 }
14134 Some(leaves[0].2)
14135 } else {
14136 None
14137 };
14138 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
14139 (tx, if tx == 64 { 32 } else { tx })
14140 } else if tx_select && !intrabc_skip_tx {
14141 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
14142 (resolved, if resolved == 64 { 32 } else { resolved })
14143 } else {
14144 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
14145 // TX_64X64, so a 128x128 block is always FOUR luma transform units
14146 // even with `tx_select` off -- the TU loop below, never the
14147 // single-unit path.
14148 (lossless_tx(side.min(64), fctx), luma_tx)
14149 };
14150 if tx_select && logical_tx < side && uv_mode != DC_PRED {
14151 hit!(SQ_CHROMA_TX_HITS);
14152 }
14153 let luma_set = if tx_select {
14154 txbset_for(logical_tx, reduced_tx_set)
14155 } else {
14156 luma_set
14157 };
14158 let luma_set = if intrabc_dv.is_some() {
14159 txbset_for_inter(logical_tx, reduced_tx_set)
14160 } else {
14161 luma_set
14162 };
14163 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
14164 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
14165 let (cpx, cpy) = (px / 2, py / 2);
14166 let chroma_side = side / 2;
14167 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
14168 // frame's own pre-loop-filter reconstruction (all loop filters are off
14169 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
14170 // block vector, with the BILINEAR kernel libaom forces for intrabc --
14171 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
14172 // odd, which is exactly what the bilinear taps then interpolate.
14173 flush_recon(fctx, y, u, v);
14174 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14175 let mut yb = vec![0u16; side * side];
14176 mc::predict_with_filter(
14177 &y.data, y.width, y.true_width, y.true_height,
14178 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14179 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14180 );
14181 let mut ub = vec![0u16; chroma_side * chroma_side];
14182 mc::predict_with_filter(
14183 &u.data, u.width, u.true_width, u.true_height,
14184 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14185 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14186 );
14187 let mut vb = vec![0u16; chroma_side * chroma_side];
14188 mc::predict_with_filter(
14189 &v.data, v.width, v.true_width, v.true_height,
14190 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14191 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14192 );
14193 (yb, ub, vb)
14194 });
14195 // A palette-Y block's own prediction is the reconstructed colour-index
14196 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
14197 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
14198 // parameter through this function's dozen `y.reconstruct`/`read_plane`
14199 // sites. A split luma transform (`tx_select && logical_tx != side`)
14200 // would need the map sliced per-TU -- untested against a real
14201 // `--enable-palette=1` stream this round, so refuse by name rather than
14202 // guess at the slicing (charter's own named-acceptable fallback).
14203 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
14204 py.map
14205 .iter()
14206 .map(|&idx| py.colors[idx as usize])
14207 .collect()
14208 });
14209 // lane-t900 r32: the intrabc luma prediction rides the very same
14210 // whole-block override slot, so the multi-TU loop below windows it per
14211 // transform unit exactly like a palette map -- setting it once up front
14212 // handed the whole `side`x`side` buffer to the FIRST unit and left every
14213 // later one predicting off block edges (the var-tx tree above is what
14214 // first makes `logical_tx < side` reachable for an intrabc block).
14215 let palette_y_buf = match &intrabc_bufs {
14216 Some((yb, _, _)) => Some(yb.clone()),
14217 None => palette_y_buf,
14218 };
14219 // With one luma transform unit the whole `side`x`side` map is the
14220 // prediction; with several (`logical_tx != side`) each unit takes its own
14221 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
14222 // below (lane-palette2 r7) -- setting the full-block buffer here would be
14223 // taken by the FIRST unit and indexed at the wrong stride.
14224 if let Some(buf) = &palette_y_buf
14225 && logical_tx == side
14226 {
14227 set_palette_pred(buf.clone(), fctx);
14228 }
14229 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
14230 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
14231 // plane's own `reconstruct`/`read_plane` call below (never both planes at
14232 // once), since Y's own set-then-take already emptied the slot by the time
14233 // either of these run.
14234 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14235 (
14236 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
14237 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
14238 )
14239 });
14240 // The chroma half of the intrabc prediction rides the same per-plane
14241 // override slot the UV-palette buffers do (set fresh before each plane's
14242 // own `reconstruct`/`read_plane` call below).
14243 let palette_uv_bufs = match &intrabc_bufs {
14244 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
14245 None => palette_uv_bufs,
14246 };
14247 if skip {
14248 // A skipped block codes no residual syntax at all (spec 5.11.34):
14249 // straight prediction, on every plane.
14250 //
14251 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
14252 // is skipped (only an INTER skip forces the largest transform), and
14253 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
14254 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
14255 // already written left/above of it inside this same block. Predicting
14256 // the whole `side`x`side` at once gives a different (uniformly off by
14257 // ~1) answer, which is exactly the residue this lane was chasing.
14258 // The palette/intrabc override path keeps the single-call shape (its
14259 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
14260 // untested for skip and unreachable in these streams).
14261 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
14262 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
14263 // per-unit prediction is keyed on the transform being smaller than
14264 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
14265 // narrower meaning (a READ split tx depth).
14266 let split_tx_skip =
14267 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
14268 if split_tx_skip {
14269 if tx_select {
14270 hit!(SKIP_SPLIT_TX_HITS);
14271 }
14272 let n_axis = side / logical_tx;
14273 for tu_row in 0..n_axis {
14274 for tu_col in 0..n_axis {
14275 let tu_px = px + tu_col * logical_tx;
14276 let tu_py = py + tu_row * logical_tx;
14277 if tu_px >= y.true_width || tu_py >= y.true_height {
14278 continue;
14279 }
14280 let tu_reach = tu_reach(
14281 side,
14282 side,
14283 tu_col * logical_tx,
14284 tu_row * logical_tx,
14285 logical_tx,
14286 reach,
14287 px,
14288 py,
14289 y.width,
14290 y.height, fctx,
14291 );
14292 push_intra(0,
14293 tu_px,
14294 tu_py,
14295 logical_tx,
14296 mode,
14297 angle_delta_y,
14298 tu_reach,
14299 &ZERO_RESIDUAL[..logical_tx * logical_tx],
14300 None,
14301 filter_intra,
14302 smooth_neighbor, fctx,
14303 );
14304 }
14305 }
14306 } else {
14307 push_intra(0,
14308 px,
14309 py,
14310 side,
14311 mode,
14312 angle_delta_y,
14313 reach,
14314 &ZERO_RESIDUAL[..side * side],
14315 None,
14316 filter_intra,
14317 smooth_neighbor, fctx,
14318 );
14319 }
14320 let ac = alpha.map(|_| cfl_src(px, py, side));
14321 let cn = (chroma_side / chroma_tx).max(1);
14322 for cu_row in 0..cn {
14323 for cu_col in 0..cn {
14324 let luma_span = chroma_tx * 2;
14325 let cu_r = if cn == 1 {
14326 reach
14327 } else {
14328 tu_reach(
14329 side, side,
14330 cu_col * luma_span, cu_row * luma_span, luma_span,
14331 reach, px, py, y.width, y.height, fctx,
14332 )
14333 };
14334 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14335 if let Some((ub, _)) = &palette_uv_bufs {
14336 set_palette_pred(ub.clone(), fctx);
14337 }
14338 push_intra(1,
14339 cu_x,
14340 cu_y,
14341 chroma_tx,
14342 uv_predict_mode,
14343 angle_delta_uv,
14344 cu_r,
14345 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14346 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14347 None,
14348 smooth_neighbor_uv, fctx,
14349 );
14350 if let Some((_, vb)) = &palette_uv_bufs {
14351 set_palette_pred(vb.clone(), fctx);
14352 }
14353 push_intra(2,
14354 cu_x,
14355 cu_y,
14356 chroma_tx,
14357 uv_predict_mode,
14358 angle_delta_uv,
14359 cu_r,
14360 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14361 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14362 None,
14363 smooth_neighbor_uv, fctx,
14364 );
14365 }
14366 }
14367 let luma_grid = vec![0i32; side * side];
14368 let u_grid = vec![0i32; chroma_side * chroma_side];
14369 let v_grid = vec![0i32; chroma_side * chroma_side];
14370 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14371 } else if logical_tx == side {
14372 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
14373 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
14374 // that arm was redundant -- and wrong at 128, where
14375 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
14376 // block is four units whether or not `tx_select` is on.
14377 // A single luma transform unit -- the old path, unchanged (including
14378 // the 64x64 corner case, `logical_tx == side == 64` with
14379 // `coeff_tx_side == 32`).
14380 let around = neighbours.around(at, side);
14381 let luma_grid = read_plane(
14382 dec,
14383 cdfs,
14384 luma_set,
14385 luma_scan,
14386 0,
14387 around[0],
14388 mode,
14389 mode,
14390 angle_delta_y,
14391 reach,
14392 y,
14393 px,
14394 py,
14395 side,
14396 coeff_tx_side,
14397 base_q_idx,
14398 None,
14399 filter_intra,
14400 None,
14401 smooth_neighbor, fctx,
14402 )?;
14403 let ac = alpha.map(|_| cfl_src(px, py, side));
14404 // Armed for exactly this block's two chroma reads (see
14405 // [`INTRABC_CHROMA_TX`]); the luma call above just set
14406 // [`LUMA_TX_TYPE`] to the type it coded.
14407 if intrabc_dv.is_some() {
14408 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14409 }
14410 if let Some((ub, _)) = &palette_uv_bufs {
14411 set_palette_pred(ub.clone(), fctx);
14412 }
14413 let u_grid = read_plane(
14414 dec,
14415 cdfs,
14416 chroma_set,
14417 scans.1,
14418 1,
14419 around[1],
14420 mode,
14421 uv_predict_mode,
14422 angle_delta_uv,
14423 reach,
14424 u,
14425 cpx,
14426 cpy,
14427 chroma_side,
14428 chroma_tx,
14429 base_q_idx,
14430 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14431 None,
14432 None,
14433 smooth_neighbor_uv, fctx,
14434 )?;
14435 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14436 eprintln!(
14437 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
14438 &u.data[cpy * u.width + cpx..][..chroma_side]
14439 );
14440 }
14441 if let Some((_, vb)) = &palette_uv_bufs {
14442 set_palette_pred(vb.clone(), fctx);
14443 }
14444 let v_grid = read_plane(
14445 dec,
14446 cdfs,
14447 chroma_set,
14448 scans.1,
14449 2,
14450 around[2],
14451 mode,
14452 uv_predict_mode,
14453 angle_delta_uv,
14454 reach,
14455 v,
14456 cpx,
14457 cpy,
14458 chroma_side,
14459 chroma_tx,
14460 base_q_idx,
14461 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14462 None,
14463 None,
14464 smooth_neighbor_uv, fctx,
14465 )?;
14466 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14467 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14468 } else {
14469 // Several luma transform units, raster order (spec
14470 // `transform_block`'s loop): the block's resolved transform is
14471 // genuinely smaller than its own side, so each tile of it predicts
14472 // and codes independently, its own context read fresh off whatever
14473 // the earlier tiles in this same block already wrote -- the same
14474 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
14475 let n_axis = side / logical_tx;
14476 let cn = (chroma_side / chroma_tx).max(1);
14477 // libaom's transform-block loop is over 64x64 luma "mu" chunks
14478 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
14479 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
14480 // before moving to the next one. Below 128 a block is a single chunk,
14481 // so this is byte-for-byte the all-luma-then-all-chroma order that has
14482 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
14483 // and reading all four luma units first desyncs the tile at the second
14484 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
14485 let nchunk = (side / 64).max(1);
14486 // `cn > 1` means the uv plane block is larger than the uv transform,
14487 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
14488 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
14489 let tpc = (n_axis / nchunk).max(1);
14490 let cpc = (cn / nchunk).max(1);
14491 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14492 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
14493 for ch_row in 0..nchunk {
14494 for ch_col in 0..nchunk {
14495 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14496 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14497 let tu_mi = (
14498 mi_r + tu_row * (logical_tx / MI),
14499 mi_c + tu_col * (logical_tx / MI),
14500 );
14501 let tu_px = px + tu_col * logical_tx;
14502 let tu_py = py + tu_row * logical_tx;
14503 // Same libaom clip as `decode_rect_split`'s loop above; a
14504 // square block only hangs off the frame when the frame's mi
14505 // dimensions are odd at the block's own level.
14506 if tu_px >= y.true_width || tu_py >= y.true_height {
14507 continue;
14508 }
14509 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14510 // A transform unit inside a block is NOT a block at that
14511 // position (lane-palette2 r12): `Reach::of` granted the
14512 // top-right 8x8 unit of a 16x16 D203 block bottom-left
14513 // pixels libaom refuses outright (`col_off > 0`), which is
14514 // the diagonal wedge seed 46 reconstructed wrong.
14515 let tu_reach = tu_reach(
14516 side,
14517 side,
14518 tu_col * logical_tx,
14519 tu_row * logical_tx,
14520 logical_tx,
14521 reach,
14522 px,
14523 py,
14524 y.width,
14525 y.height, fctx,
14526 );
14527 // This transform unit's own bsize (`logical_tx`) is smaller
14528 // than the block it sits in (`side`), so `txb_skip_ctx` is
14529 // the neighbour-magnitude table, not the lone-TU 0 (spec
14530 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
14531 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14532 if let Some(buf) = &palette_y_buf {
14533 hit!(PALETTE_SPLIT_TX_HITS);
14534 let mut window = vec![0u16; logical_tx * logical_tx];
14535 for row in 0..logical_tx {
14536 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
14537 window[row * logical_tx..][..logical_tx]
14538 .copy_from_slice(&buf[src..][..logical_tx]);
14539 }
14540 set_palette_pred(window, fctx);
14541 }
14542 let tu_grid = read_plane(
14543 dec,
14544 cdfs,
14545 luma_set,
14546 luma_scan,
14547 0,
14548 tu_around,
14549 mode,
14550 mode,
14551 angle_delta_y,
14552 tu_reach,
14553 y,
14554 tu_px,
14555 tu_py,
14556 logical_tx,
14557 // The unit's own COEFFICIENT grid, half its side at
14558 // TX_64X64 (a 64-point transform codes nothing past 32);
14559 // identical to `logical_tx` at every smaller size
14560 // (lane-sb128b r1).
14561 coeff_tx_side,
14562 base_q_idx,
14563 None,
14564 filter_intra,
14565 Some(tu_skip_ctx),
14566 smooth_neighbor, fctx,
14567 )?;
14568 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14569 eprintln!(
14570 "TRACE tu_bitpos mi=({},{}) tell={}",
14571 tu_mi.0,
14572 tu_mi.1,
14573 dec.debug_bitpos()
14574 );
14575 }
14576 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14577 }
14578 }
14579 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
14580 // this still runs after every luma unit of the block.
14581 let ac = alpha.map(|_| cfl_src(px, py, side));
14582 // The block's uv plane block is `chroma_side` across but its uv
14583 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
14584 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
14585 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
14586 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
14587 // FOUR units (lane-sb128b r2) -- one per mu chunk.
14588 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
14589 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
14590 // the chunk, then every V unit. At one unit per plane per chunk --
14591 // every non-lossless case this decoder reaches -- that is the same
14592 // symbol order as the interleaved pair this loop used to read; a
14593 // lossless frame's 4x4 chroma units are the case where it differs
14594 // (lane-lossless2).
14595 let mut u_pass: Vec<Grid> = Vec::new();
14596 for plane_pass in 1..=2usize {
14597 let mut pass_idx = 0usize;
14598 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
14599 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
14600 // The chroma context arrays are indexed in LUMA mi, so this
14601 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
14602 // pixels span `2 * chroma_tx` luma ones.
14603 let luma_span = chroma_tx * 2;
14604 let cu_mi = (
14605 mi_r + cu_row * (luma_span / MI),
14606 mi_c + cu_col * (luma_span / MI),
14607 );
14608 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14609 let cu_reach = if cn == 1 {
14610 reach
14611 } else {
14612 tu_reach(
14613 side, side,
14614 cu_col * luma_span, cu_row * luma_span, luma_span,
14615 reach, px, py, y.width, y.height, fctx,
14616 )
14617 };
14618 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14619 if let Some((ub, vb)) = &palette_uv_bufs {
14620 let pbuf = if plane_pass == 1 { ub } else { vb };
14621 set_palette_pred(
14622 palette_window(
14623 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
14624 chroma_tx, chroma_tx,
14625 ),
14626 fctx,
14627 );
14628 }
14629 let buf: &mut PlaneBuf<'static> =
14630 if plane_pass == 1 { &mut *u } else { &mut *v };
14631 let cu_grid = read_plane(
14632 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
14633 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
14634 chroma_tx, chroma_tx, base_q_idx,
14635 alpha.zip(ac).map(|((au, av), ac)| {
14636 (if plane_pass == 1 { au } else { av }, ac)
14637 }),
14638 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14639 )?;
14640 if cn > 1 {
14641 hit!(CHROMA_SPLIT_TX_HITS);
14642 // Immediately, so the NEXT unit of this same block reads
14643 // this one's coefficient context (libaom's chroma
14644 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
14645 // 1 from this left neighbour -- measured against aomdec).
14646 // The same writes are replayed after `record_split_luma`
14647 // below, which would otherwise clobber them whole-block.
14648 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
14649 }
14650 if plane_pass == 1 {
14651 u_pass.push(cu_grid);
14652 } else {
14653 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
14654 if cn > 1 {
14655 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
14656 }
14657 last_grids = [u_grid, cu_grid];
14658 }
14659 pass_idx += 1;
14660 }
14661 }
14662 }
14663 }
14664 }
14665 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
14666 // context write; at `cn > 1` the per-unit writes above are what the
14667 // next block reads, so they run after this (last writer wins).
14668 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
14669 for (cu_mi, luma_span, u_grid, v_grid) in &units {
14670 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
14671 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
14672 }
14673 }
14674 // Unconditional, `size == 0` for a non-palette block: clears any stale
14675 // neighbour palette state the same way [`Neighbours::record`] always
14676 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
14677 // (the split-luma-TU branch above always refuses before reaching here
14678 // when `palette_y` is `Some`, so it is never live for that branch).
14679 let (py_size, py_colors) = palette_y
14680 .as_ref()
14681 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14682 neighbours.record_palette_y(at, side, py_size, py_colors);
14683 let (puv_size, puv_colors) = palette_uv
14684 .as_ref()
14685 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14686 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
14687 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
14688 neighbours.fill_lf_grid(
14689 (r * (SUB / MI), c * (SUB / MI)),
14690 side / MI,
14691 logical_tx as u8,
14692 0, fctx,
14693 );
14694 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
14695 // `decode_block`, key frames included, and the intrabc var-tx read above
14696 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
14697 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
14698 // row. Armed by the frame's own `allow_intrabc` so every other key frame
14699 // (whose readers use the deblock-grid approximation) is untouched.
14700 if allow_intrabc {
14701 set_txfm_ctxs(
14702 neighbours,
14703 (mi_r, mi_c),
14704 logical_tx,
14705 side / MI,
14706 side / MI,
14707 skip && intrabc_dv.is_some(),
14708 );
14709 }
14710 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
14711 Ok(())
14712}
14713
14714thread_local! {
14715 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
14716 /// root's HORZ arm, and 64x128 ones at its VERT arm.
14717 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14718 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14719 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
14720 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
14721 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
14722 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
14723 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
14724 /// inter frame) -- (128x64, 64x128).
14725 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
14726 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
14727 /// handed back var-tx leaves, so the per-transform-unit luma publication
14728 /// loop never ran and the block has to clear its own luma coefficient
14729 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
14730 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
14731 /// non-vacuous.
14732 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14733}
14734
14735/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
14736pub fn skip_vartx_luma_reset_hits() -> usize {
14737 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
14738}
14739
14740/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
14741pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
14742 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
14743}
14744
14745/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
14746/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
14747pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
14748 (
14749 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
14750 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
14751 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
14752 )
14753}
14754
14755/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
14756/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
14757/// `decode_inter_block`'s own rect path).
14758///
14759/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
14760/// transform unit, with the 128-specific geometry:
14761/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
14762/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
14763/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
14764/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
14765/// same CDF a 64x64 square block reads).
14766/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
14767/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
14768/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
14769/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
14770/// a chunk before moving to the next (the interleave lane-sb128b r3
14771/// measured at the 128x128 NONE root).
14772/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
14773/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
14774/// No CfL, no filter intra (both cap at 32x32) and no palette
14775/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
14776/// reader's own size gates already say so, and the guard below is defensive.
14777#[allow(clippy::too_many_arguments)]
14778fn decode_block_128rect(
14779 dec: &mut SymbolDecoder,
14780 cdfs: &mut Cdfs,
14781 neighbours: &mut Neighbours,
14782 at: (usize, usize),
14783 bw: usize,
14784 bh: usize,
14785 y: &mut PlaneBuf<'static>,
14786 u: &mut PlaneBuf<'static>,
14787 v: &mut PlaneBuf<'static>,
14788 base_q_idx: u8,
14789 enable_filter_intra: bool,
14790 allow_screen_content_tools: bool,
14791 tx_select: bool,
14792 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14793) -> Result<()> {
14794 let (r, c) = at;
14795 let (px, py) = (c * SUB, r * SUB);
14796 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14797 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14798 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14799 let palette_uv_cache = neighbours.palette_uv_cache(at);
14800 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14801 read_intra_mode_rect(
14802 dec,
14803 cdfs,
14804 nb_above_mode,
14805 nb_left_mode,
14806 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
14807 // 13-symbol no-CFL CDF here, never the 14-symbol one.
14808 false,
14809 true,
14810 bw,
14811 bh,
14812 enable_filter_intra,
14813 neighbours.skip_txfm_ctx(mi_r, mi_c),
14814 allow_screen_content_tools,
14815 Some((palette_ctx, &palette_cache)),
14816 &palette_uv_cache,
14817 mi_r,
14818 mi_c, fctx,
14819 )?;
14820 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
14821 return Err(unsupported(
14822 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
14823 their size gates caps at 64x64 or below, so none of these symbols exists there)",
14824 ));
14825 }
14826 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14827 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14828 if smooth_neighbor {
14829 hit!(SMOOTH_LUMA_HITS);
14830 }
14831 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
14832 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
14833 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
14834 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
14835 let depth = if tx_select {
14836 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
14837 // the real `TXFM_CONTEXT` bands, and compares them against
14838 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
14839 // every 128-axis block, hence the `min(64)`.
14840 let ctx = if in_inter {
14841 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
14842 } else {
14843 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
14844 };
14845 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14846 } else {
14847 0
14848 };
14849 if depth != 0 {
14850 hit!(TX_DEPTH_HITS);
14851 }
14852 hit_do! {
14853 INTRA_SB128_DEPTH_HITS.with(|c| {
14854 let mut h = c.get();
14855 h[depth.min(2)] += 1;
14856 c.set(h);
14857 });
14858 }
14859 let logical_tx = 64 >> depth;
14860 // A 64-point transform codes nothing past its low 32 coefficients.
14861 let coeff_tx_side = logical_tx.min(32);
14862 let luma_set = txbset_for(logical_tx, reduced_tx_set);
14863 let luma_scan = default_scan(coeff_tx_side);
14864 let chroma_tx = 32;
14865 let chroma_scan = default_scan(chroma_tx);
14866 let (cpx, cpy) = (px / 2, py / 2);
14867 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
14868 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14869 let (nch_x, nch_y) = (bw / 64, bh / 64);
14870 // One 32x32 chroma unit per mu chunk, per plane.
14871 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
14872 let tpc = 64 / logical_tx;
14873 let zero_tu = vec![0i32; logical_tx * logical_tx];
14874 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
14875 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14876 let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new();
14877 for ch_row in 0..nch_y {
14878 for ch_col in 0..nch_x {
14879 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14880 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14881 let tu_mi = (
14882 mi_r + tu_row * (logical_tx / MI),
14883 mi_c + tu_col * (logical_tx / MI),
14884 );
14885 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
14886 // libaom clips the transform loop to
14887 // `max_blocks_wide/high`: a unit whose top-left sample is
14888 // outside the frame is never coded.
14889 if tu_px >= y.true_width || tu_py >= y.true_height {
14890 continue;
14891 }
14892 // Edge availability of a unit INSIDE a block, with the
14893 // 128 geometry -- `has_top_right` is false for a block
14894 // whose largest side is > 64, which [`Reach::of_rect`]
14895 // already answered for the block and [`tu_reach`] carries
14896 // down to the units on its own top row.
14897 let tu_r = tu_reach(
14898 bw,
14899 bh,
14900 tu_col * logical_tx,
14901 tu_row * logical_tx,
14902 logical_tx,
14903 reach,
14904 px,
14905 py,
14906 y.width,
14907 y.height, fctx,
14908 );
14909 if skip {
14910 push_intra(0,
14911 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
14912 None, smooth_neighbor, fctx,
14913 );
14914 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
14915 continue;
14916 }
14917 // The unit is smaller than its block, so `txb_skip_ctx`
14918 // is the neighbour-magnitude table, never the lone-TU 0.
14919 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14920 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14921 let tu_grid = read_plane(
14922 dec,
14923 cdfs,
14924 luma_set,
14925 &luma_scan,
14926 0,
14927 tu_around,
14928 mode,
14929 mode,
14930 angle_delta_y,
14931 tu_r,
14932 y,
14933 tu_px,
14934 tu_py,
14935 logical_tx,
14936 coeff_tx_side,
14937 base_q_idx,
14938 None,
14939 None,
14940 Some(tu_skip_ctx),
14941 smooth_neighbor, fctx,
14942 )?;
14943 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14944 }
14945 }
14946 // The chroma context arrays are indexed in LUMA mi, so this
14947 // unit's anchor is its own 64x64 mu chunk.
14948 let luma_span = chroma_tx * 2;
14949 let cu_mi = (
14950 mi_r + ch_row * (luma_span / MI),
14951 mi_c + ch_col * (luma_span / MI),
14952 );
14953 let cu_r = tu_reach(
14954 bw,
14955 bh,
14956 ch_col * luma_span,
14957 ch_row * luma_span,
14958 luma_span,
14959 reach,
14960 px,
14961 py,
14962 y.width,
14963 y.height, fctx,
14964 );
14965 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
14966 if skip {
14967 push_intra(1,
14968 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14969 None, smooth_neighbor_uv, fctx,
14970 );
14971 push_intra(2,
14972 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14973 None, smooth_neighbor_uv, fctx,
14974 );
14975 continue;
14976 }
14977 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14978 let u_grid = read_plane(
14979 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
14980 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14981 Some(3), smooth_neighbor_uv, fctx,
14982 )?;
14983 let v_grid = read_plane(
14984 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
14985 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14986 Some(3), smooth_neighbor_uv, fctx,
14987 )?;
14988 hit!(CHROMA_SPLIT_TX_HITS);
14989 // Immediately, so the NEXT unit of this same block reads this
14990 // one's coefficient context; replayed after `record_split_luma_rect`
14991 // below, which would otherwise clobber them whole-block.
14992 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14993 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14994 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
14995 last_grids = [u_grid, v_grid];
14996 }
14997 }
14998 if skip {
14999 neighbours.record_rect(
15000 at,
15001 bw,
15002 bh,
15003 mode,
15004 uv_predict_mode,
15005 &[
15006 &ZERO_RESIDUAL[..bw * bh],
15007 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15008 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15009 ],
15010 );
15011 } else {
15012 neighbours.record_split_luma_rect(
15013 at,
15014 bw,
15015 bh,
15016 mode,
15017 uv_predict_mode,
15018 [&last_grids[0], &last_grids[1]],
15019 );
15020 for (cu_mi, u_grid, v_grid) in &units {
15021 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
15022 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
15023 }
15024 }
15025 // No palette exists at this size; the unconditional stamp clears any
15026 // stale neighbour palette state, as every other block path does.
15027 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
15028 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
15029 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15030 neighbours.fill_lf_grid_rect(
15031 (mi_r, mi_c),
15032 bw / MI,
15033 bh / MI,
15034 logical_tx as u8,
15035 logical_tx as u8,
15036 0, fctx,
15037 );
15038 if in_inter {
15039 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
15040 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
15041 // inter frame, intra ones included: an intra block stamps its
15042 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
15043 // A key frame has no var-tx tree and its readers use the deblock grid,
15044 // so this is the inter path's alone.
15045 txfm_partition_update_rect(
15046 neighbours,
15047 (mi_r, mi_c),
15048 (logical_tx, logical_tx),
15049 (bw, bh),
15050 );
15051 hit_do! {
15052 INTRA128_IN_INTER_HITS.with(|c| {
15053 let mut h = c.get();
15054 h[usize::from(bw < bh)] += 1;
15055 c.set(h);
15056 });
15057 }
15058 } else if bw > bh {
15059 hit!(INTRA_SB128_HORZ_HITS);
15060 } else {
15061 hit!(INTRA_SB128_VERT_HITS);
15062 }
15063 Ok(())
15064}
15065
15066
15067/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
15068/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
15069/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
15070/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
15071/// just-decoded mode, not the enclosing slot's stale one, is the true
15072/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
15073/// units, which is what its coefficient context (finer than [`SUB`]) is read
15074/// at. Returns the mode this leaf decoded, for the caller's own
15075/// `prev_leaf`/final mode-writeback bookkeeping.
15076#[allow(clippy::too_many_arguments)]
15077/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
15078/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
15079/// `above_mode[col]`, and its true above neighbour is the mi directly above
15080/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
15081/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
15082/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
15083/// (bottom-right) into both, as this path did, is right only when all four
15084/// leaves happen to share a mode. `done` may be short at the true frame edge
15085/// (the straddle caller filters positions off the frame), so each side falls
15086/// back to the last leaf actually decoded.
15087fn write_back_split_modes(
15088 neighbours: &mut Neighbours,
15089 done: &[((usize, usize), usize)],
15090 parent_mi: (usize, usize),
15091 slot: (usize, usize),
15092) {
15093 let (sr, sc) = slot;
15094 let Some(&(_, last)) = done.last() else {
15095 return;
15096 };
15097 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
15098 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
15099 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
15100}
15101
15102fn decode_leaf8(
15103 dec: &mut SymbolDecoder,
15104 cdfs: &mut Cdfs,
15105 neighbours: &mut Neighbours,
15106 outer_at: (usize, usize),
15107 leaf_mi: (usize, usize),
15108 scans: (&[u16], &[u16]),
15109 prev_leaf: Option<((usize, usize), usize)>,
15110 y: &mut PlaneBuf<'static>,
15111 u: &mut PlaneBuf<'static>,
15112 v: &mut PlaneBuf<'static>,
15113 base_q_idx: u8,
15114 enable_filter_intra: bool,
15115 allow_screen_content_tools: bool,
15116 allow_intrabc: bool,
15117 tx_select: bool,
15118 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15119) -> Result<usize> {
15120 let (r, c) = outer_at;
15121 // lane-modectx r1: the group's own availability-correct fallback pair, not
15122 // the raw coarse bands (which leak across a tile edge -- see
15123 // `modes_above_left`).
15124 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
15125 if let Some(((pr, pc), pmode)) = prev_leaf {
15126 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15127 above_mode = pmode;
15128 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15129 left_mode = pmode;
15130 }
15131 }
15132 // The mi-exact neighbour wins over both the coarse 16x16 slot and
15133 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
15134 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
15135 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
15136 // lane-rectsplitx r2 swept this arm into
15137 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
15138 // "no neighbour" at a tile edge, where the coarse cell holds the block
15139 // above/left of it inside the same 16x16.
15140 let (above_mode, left_mode) =
15141 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15142 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15143 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
15144 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
15145 // this leaf's `smooth_neighbor` is built from -- passing `false` here
15146 // filtered a directional chroma block's edge at the wrong strength
15147 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
15148 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
15149 // with the coarse [`SUB`] slot as the fallback when no block recorded
15150 // that exact mi cell.
15151 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15152 if smooth_neighbor {
15153 hit!(SMOOTH_LUMA_HITS);
15154 }
15155 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
15156 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
15157 // `decode_block` caller at 16x16 and up.
15158 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
15159 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
15160 // `read_palette_mode_info`), at its REAL mi position -- passing
15161 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
15162 // moment a real 8x8 palette block fired, which is where every 8-bit
15163 // `--tune-content=screen --min-partition-size=8` stream stopped.
15164 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
15165 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
15166 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
15167 read_intra_mode(
15168 dec,
15169 cdfs,
15170 above_mode,
15171 left_mode,
15172 true,
15173 8,
15174 enable_filter_intra,
15175 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15176 allow_screen_content_tools,
15177 allow_intrabc,
15178 Some((palette_ctx, &palette_cache)),
15179 &palette_uv_cache,
15180 leaf_mi.0,
15181 leaf_mi.1, fctx,
15182 )?;
15183 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
15184 // `read_intra_mode` and then decoded the block as if it were ordinary
15185 // intra. libaom's `is_inter_block` counts an intrabc block
15186 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
15187 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
15188 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
15189 // same value with a different interval, so the tile desynced at the very
15190 // next symbol (class `wrong-alphabet-same-value`). Everything below
15191 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
15192 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
15193 if intrabc_dv.is_some() {
15194 hit!(LEAF8_INTRABC_HITS);
15195 }
15196 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
15197 // index map, mapped through the base colours, IS the block's prediction --
15198 // carried to the next `reconstruct`/`read_plane` through the same
15199 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
15200 let palette_y_buf: Option<Vec<u16>> = palette_y
15201 .as_ref()
15202 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15203 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15204 (
15205 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15206 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15207 )
15208 });
15209 let (pal_y_size, pal_y_colors) =
15210 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15211 let (pal_uv_size, pal_uv_colors) =
15212 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15213 if palette_y.is_some() || palette_uv.is_some() {
15214 hit!(PALETTE_LEAF8_HITS);
15215 }
15216 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15217 DC_PRED
15218 } else {
15219 uv_mode
15220 };
15221 neighbours.above_uv_mode[c] = uv_predict_mode;
15222 neighbours.left_uv_mode[r] = uv_predict_mode;
15223 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15224 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
15225 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
15226 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
15227 // transform units, same raster-order per-TU pattern `decode_block`'s
15228 // multi-TU branch runs).
15229 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
15230 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
15231 // intrabc block, so a SKIPPED one takes the largest transform and an
15232 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
15233 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
15234 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
15235 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
15236 let mut leaves = Vec::new();
15237 let mi_cols = 2 * y.true_width.div_ceil(8);
15238 let mi_rows = 2 * y.true_height.div_ceil(8);
15239 read_var_tx_size(
15240 dec,
15241 cdfs,
15242 neighbours,
15243 leaf_mi,
15244 8,
15245 (
15246 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
15247 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
15248 ),
15249 (8, 8),
15250 0,
15251 0,
15252 0,
15253 &mut leaves,
15254 );
15255 hit!(INTRABC_VARTX_HITS);
15256 leaves.first().map_or(8, |l| l.2)
15257 } else if tx_select && intrabc_dv.is_none() {
15258 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
15259 } else {
15260 // lane-lossless: TX_4X4 on a lossless frame, no symbol
15261 // (libaom `read_tx_size`).
15262 lossless_tx(8, fctx)
15263 };
15264 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15265 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
15266 let (cpx, cpy) = (px / 2, py / 2);
15267 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
15268 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
15269 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
15270 // the full-pel block vector, with the BILINEAR kernel libaom forces.
15271 flush_recon(fctx, y, u, v);
15272 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
15273 let mut yb = vec![0u16; 8 * 8];
15274 mc::predict_with_filter(
15275 &y.data, y.width, y.true_width, y.true_height,
15276 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
15277 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
15278 );
15279 let mut ub = vec![0u16; 4 * 4];
15280 mc::predict_with_filter(
15281 &u.data, u.width, u.true_width, u.true_height,
15282 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15283 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
15284 );
15285 let mut vb = vec![0u16; 4 * 4];
15286 mc::predict_with_filter(
15287 &v.data, v.width, v.true_width, v.true_height,
15288 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15289 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
15290 );
15291 (yb, ub, vb)
15292 });
15293 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
15294 // `decode_block` uses: set fresh right before each plane's own
15295 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
15296 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
15297 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
15298 // first shape that reaches that loop with an override set).
15299 let palette_y_buf = match &intrabc_bufs {
15300 Some((yb, _, _)) => Some(yb.clone()),
15301 None => palette_y_buf,
15302 };
15303 let (luma_grid, u_grid, v_grid);
15304 if skip {
15305 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
15306 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
15307 // transform units, each off the units already written left/above of
15308 // it inside this same leaf -- an intra block's transform size is read
15309 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
15310 // A palette block's prediction is the whole-block index map, never
15311 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
15312 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
15313 // even when `tx_depth` resolved to TX_4X4.
15314 if resolved == 4 && palette_y_buf.is_none() {
15315 hit!(SKIP_SPLIT_TX_HITS);
15316 for tu_row in 0..2 {
15317 for tu_col in 0..2 {
15318 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
15319 if tu_px >= y.true_width || tu_py >= y.true_height {
15320 continue;
15321 }
15322 let tu_reach = tu_reach(
15323 8,
15324 8,
15325 tu_col * 4,
15326 tu_row * 4,
15327 4,
15328 reach,
15329 px,
15330 py,
15331 y.width,
15332 y.height, fctx,
15333 );
15334 push_intra(0,
15335 tu_px,
15336 tu_py,
15337 4,
15338 mode,
15339 angle_delta_y,
15340 tu_reach,
15341 &ZERO_RESIDUAL[..16],
15342 None,
15343 filter_intra,
15344 smooth_neighbor, fctx,
15345 );
15346 }
15347 }
15348 } else {
15349 if let Some(buf) = &palette_y_buf {
15350 set_palette_pred(buf.clone(), fctx);
15351 }
15352 push_intra(0,
15353 px,
15354 py,
15355 8,
15356 mode,
15357 angle_delta_y,
15358 reach,
15359 &ZERO_RESIDUAL[..64],
15360 None,
15361 filter_intra,
15362 smooth_neighbor, fctx,
15363 );
15364 }
15365 let ac = alpha.map(|_| cfl_src(px, py, 8));
15366 if let Some((_, ub, _)) = &intrabc_bufs {
15367 set_palette_pred(ub.clone(), fctx);
15368 } else if let Some((ub, _)) = &palette_uv_bufs {
15369 set_palette_pred(ub.clone(), fctx);
15370 }
15371 push_intra(1,
15372 cpx,
15373 cpy,
15374 4,
15375 uv_predict_mode,
15376 angle_delta_uv,
15377 reach,
15378 &ZERO_RESIDUAL[..16],
15379 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15380 None,
15381 smooth_neighbor_uv, fctx,
15382 );
15383 if let Some((_, _, vb)) = &intrabc_bufs {
15384 set_palette_pred(vb.clone(), fctx);
15385 } else if let Some((_, vb)) = &palette_uv_bufs {
15386 set_palette_pred(vb.clone(), fctx);
15387 }
15388 push_intra(2,
15389 cpx,
15390 cpy,
15391 4,
15392 uv_predict_mode,
15393 angle_delta_uv,
15394 reach,
15395 &ZERO_RESIDUAL[..16],
15396 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15397 None,
15398 smooth_neighbor_uv, fctx,
15399 );
15400 luma_grid = Grid::Zero(64);
15401 u_grid = Grid::Zero(16);
15402 v_grid = Grid::Zero(16);
15403 } else if resolved != 4 {
15404 let around = neighbours.around_mi(leaf_mi, 8);
15405 if let Some(buf) = &palette_y_buf {
15406 set_palette_pred(buf.clone(), fctx);
15407 }
15408 luma_grid = read_plane(
15409 dec,
15410 cdfs,
15411 if intrabc_dv.is_some() {
15412 txbset_for_inter(8, reduced_tx_set)
15413 } else if reduced_tx_set {
15414 TxbSet::Luma8
15415 } else {
15416 TxbSet::Luma8Set1
15417 },
15418 scans.0,
15419 0,
15420 around[0],
15421 mode,
15422 mode,
15423 angle_delta_y,
15424 reach,
15425 y,
15426 px,
15427 py,
15428 8,
15429 TX8,
15430 base_q_idx,
15431 None,
15432 filter_intra,
15433 None,
15434 smooth_neighbor, fctx,
15435 )?;
15436 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
15437 // an intrabc block's chroma tx_type is the colocated LUMA transform's
15438 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
15439 if intrabc_dv.is_some() {
15440 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15441 }
15442 let ac = alpha.map(|_| cfl_src(px, py, 8));
15443 if let Some((_, ub, _)) = &intrabc_bufs {
15444 set_palette_pred(ub.clone(), fctx);
15445 } else if let Some((ub, _)) = &palette_uv_bufs {
15446 set_palette_pred(ub.clone(), fctx);
15447 }
15448 u_grid = read_plane(
15449 dec,
15450 cdfs,
15451 TxbSet::Chroma4,
15452 scans.1,
15453 1,
15454 around[1],
15455 mode,
15456 uv_predict_mode,
15457 angle_delta_uv,
15458 reach,
15459 u,
15460 cpx,
15461 cpy,
15462 4,
15463 TX4,
15464 base_q_idx,
15465 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15466 None,
15467 None,
15468 smooth_neighbor_uv, fctx,
15469 )?;
15470 if let Some((_, _, vb)) = &intrabc_bufs {
15471 set_palette_pred(vb.clone(), fctx);
15472 } else if let Some((_, vb)) = &palette_uv_bufs {
15473 set_palette_pred(vb.clone(), fctx);
15474 }
15475 v_grid = read_plane(
15476 dec,
15477 cdfs,
15478 TxbSet::Chroma4,
15479 scans.1,
15480 2,
15481 around[2],
15482 mode,
15483 uv_predict_mode,
15484 angle_delta_uv,
15485 reach,
15486 v,
15487 cpx,
15488 cpy,
15489 4,
15490 TX4,
15491 base_q_idx,
15492 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15493 None,
15494 None,
15495 smooth_neighbor_uv, fctx,
15496 )?;
15497 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
15498 // two chroma reads (`decode_block`'s own tail does the same) -- left
15499 // set, every later chroma block would inherit this luma tx_type,
15500 // which picks the scan and the inverse transform.
15501 fctx.intrabc_chroma_tx.with(|c| c.set(None));
15502 } else {
15503 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
15504 // grid of 4x4 transform units, each predicted from the leaf's own
15505 // 8x8 `mode` and reading its own fresh context off the earlier
15506 // units in this same leaf (the same per-TU pattern `decode_block`'s
15507 // multi-TU branch runs at bigger blocks).
15508 for tu_row in 0..2 {
15509 for tu_col in 0..2 {
15510 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15511 let tu_px = px + tu_col * 4;
15512 let tu_py = py + tu_row * 4;
15513 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15514 if crate::encode::Reach::in_vert_ab() {
15515 hit!(VERT_AB_TX4_HITS);
15516 }
15517 let tu_reach = tu_reach(
15518 8,
15519 8,
15520 tu_col * 4,
15521 tu_row * 4,
15522 4,
15523 reach,
15524 px,
15525 py,
15526 y.width,
15527 y.height, fctx,
15528 );
15529 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15530 // Each 4x4 unit predicts from its own window of the block's
15531 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
15532 // 16x16 and up) -- the whole-block buffer would be taken by
15533 // the FIRST unit and indexed at the wrong stride.
15534 if let Some(buf) = &palette_y_buf {
15535 hit!(PALETTE_SPLIT_TX_HITS);
15536 let mut window = vec![0u16; 16];
15537 for row in 0..4 {
15538 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
15539 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
15540 }
15541 set_palette_pred(window, fctx);
15542 }
15543 let tu_grid = read_plane(
15544 dec,
15545 cdfs,
15546 if intrabc_dv.is_some() {
15547 txbset_for_inter(4, reduced_tx_set)
15548 } else if reduced_tx_set {
15549 TxbSet::Luma4
15550 } else {
15551 TxbSet::Luma4Set1
15552 },
15553 scans.1,
15554 0,
15555 tu_around,
15556 mode,
15557 mode,
15558 angle_delta_y,
15559 tu_reach,
15560 y,
15561 tu_px,
15562 tu_py,
15563 4,
15564 4,
15565 base_q_idx,
15566 None,
15567 filter_intra,
15568 Some(tu_skip_ctx),
15569 smooth_neighbor, fctx,
15570 )?;
15571 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15572 eprintln!(
15573 "TRACE tu_bitpos mi=({},{}) tell={}",
15574 tu_mi.0,
15575 tu_mi.1,
15576 dec.debug_bitpos()
15577 );
15578 }
15579 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15580 }
15581 }
15582 let ac = alpha.map(|_| cfl_src(px, py, 8));
15583 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15584 if let Some((ub, _)) = &palette_uv_bufs {
15585 set_palette_pred(ub.clone(), fctx);
15586 }
15587 u_grid = read_plane(
15588 dec,
15589 cdfs,
15590 TxbSet::Chroma4,
15591 scans.1,
15592 1,
15593 chroma_around[1],
15594 mode,
15595 uv_predict_mode,
15596 angle_delta_uv,
15597 reach,
15598 u,
15599 cpx,
15600 cpy,
15601 4,
15602 TX4,
15603 base_q_idx,
15604 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15605 None,
15606 None,
15607 smooth_neighbor_uv, fctx,
15608 )?;
15609 if let Some((_, vb)) = &palette_uv_bufs {
15610 set_palette_pred(vb.clone(), fctx);
15611 }
15612 v_grid = read_plane(
15613 dec,
15614 cdfs,
15615 TxbSet::Chroma4,
15616 scans.1,
15617 2,
15618 chroma_around[2],
15619 mode,
15620 uv_predict_mode,
15621 angle_delta_uv,
15622 reach,
15623 v,
15624 cpx,
15625 cpy,
15626 4,
15627 TX4,
15628 base_q_idx,
15629 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15630 None,
15631 None,
15632 smooth_neighbor_uv, fctx,
15633 )?;
15634 // `record_split_luma` expects a `record`-style `(r, c)` position in
15635 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
15636 // already in mi units, so calling it here double-scaled the
15637 // position. Plane 0 is already correct per-TU from the
15638 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
15639 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
15640 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
15641 // leaf's own 8x8 side over `MI`).
15642 let side_mi = 2;
15643 for cell in 0..side_mi {
15644 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
15645 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
15646 }
15647 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15648 let bound_h = round_up_even(neighbours.mi_rows);
15649 let bound_w = round_up_even(neighbours.mi_cols);
15650 let u_state = neighbour_state(&u_grid);
15651 let v_state = neighbour_state(&v_grid);
15652 for cell in 0..side_mi {
15653 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15654 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15655 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15656 }
15657 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15658 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15659 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15660 }
15661 }
15662 // This leaf's own palette state into the mi-granular above/left bands
15663 // (sizes 0 when it used none, which is what clears a previous block's
15664 // palette out of the next block's ctx and colour cache).
15665 {
15666 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15667 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15668 }
15669 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15670 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
15671 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15672 // own copy; only an intrabc var-tx read consumes these bands on the intra
15673 // path, so the write is armed by `allow_intrabc`.
15674 if allow_intrabc {
15675 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
15676 }
15677 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15678 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15679 return Ok(mode);
15680 }
15681 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15682 // This leaf's own palette state into the mi-granular above/left bands
15683 // (sizes 0 when it used none, which is what clears a previous block's
15684 // palette out of the next block's ctx and colour cache).
15685 {
15686 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15687 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15688 }
15689 hit!(INTER8_SKIP_BAND_HITS);
15690 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15691 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
15692 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
15693 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
15694 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
15695 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
15696 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
15697 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
15698 // wrong CDF row, so the msac range diverged mid-frame with no refusal
15699 // (class `wrong-alphabet-same-value`; the ReelB key frame at
15700 // -ss 900, first bad luma sample row 186 col 1803).
15701 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
15702 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15703 // own copy; only an intrabc var-tx read consumes these bands on the intra
15704 // path, so the write is armed by `allow_intrabc`.
15705 if allow_intrabc {
15706 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
15707 }
15708 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15709 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
15710 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
15711 // publish its own cells exactly like `decode_block` does.
15712 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15713 Ok(mode)
15714}
15715
15716/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
15717/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
15718/// bottom, where no partition symbol is read at all -- `decode_block` runs
15719/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
15720/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
15721/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
15722/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
15723/// of the 2x2 4x4 group carries chroma syntax at all.
15724#[allow(clippy::too_many_arguments)]
15725fn read_intra_mode_sub8(
15726 dec: &mut SymbolDecoder,
15727 cdfs: &mut Cdfs,
15728 above_mode: usize,
15729 left_mode: usize,
15730 has_chroma: bool,
15731 enable_filter_intra: bool,
15732 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
15733 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
15734 // from the wrong row is the same VALUE with a different interval, so it
15735 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
15736 fi_class: usize,
15737 skip_ctx: usize,
15738 allow_intrabc: bool,
15739 mi_r: usize,
15740 mi_c: usize,
15741 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
15742 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
15743 // left the second mi column at segment 0, which reads back as a
15744 // neighbour's `cdf_index`/prediction two blocks later.
15745 seg_w_mi: usize,
15746 seg_h_mi: usize, fctx: &crate::decode::FrameCtx,
15747) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
15748 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15749 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
15750 if ec_istep {
15751 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
15752 }
15753 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
15754 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
15755 macro_rules! istep {
15756 ($name:literal, $val:expr) => {
15757 if ec_istep {
15758 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0);
15759 }
15760 };
15761 }
15762 // lane-seg2: same `intra_segment_id` placement as the square and rect
15763 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
15764 // like any other block, over its own 1x1 mi footprint. Dropping it here
15765 // both ate a symbol (the tile desynced at the frame's first sub-8x8
15766 // split) and left `cur_segment_id` on the previous block, so the leaf
15767 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
15768 if seg_id_pre_skip(fctx) {
15769 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
15770 }
15771 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15772 if trace {
15773 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
15774 }
15775 istep!("skip", skip as i32);
15776 if !seg_id_pre_skip(fctx) {
15777 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
15778 }
15779 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
15780 istep!("cdef", 0);
15781 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15782 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15783 istep!("dq", 0);
15784 if allow_intrabc {
15785 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15786 if use_intrabc {
15787 return Err(unsupported(
15788 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
15789 ));
15790 }
15791 }
15792 let above_ctx = INTRA_MODE_CTX[above_mode];
15793 let left_ctx = INTRA_MODE_CTX[left_mode];
15794 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15795 istep!("mode", mode);
15796 if trace {
15797 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15798 }
15799 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
15800 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
15801 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
15802 // symbol. Reading one consumed a symbol the encoder never wrote and
15803 // desynced the tile at the very next element.
15804 let angle_delta_y = 0;
15805 let chroma = if has_chroma {
15806 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15807 if trace {
15808 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
15809 }
15810 if (9..=12).contains(&uv_mode) {
15811 hit!(SMOOTH_UV_HITS);
15812 }
15813 let alpha = if uv_mode == UV_CFL_PRED {
15814 Some(read_cfl_alphas(dec, cdfs))
15815 } else {
15816 None
15817 };
15818 if (V_PRED..=D67_PRED).contains(&uv_mode) {
15819 hit!(DIRECTIONAL_UV_HITS);
15820 }
15821 // See the luma comment above: no angle delta below 8x8.
15822 let angle_delta_uv = 0;
15823 Some((uv_mode, angle_delta_uv, alpha))
15824 } else {
15825 None
15826 };
15827 let mut filter_intra = None;
15828 if mode == DC_PRED && enable_filter_intra {
15829 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
15830 if trace {
15831 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
15832 }
15833 if use_filter_intra {
15834 hit!(FILTER_INTRA_HITS);
15835 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
15836 filter_intra = Some(fi_mode);
15837 }
15838 }
15839 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
15840}
15841
15842/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
15843/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
15844/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
15845/// bookkeeping needs no change. Each leaf reads its own luma mode info,
15846/// neighboured off the *previously decoded leaf in this same group* on
15847/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
15848/// pattern, one level deeper); chroma is read and reconstructed exactly
15849/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
15850/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
15851/// derivation.
15852#[allow(clippy::too_many_arguments)]
15853fn decode_leaf_split4(
15854 dec: &mut SymbolDecoder,
15855 cdfs: &mut Cdfs,
15856 neighbours: &mut Neighbours,
15857 outer_at: (usize, usize),
15858 leaf_mi: (usize, usize),
15859 scan4: &[u16],
15860 prev_leaf: Option<((usize, usize), usize)>,
15861 y: &mut PlaneBuf<'static>,
15862 u: &mut PlaneBuf<'static>,
15863 v: &mut PlaneBuf<'static>,
15864 base_q_idx: u8,
15865 enable_filter_intra: bool,
15866 allow_intrabc: bool,
15867 reduced_tx_set: bool,
15868 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
15869 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
15870 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
15871 fctx: &crate::decode::FrameCtx,
15872) -> Result<(usize, usize)> {
15873 hit!(SUB8_SPLIT_HITS);
15874 let (r, c) = outer_at;
15875 let mut above_mode = neighbours.above_mode[c];
15876 let mut left_mode = neighbours.left_mode[r];
15877 if let Some(((pr, pc), pmode)) = prev_leaf {
15878 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15879 above_mode = pmode;
15880 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15881 left_mode = pmode;
15882 }
15883 }
15884 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
15885 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
15886 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15887 let mut leaf_modes = [0usize; 4];
15888 let mut leaf_skips = [false; 4];
15889 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15890 for i in 0..4usize {
15891 let (dr, dc) = (i / 2, i % 2);
15892 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
15893 // Neighbour modes at real mi granularity: inside the group the
15894 // sibling leaf, outside it the split-leaf map when the adjacent mi
15895 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
15896 // `sub8_mode_col`'s doc).
15897 let leaf_above = if dr == 0 {
15898 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15899 } else {
15900 leaf_modes[i - 2]
15901 };
15902 let leaf_left = if dc == 0 {
15903 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15904 } else {
15905 leaf_modes[i - 1]
15906 };
15907 let has_chroma = i == 3;
15908 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15909 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15910 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15911 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
15912 skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx,
15913 )?;
15914 leaf_modes[i] = mode;
15915 leaf_skips[i] = skip;
15916 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
15917 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15918 if smooth_neighbor {
15919 hit!(SMOOTH_LUMA_HITS);
15920 }
15921 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15922 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
15923 if skip {
15924 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
15925 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
15926 } else {
15927 let tu_around = neighbours.around_mi(lmi, 4)[0];
15928 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
15929 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
15930 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
15931 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
15932 // off the wrong CDF on the very first leaf and desynced the tile.
15933 let tu_grid = read_plane(
15934 dec,
15935 cdfs,
15936 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
15937 scan4,
15938 0,
15939 tu_around,
15940 mode,
15941 mode,
15942 angle_delta_y,
15943 reach,
15944 y,
15945 px,
15946 py,
15947 4,
15948 4,
15949 base_q_idx,
15950 None,
15951 filter_intra,
15952 None,
15953 smooth_neighbor, fctx,
15954 )?;
15955 neighbours.record_mi_luma(lmi, 4, &tu_grid);
15956 }
15957 neighbours.fill_skip_grid(lmi, 1, skip);
15958 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
15959 if has_chroma {
15960 last_uv = chroma;
15961 }
15962 }
15963 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15964 let (cpx, cpy) = (gpx / 2, gpy / 2);
15965 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15966 let (uv_mode, angle_delta_uv, alpha) =
15967 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
15968 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15969 neighbours.above_uv_mode[c] = uv_predict_mode;
15970 neighbours.left_uv_mode[r] = uv_predict_mode;
15971 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15972 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
15973 // A skipped chroma block still gets its CfL contribution: libaom's
15974 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15975 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15976 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15977 // added -- `skip_txfm` only drops the residual, never the alpha.
15978 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15979 // merge keeps one fix and feeds both lanes' counters so neither of
15980 // their gates goes vacuous.
15981 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15982 if alpha.is_some() {
15983 hit!(CHROMA_SKIP_CFL_HITS);
15984 hit!(SKIP_CFL_HITS);
15985 }
15986 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);
15987 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);
15988 (Grid::Zero(16), Grid::Zero(16))
15989 } else {
15990 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15991 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15992 let ug = read_plane(
15993 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15994 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15995 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15996 )?;
15997 let vg = read_plane(
15998 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15999 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16000 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16001 )?;
16002 (ug, vg)
16003 };
16004 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
16005 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
16006 // rescaling is wrong for an already-mi-unit position, so this inlines
16007 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
16008 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
16009 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
16010 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
16011 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
16012 // bottom). libaom's `update_ext_partition_context` writes
16013 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
16014 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
16015 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
16016 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
16017 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
16018 // round's bug) makes the very next sibling 8x8's `partition_w8` read
16019 // with the wrong context and desync immediately.
16020 let side_mi = 2;
16021 for cell in 0..side_mi {
16022 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
16023 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
16024 }
16025 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16026 let bound_h = round_up_even(neighbours.mi_rows);
16027 let bound_w = round_up_even(neighbours.mi_cols);
16028 let u_state = neighbour_state(&u_grid);
16029 let v_state = neighbour_state(&v_grid);
16030 for cell in 0..side_mi {
16031 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
16032 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16033 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16034 }
16035 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
16036 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16037 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16038 }
16039 }
16040 // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette`
16041 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
16042 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
16043 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
16044 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
16045 // block above a 4x4 group left its size/colours standing in the mi-granular
16046 // bands: the block below the group read `palette_y_mode` off CDF row 1
16047 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
16048 // palette libaom never coded, and then skipped the `use_filter_intra`
16049 // symbol that a palette block has none of -- one symbol short, tile
16050 // desynced. Publishing the group's own zeros is the clear.
16051 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16052 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16053 Ok((leaf_modes[2], leaf_modes[1]))
16054}
16055
16056/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
16057/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
16058/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
16059/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
16060/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
16061/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
16062/// every sub-block one mi wide or high but the last) -- differing only where
16063/// the shape does:
16064///
16065/// * the transform is a true `TX_4X8`/`TX_8X4`
16066/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
16067/// `av1_inv_txfm_shift_ls` row already cover this size pair);
16068/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
16069/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
16070/// row -- see that variant's doc comment;
16071/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
16072/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
16073/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
16074/// ([`Reach::of_rect`]);
16075/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
16076/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
16077/// `BLOCK_4X4` split writes.
16078///
16079/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
16080/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
16081/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
16082/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
16083/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
16084/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
16085#[allow(clippy::too_many_arguments)]
16086fn decode_leaf_rect8(
16087 dec: &mut SymbolDecoder,
16088 cdfs: &mut Cdfs,
16089 neighbours: &mut Neighbours,
16090 outer_at: (usize, usize),
16091 leaf_mi: (usize, usize),
16092 vert: bool,
16093 scan4: &[u16],
16094 y: &mut PlaneBuf<'static>,
16095 u: &mut PlaneBuf<'static>,
16096 v: &mut PlaneBuf<'static>,
16097 base_q_idx: u8,
16098 enable_filter_intra: bool,
16099 allow_intrabc: bool,
16100 tx_select: bool,
16101 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
16102) -> Result<(usize, usize)> {
16103 let (r, c) = outer_at;
16104 // lane-modectx r1: availability-correct fallback pair (see
16105 // `modes_above_left`), not the raw coarse bands.
16106 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
16107 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
16108 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
16109 let (w_mi, h_mi) = (bw / MI, bh / MI);
16110 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
16111 let mut leaf_modes = [0usize; 2];
16112 let mut leaf_skips = [false; 2];
16113 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
16114 for i in 0..2usize {
16115 let lmi = if vert {
16116 (leaf_mi.0, leaf_mi.1 + i)
16117 } else {
16118 (leaf_mi.0 + i, leaf_mi.1)
16119 };
16120 // Inside the pair the sibling is the neighbour on the split axis;
16121 // outside it the mi-granular map, else the coarse 16x16 slot.
16122 let leaf_above = if !vert && i == 1 {
16123 leaf_modes[0]
16124 } else {
16125 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
16126 };
16127 let leaf_left = if vert && i == 1 {
16128 leaf_modes[0]
16129 } else {
16130 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
16131 };
16132 let has_chroma = i == 1;
16133 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
16134 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
16135 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
16136 filter_intra_size_class_rect(bw, bh)
16137 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
16138 skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx,
16139 )?;
16140 if filter_intra.is_some() {
16141 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
16142 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
16143 // same `reconstruct_rect`/`reconstruct` calls below -- and under
16144 // a split transform, per 4x4 unit with that unit's own edge,
16145 // which is exactly what the depth-1 loop already does.
16146 hit!(FILTER_INTRA_RECT_HITS);
16147 hit!(FILTER_INTRA_RECT_SUB8_HITS);
16148 }
16149 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
16150 // leaf too, and is read for every intra block, skipped or not. Its
16151 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
16152 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
16153 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
16154 // `tx_size_cat2` the 32x16 strips read -- with the rect context
16155 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
16156 // Missing this read consumed one symbol fewer than the encoder wrote
16157 // and desynced the tile at the very first rect leaf (class
16158 // `symbol-consumption-gap`).
16159 let depth = if tx_select {
16160 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
16161 // read every other rect reader now does -- a no-op on a key frame.
16162 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16163 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
16164 } else {
16165 tx_size_context_rect(neighbours, lmi, bw, bh)
16166 };
16167 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16168 } else {
16169 0
16170 };
16171 if depth != 0 {
16172 hit!(TX_DEPTH_HITS);
16173 hit!(RECT8_SPLIT_TX_HITS);
16174 }
16175 leaf_modes[i] = mode;
16176 leaf_skips[i] = skip;
16177 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
16178 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
16179 if smooth_neighbor {
16180 hit!(SMOOTH_LUMA_HITS);
16181 }
16182 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
16183 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16184 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
16185 // two 4x4 transform units along its long axis, each predicted from
16186 // the previous unit's reconstruction and reading its own `txb_skip`
16187 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
16188 // four. The per-TU path writes its own neighbour state, so the
16189 // block-level write below is skipped for it.
16190 let split = depth != 0 || lossless(fctx);
16191 if split {
16192 let mut done = 0usize;
16193 for tu in 0..2usize {
16194 let tu_mi = if vert {
16195 (lmi.0 + tu, lmi.1)
16196 } else {
16197 (lmi.0, lmi.1 + tu)
16198 };
16199 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
16200 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
16201 // Same per-TU rule as every other split-transform site
16202 // (lane-palette2 r12): a transform unit inside a block is not
16203 // a block at that position, so its reach comes from the
16204 // block's own row, offset by the unit's position.
16205 let tu_reach = tu_reach(
16206 bw,
16207 bh,
16208 tu_px - px,
16209 tu_py - py,
16210 4,
16211 reach,
16212 px,
16213 py,
16214 y.width,
16215 y.height, fctx,
16216 );
16217 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
16218 if skip {
16219 // A skipped leaf still predicts per transform unit: the
16220 // second 4x4 takes its above/left edge from the first
16221 // one's reconstruction, which is NOT what a single 4x8
16222 // prediction of the same mode produces.
16223 let zeros = vec![0i32; 16];
16224 push_intra(0,
16225 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
16226 filter_intra, smooth_neighbor, fctx,
16227 );
16228 neighbours.record_mi_luma(tu_mi, 4, &zeros);
16229 continue;
16230 }
16231 let tu_grid = read_plane(
16232 dec,
16233 cdfs,
16234 if reduced_tx_set {
16235 TxbSet::Luma4
16236 } else {
16237 TxbSet::Luma4Set1
16238 },
16239 scan4,
16240 0,
16241 tu_around,
16242 mode,
16243 mode,
16244 angle_delta_y,
16245 tu_reach,
16246 y,
16247 tu_px,
16248 tu_py,
16249 4,
16250 TX4,
16251 base_q_idx,
16252 None,
16253 filter_intra,
16254 Some(tu_skip_ctx),
16255 smooth_neighbor, fctx,
16256 )?;
16257 if tu_grid.iter().any(|&l| l != 0) {
16258 done += 1;
16259 }
16260 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
16261 }
16262 if done > 0 {
16263 if vert {
16264 hit!(TX4X8_CODED_HITS);
16265 } else {
16266 hit!(TX8X4_CODED_HITS);
16267 }
16268 }
16269 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16270 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
16271 if has_chroma {
16272 last_uv = chroma;
16273 }
16274 continue;
16275 }
16276 let grid = if skip {
16277 let zeros = Grid::Zero(bw * bh);
16278 push_intra_rect(0,
16279 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
16280 smooth_neighbor, fctx,
16281 );
16282 zeros
16283 } else {
16284 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
16285 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
16286 // at 0 -- see `decode_leaf_split4`'s own note.
16287 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
16288 let set = if reduced_tx_set {
16289 TxbSet::LumaRect4x8
16290 } else {
16291 TxbSet::LumaRect4x8Set1
16292 };
16293 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
16294 let (levels, tx_type) = read_coeffs_rect(
16295 dec,
16296 &mut coding,
16297 scan,
16298 bw,
16299 bh,
16300 0,
16301 dc_sign_ctx(around.2),
16302 TxType::DctDct,
16303 )?;
16304 if levels.iter().any(|&l| l != 0) {
16305 if vert {
16306 hit!(TX4X8_CODED_HITS);
16307 } else {
16308 hit!(TX8X4_CODED_HITS);
16309 }
16310 }
16311 let residual = dequant_and_inverse_typed_wh(
16312 &levels,
16313 bw,
16314 bh,
16315 crate::decode::bit_depth(fctx),
16316 // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at
16317 // every other dequant site (class `parsed-then-discarded`).
16318 block_q_idx(fctx),
16319 plane_q_delta(0, fctx).0,
16320 plane_q_delta(0, fctx).1,
16321 tx_type,
16322 );
16323 push_intra_rect(0,
16324 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
16325 smooth_neighbor, fctx,
16326 );
16327 levels
16328 };
16329 // Plane 0's per-TU coefficient context over this leaf's own mi span
16330 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
16331 // for the whole 8x8 group below).
16332 let state = neighbour_state(&grid);
16333 for cell in 0..h_mi {
16334 if lmi.0 + cell < neighbours.mi_rows {
16335 neighbours.left[lmi.0 + cell][0] = state;
16336 }
16337 }
16338 for cell in 0..w_mi {
16339 if lmi.1 + cell < neighbours.mi_cols {
16340 neighbours.above[lmi.1 + cell][0] = state;
16341 }
16342 }
16343 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16344 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
16345 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
16346 if has_chroma {
16347 last_uv = chroma;
16348 }
16349 }
16350 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16351 let (cpx, cpy) = (gpx / 2, gpy / 2);
16352 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
16353 let (uv_mode, angle_delta_uv, alpha) =
16354 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
16355 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16356 neighbours.above_uv_mode[c] = uv_predict_mode;
16357 neighbours.left_uv_mode[r] = uv_predict_mode;
16358 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16359 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] {
16360 // A skipped chroma block still gets its CfL contribution: libaom's
16361 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16362 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16363 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16364 // added -- `skip_txfm` only drops the residual, never the alpha.
16365 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16366 // merge keeps one fix and feeds both lanes' counters so neither of
16367 // their gates goes vacuous.
16368 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16369 if alpha.is_some() {
16370 hit!(CHROMA_SKIP_CFL_HITS);
16371 hit!(SKIP_CFL_HITS);
16372 }
16373 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);
16374 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);
16375 (Grid::Zero(16), Grid::Zero(16))
16376 } else {
16377 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16378 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16379 let ug = read_plane(
16380 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16381 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16382 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16383 )?;
16384 let vg = read_plane(
16385 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16386 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16387 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16388 )?;
16389 (ug, vg)
16390 };
16391 // `update_partition_context` at the 8x8 level writes
16392 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
16393 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
16394 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
16395 // `partition_ctx_mi` reads back off these side values.
16396 for cell in 0..2 {
16397 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
16398 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
16399 }
16400 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16401 let bound_h = round_up_even(neighbours.mi_rows);
16402 let bound_w = round_up_even(neighbours.mi_cols);
16403 let u_state = neighbour_state(&u_grid);
16404 let v_state = neighbour_state(&v_grid);
16405 for cell in 0..2usize {
16406 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
16407 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16408 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16409 }
16410 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
16411 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16412 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16413 }
16414 }
16415 // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette`
16416 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
16417 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
16418 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
16419 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
16420 // block above a 4x4 group left its size/colours standing in the mi-granular
16421 // bands: the block below the group read `palette_y_mode` off CDF row 1
16422 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
16423 // palette libaom never coded, and then skipped the `use_filter_intra`
16424 // symbol that a palette block has none of -- one symbol short, tile
16425 // desynced. Publishing the group's own zeros is the clear.
16426 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16427 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16428 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
16429 // bottom one (the second under HORZ, the left one under VERT), the one a
16430 // neighbour to the right sees is the top-right (the second under VERT).
16431 Ok(if vert {
16432 (leaf_modes[0], leaf_modes[1])
16433 } else {
16434 (leaf_modes[1], leaf_modes[0])
16435 })
16436}
16437
16438/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
16439/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
16440/// (mod 8) reuse the same table.
16441const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
16442 [(-1, 1), (-2, 2)],
16443 [(0, 1), (-1, 2)],
16444 [(0, 1), (0, 2)],
16445 [(0, 1), (1, 2)],
16446 [(1, 1), (2, 2)],
16447 [(1, 0), (2, 1)],
16448 [(1, 0), (2, 0)],
16449 [(1, 0), (2, -1)],
16450];
16451/// A neighbour tap outside the frame's true extent -- `constrain` reads this
16452/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
16453const CDEF_VERY_LARGE: i32 = 0x4000;
16454const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
16455const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
16456
16457fn cdef_msb(x: i32) -> i32 {
16458 31 - x.leading_zeros() as i32
16459}
16460
16461/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
16462/// centre sample a filter tap is allowed to contribute.
16463#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16464fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
16465 if threshold == 0 {
16466 return 0;
16467 }
16468 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
16469}
16470
16471/// `constrain`'s damping shift: a function of the block's threshold and
16472/// damping alone, so the filter loop computes it once per block instead of
16473/// the `leading_zeros` + branch it used to do twice per tap read.
16474fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
16475 (damping - cdef_msb(threshold)).max(0)
16476}
16477
16478/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
16479/// non-zero on every call (the caller only filters when its strength is).
16480fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
16481 let a = diff.abs();
16482 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
16483}
16484
16485/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
16486/// lies inside its own samples grown by this much.
16487const CDEF_BORDER: usize = 2;
16488
16489/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
16490/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
16491/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
16492/// index a small contiguous window instead of re-deriving the frame-bounds
16493/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
16494/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
16495fn cdef_gather(
16496 src: &[u16],
16497 stride: usize,
16498 true_w: usize,
16499 true_h: usize,
16500 ox: usize,
16501 oy: usize,
16502 bw: usize,
16503 bh: usize,
16504 buf: &mut [i16],
16505) {
16506 let bstride = bw + 2 * CDEF_BORDER;
16507 let rows = bh + 2 * CDEF_BORDER;
16508 if oy >= CDEF_BORDER
16509 && ox >= CDEF_BORDER
16510 && oy + bh + CDEF_BORDER <= true_h
16511 && ox + bw + CDEF_BORDER <= true_w
16512 {
16513 // Interior block: every tap is inside the frame, so the whole window
16514 // is `rows` contiguous runs.
16515 for r in 0..rows {
16516 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
16517 let src_row = &src[s0..s0 + bstride];
16518 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
16519 for (d, &v) in dst_row.iter_mut().zip(src_row) {
16520 *d = v as i16;
16521 }
16522 }
16523 return;
16524 }
16525 for r in 0..rows {
16526 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
16527 for c in 0..bstride {
16528 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
16529 buf[r * bstride + c] =
16530 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
16531 CDEF_VERY_LARGE as i16
16532 } else {
16533 src[ny as usize * stride + nx as usize] as i16
16534 };
16535 }
16536 }
16537}
16538
16539/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
16540/// array takes the row, its reverse, its pairwise sums or its total added
16541/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
16542/// per-sample form did become a handful of lane-wide adds per row. i32 is
16543/// exact here: every partial is a sum of at most eight values in -128..127,
16544/// and slot 15 exists only so an eight-lane store at offset 7 fits.
16545fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
16546 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
16547 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
16548 *d += x;
16549 }
16550 }
16551 let mut partial = [[0i32; 16]; 8];
16552 for i in 0..8usize {
16553 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16554 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
16555 // accumulating, same as `constrain`'s threshold shift.
16556 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
16557 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
16558 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
16559 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
16560 let (p, rest) = partial.split_at_mut(1);
16561 add_at(&mut p[0], i, &row); // partial[0][i + j]
16562 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
16563 rest[1][i] = row.iter().sum(); // partial[2][i]
16564 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
16565 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
16566 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
16567 add_at(&mut rest[5], 0, &row); // partial[6][j]
16568 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
16569 }
16570 partial
16571}
16572
16573/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
16574/// direction of an 8x8 luma window and the variance gap between it and its
16575/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
16576/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
16577fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
16578 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
16579 #[cfg(target_arch = "x86_64")]
16580 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16581 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16582 // the same eight rows of eight samples the scalar form does.
16583 #[allow(unsafe_code)]
16584 unsafe {
16585 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
16586 }
16587 } else {
16588 cdef_find_dir_partials(win, bstride, coeff_shift)
16589 };
16590 #[cfg(not(target_arch = "x86_64"))]
16591 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
16592 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
16593 let mut cost = [0i64; 8];
16594 for i in 0..8usize {
16595 cost[2] += sq(partial[2][i]);
16596 cost[6] += sq(partial[6][i]);
16597 }
16598 cost[2] *= DIV_TABLE[8];
16599 cost[6] *= DIV_TABLE[8];
16600 for i in 0..7usize {
16601 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
16602 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
16603 }
16604 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
16605 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
16606 for i in (1..8).step_by(2) {
16607 for j in 0..5usize {
16608 cost[i] += sq(partial[i][3 + j]);
16609 }
16610 cost[i] *= DIV_TABLE[8];
16611 for j in 0..3usize {
16612 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
16613 }
16614 }
16615 let mut best_cost = 0i64;
16616 let mut best_dir = 0usize;
16617 for (i, &c) in cost.iter().enumerate() {
16618 if c > best_cost {
16619 best_cost = c;
16620 best_dir = i;
16621 }
16622 }
16623 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
16624 (best_dir, var as i32)
16625}
16626
16627/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
16628/// (high variance gap) gets more deringing than a flat or non-directional
16629/// one, only ever applied to the luma primary strength.
16630fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
16631 if var == 0 {
16632 return 0;
16633 }
16634 let i = if var >> 6 != 0 {
16635 cdef_msb(var >> 6).min(12)
16636 } else {
16637 0
16638 };
16639 (strength * (4 + i) + 8) >> 4
16640}
16641
16642/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
16643/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
16644/// previously-filtered neighbour must never feed this block's own sum).
16645#[allow(clippy::too_many_arguments)]
16646#[allow(unsafe_code)]
16647fn cdef_filter_block(
16648 src: &[i16],
16649 dst: &mut PlaneBuf<'static>,
16650 ox: usize,
16651 oy: usize,
16652 bw: usize,
16653 bh: usize,
16654 pri_strength: i32,
16655 sec_strength: i32,
16656 dir: usize,
16657 pri_damping: i32,
16658 sec_damping: i32,
16659 enable_primary: bool,
16660 enable_secondary: bool,
16661 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
16662) {
16663 let (stride, smax) = (dst.width, sample_max(fctx));
16664 #[cfg(target_arch = "x86_64")]
16665 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
16666 {
16667 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16668 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
16669 // `bh` runs of `bw` samples the scalar form writes.
16670 unsafe {
16671 cdef_simd::filter_block_avx2(
16672 src,
16673 dst.data.to_mut(),
16674 stride,
16675 ox,
16676 oy,
16677 bw,
16678 bh,
16679 pri_strength,
16680 sec_strength,
16681 dir,
16682 pri_damping,
16683 sec_damping,
16684 enable_primary,
16685 enable_secondary,
16686 coeff_shift,
16687 smax,
16688 )
16689 };
16690 return;
16691 }
16692 cdef_filter_block_scalar(
16693 src,
16694 dst.data.to_mut(),
16695 stride,
16696 ox,
16697 oy,
16698 bw,
16699 bh,
16700 pri_strength,
16701 sec_strength,
16702 dir,
16703 pri_damping,
16704 sec_damping,
16705 enable_primary,
16706 enable_secondary,
16707 coeff_shift,
16708 smax,
16709 );
16710}
16711
16712/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
16713/// the form every non-AVX2 build decodes through and the one
16714/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
16715#[allow(clippy::too_many_arguments)]
16716fn cdef_filter_block_scalar(
16717 src: &[i16],
16718 dst: &mut [u16],
16719 stride: usize,
16720 ox: usize,
16721 oy: usize,
16722 bw: usize,
16723 bh: usize,
16724 pri_strength: i32,
16725 sec_strength: i32,
16726 dir: usize,
16727 pri_damping: i32,
16728 sec_damping: i32,
16729 enable_primary: bool,
16730 enable_secondary: bool,
16731 coeff_shift: i32,
16732 smax: i32,
16733) {
16734 let clipping_required = enable_primary && enable_secondary;
16735 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
16736 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
16737 // derivative) carries the bit-depth shift, so the tap-set parity bit
16738 // must be read back above that shift, not off the raw low bit.
16739 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16740 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
16741 // `constrain`), so they are resolved here rather than per tap read.
16742 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
16743 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
16744 let bstride = bw + 2 * CDEF_BORDER;
16745 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
16746 // reaching +-CDEF_BORDER, so every index below is in range by construction.
16747 let at = |i: i32, j: i32| -> i32 {
16748 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
16749 };
16750 let (pri_dir, sec_dir0, sec_dir1) =
16751 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16752 for i in 0..bh {
16753 for j in 0..bw {
16754 let (i32i, i32j) = (i as i32, j as i32);
16755 let x = at(i32i, i32j);
16756 let mut sum = 0i32;
16757 let mut max = x;
16758 let mut min = x;
16759 for k in 0..2usize {
16760 if enable_primary {
16761 let (tr, tc) = pri_dir[k];
16762 let p0 = at(i32i + tr, i32j + tc);
16763 let p1 = at(i32i - tr, i32j - tc);
16764 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
16765 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
16766 if clipping_required {
16767 if p0 != CDEF_VERY_LARGE {
16768 max = max.max(p0);
16769 }
16770 if p1 != CDEF_VERY_LARGE {
16771 max = max.max(p1);
16772 }
16773 min = min.min(p0).min(p1);
16774 }
16775 }
16776 if enable_secondary {
16777 let (tr0, tc0) = sec_dir0[k];
16778 let (tr1, tc1) = sec_dir1[k];
16779 let s0 = at(i32i + tr0, i32j + tc0);
16780 let s1 = at(i32i - tr0, i32j - tc0);
16781 let s2 = at(i32i + tr1, i32j + tc1);
16782 let s3 = at(i32i - tr1, i32j - tc1);
16783 if clipping_required {
16784 for s in [s0, s1, s2, s3] {
16785 if s != CDEF_VERY_LARGE {
16786 max = max.max(s);
16787 }
16788 }
16789 min = min.min(s0).min(s1).min(s2).min(s3);
16790 }
16791 sum += CDEF_SEC_TAPS[k]
16792 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
16793 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
16794 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
16795 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
16796 }
16797 }
16798 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
16799 if clipping_required {
16800 y = y.clamp(min, max);
16801 }
16802 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
16803 }
16804 }
16805}
16806
16807/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
16808/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
16809/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
16810/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
16811/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
16812/// a time in 16-bit lanes.
16813///
16814/// 16-bit lanes are exact for every value this filter sees: window samples
16815/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
16816/// `i16`, a `constrain` result is bounded by the threshold (at most
16817/// `15 << 4`), and the tap-weighted sum by `24 *` that.
16818#[cfg(target_arch = "x86_64")]
16819#[allow(unsafe_code)]
16820#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16821mod cdef_simd {
16822 use super::{
16823 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
16824 CDEF_VERY_LARGE,
16825 };
16826 use std::arch::x86_64::*;
16827
16828 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
16829 /// register (low half = row `i`).
16830 ///
16831 /// # Safety
16832 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
16833 #[target_feature(enable = "avx2")]
16834 #[inline]
16835 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
16836 let lo = _mm_loadu_si128(w.offset(off).cast());
16837 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
16838 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
16839 }
16840
16841 /// Spec 7.15.3's `constrain`, lane-parallel:
16842 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
16843 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
16844 /// clamped magnitude is already 0 where `diff` is).
16845 ///
16846 /// # Safety
16847 /// Requires AVX2.
16848 #[target_feature(enable = "avx2")]
16849 #[inline]
16850 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
16851 let diff = _mm256_sub_epi16(p, x);
16852 let a = _mm256_abs_epi16(diff);
16853 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
16854 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
16855 _mm256_sign_epi16(t, diff)
16856 }
16857
16858 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
16859 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
16860 /// four the auto-vectorised scalar form gets without the feature.
16861 ///
16862 /// # Safety
16863 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
16864 /// grown by `CDEF_BORDER` at row stride `bstride`.
16865 #[target_feature(enable = "avx2")]
16866 pub unsafe fn find_dir_partials_avx2(
16867 win: &[i16],
16868 bstride: usize,
16869 coeff_shift: i32,
16870 ) -> [[i32; 16]; 8] {
16871 #[target_feature(enable = "avx2")]
16872 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
16873 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
16874 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
16875 }
16876 #[target_feature(enable = "avx2")]
16877 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
16878 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
16879 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
16880 }
16881 let mut partial = [[0i32; 16]; 8];
16882 let shift = _mm_cvtsi32_si128(coeff_shift);
16883 let c128 = _mm256_set1_epi32(128);
16884 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
16885 let mut p6 = _mm256_setzero_si256();
16886 for i in 0..8usize {
16887 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16888 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
16889 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
16890 let rev = _mm256_permutevar8x32_epi32(row, revidx);
16891 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
16892 // four pairwise sums are the two lanes' low halves joined.
16893 let h = _mm256_hadd_epi32(row, row);
16894 let pair =
16895 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
16896 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
16897 let hs = _mm_hadd_epi32(pair, pair);
16898 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
16899 add8(&mut partial[0], i, row);
16900 add4(&mut partial[1], i, pair);
16901 partial[2][i] = total;
16902 add4(&mut partial[3], i, rpair);
16903 add8(&mut partial[4], i, rev);
16904 add8(&mut partial[5], 3 - i / 2, row);
16905 p6 = _mm256_add_epi32(p6, row);
16906 add8(&mut partial[7], i / 2, row);
16907 }
16908 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
16909 partial
16910 }
16911
16912 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
16913 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
16914 /// `bw == 4` the upper four lanes of each half are window samples read
16915 /// past the row (never past the buffer -- `w` is padded to 256 entries),
16916 /// computed and then dropped by the 64-bit store.
16917 ///
16918 /// # Safety
16919 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
16920 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
16921 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
16922 /// of `bw` samples at `(ox, oy)`.
16923 #[target_feature(enable = "avx2")]
16924 #[allow(clippy::too_many_arguments)]
16925 pub unsafe fn filter_block_avx2(
16926 src: &[i16],
16927 dst: &mut [u16],
16928 stride: usize,
16929 ox: usize,
16930 oy: usize,
16931 bw: usize,
16932 bh: usize,
16933 pri_strength: i32,
16934 sec_strength: i32,
16935 dir: usize,
16936 pri_damping: i32,
16937 sec_damping: i32,
16938 enable_primary: bool,
16939 enable_secondary: bool,
16940 coeff_shift: i32,
16941 smax: i32,
16942 ) {
16943 let bstride = bw + 2 * CDEF_BORDER;
16944 // The caller's window is already `i16` and 256 entries long, so the
16945 // kernel taps it in place: the largest two-row load is
16946 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
16947 // 4x4 chroma one, both inside the buffer's zeroed tail.
16948 let w = src;
16949 let clipping_required = enable_primary && enable_secondary;
16950 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16951 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
16952 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
16953 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
16954 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
16955 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
16956 let zero = _mm256_setzero_si256();
16957 let eight = _mm256_set1_epi16(8);
16958 let smaxv = _mm256_set1_epi16(smax as i16);
16959 let (pri_dir, sec_dir0, sec_dir1) =
16960 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16961 let wp = w.as_ptr();
16962 let bs = bstride as isize;
16963 let dp = dst.as_mut_ptr();
16964 let mut i = 0usize;
16965 while i < bh {
16966 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
16967 let x = ld2(wp, base, bs);
16968 let mut sum = zero;
16969 let mut max = x;
16970 let mut min = x;
16971 for k in 0..2usize {
16972 if enable_primary {
16973 let (tr, tc) = pri_dir[k];
16974 let off = tr as isize * bs + tc as isize;
16975 let p0 = ld2(wp, base + off, bs);
16976 let p1 = ld2(wp, base - off, bs);
16977 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
16978 sum = _mm256_add_epi16(
16979 sum,
16980 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
16981 );
16982 sum = _mm256_add_epi16(
16983 sum,
16984 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
16985 );
16986 if clipping_required {
16987 // The sentinel is excluded from the max exactly as the
16988 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
16989 // 0 cannot win a max whose seed `x` is non-negative.
16990 max = _mm256_max_epi16(
16991 max,
16992 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
16993 );
16994 max = _mm256_max_epi16(
16995 max,
16996 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
16997 );
16998 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
16999 }
17000 }
17001 if enable_secondary {
17002 let (tr0, tc0) = sec_dir0[k];
17003 let (tr1, tc1) = sec_dir1[k];
17004 let off0 = tr0 as isize * bs + tc0 as isize;
17005 let off1 = tr1 as isize * bs + tc1 as isize;
17006 let s0 = ld2(wp, base + off0, bs);
17007 let s1 = ld2(wp, base - off0, bs);
17008 let s2 = ld2(wp, base + off1, bs);
17009 let s3 = ld2(wp, base - off1, bs);
17010 if clipping_required {
17011 for s in [s0, s1, s2, s3] {
17012 max = _mm256_max_epi16(
17013 max,
17014 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
17015 );
17016 }
17017 min = _mm256_min_epi16(
17018 min,
17019 _mm256_min_epi16(
17020 _mm256_min_epi16(s0, s1),
17021 _mm256_min_epi16(s2, s3),
17022 ),
17023 );
17024 }
17025 let c = _mm256_add_epi16(
17026 _mm256_add_epi16(
17027 constrain(s0, x, sec_thr, sec_shift),
17028 constrain(s1, x, sec_thr, sec_shift),
17029 ),
17030 _mm256_add_epi16(
17031 constrain(s2, x, sec_thr, sec_shift),
17032 constrain(s3, x, sec_thr, sec_shift),
17033 ),
17034 );
17035 sum = _mm256_add_epi16(
17036 sum,
17037 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
17038 );
17039 }
17040 }
17041 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
17042 let neg = _mm256_cmpgt_epi16(zero, sum);
17043 let mut y = _mm256_add_epi16(
17044 x,
17045 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
17046 );
17047 if clipping_required {
17048 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
17049 }
17050 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
17051 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
17052 let o0 = ((oy + i) * stride + ox) as isize;
17053 let o1 = o0 + stride as isize;
17054 if bw == 8 {
17055 _mm_storeu_si128(dp.offset(o0).cast(), lo);
17056 _mm_storeu_si128(dp.offset(o1).cast(), hi);
17057 } else {
17058 _mm_storel_epi64(dp.offset(o0).cast(), lo);
17059 _mm_storel_epi64(dp.offset(o1).cast(), hi);
17060 }
17061 i += 2;
17062 }
17063 }
17064}
17065
17066/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
17067/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
17068/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
17069/// every block's level comes from [`LoopFilterParams::level`] plus the
17070/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
17071/// `get_filter_level`, precomputed per-block here rather than cached in a
17072/// table the way libaom's `av1_loop_filter_frame_init` does).
17073///
17074/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
17075/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
17076fn apply_deblock(
17077 y: &mut PlaneBuf<'static>,
17078 u: &mut PlaneBuf<'static>,
17079 v: &mut PlaneBuf<'static>,
17080 lf: &LoopFilterParams,
17081 n: &Neighbours,
17082 frame_width: usize,
17083 frame_height: usize, fctx: &crate::decode::FrameCtx,
17084) {
17085 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
17086 // mismatch between the raw reconstruction and post-filter output.
17087 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
17088 return;
17089 }
17090 if lf.level[0] != 0 || lf.level[1] != 0 {
17091 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
17092 }
17093 if lf.level[2] != 0 {
17094 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
17095 }
17096 if lf.level[3] != 0 {
17097 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
17098 }
17099}
17100
17101/// [`apply_deblock`] for ONE pass over ONE band of luma rows
17102/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
17103/// planes' vertical passes and then their three horizontal ones is the same
17104/// output as `apply_deblock`'s plane-at-a-time order: the planes are
17105/// separate buffers and neither pass reads another plane.
17106#[allow(clippy::too_many_arguments)]
17107fn deblock_span(
17108 y: &mut PlaneBuf<'static>,
17109 u: &mut PlaneBuf<'static>,
17110 v: &mut PlaneBuf<'static>,
17111 lf: &LoopFilterParams,
17112 n: &Neighbours,
17113 frame_width: usize,
17114 frame_height: usize,
17115 y_lo: usize,
17116 y_hi: usize,
17117 horz: bool,
17118 fctx: &crate::decode::FrameCtx,
17119) {
17120 if lf.level[0] != 0 || lf.level[1] != 0 {
17121 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
17122 }
17123 if lf.level[2] != 0 {
17124 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
17125 }
17126 if lf.level[3] != 0 {
17127 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
17128 }
17129}
17130
17131/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
17132/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
17133/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
17134/// mi unit under this decoder's assumed 4:2:0 subsampling).
17135///
17136/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
17137/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
17138/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
17139/// prediction mode is obtained from the bottom/right mi structure of the
17140/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
17141/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
17142/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
17143/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
17144/// the group is split into 4x4 luma blocks (class
17145/// `context-read-from-one-cell`).
17146fn plane_to_mi(chroma: bool, coord: usize) -> usize {
17147 if chroma { (coord / 2) | 1 } else { coord / 4 }
17148}
17149
17150/// This plane's own transform width in pixels at the covering block, spec
17151/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
17152/// width directly; chroma halves it (this decoder's UV transform is always
17153/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
17154/// under 4:2:0 and a block that never splits its own transform).
17155fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17156 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
17157 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17158}
17159
17160/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
17161/// edges step and gate by transform height, which differs from width only
17162/// on rect partition strips.
17163fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17164 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
17165 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17166}
17167
17168/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
17169/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
17170/// present only when its neighbour exists inside the true frame -- whether
17171/// the block immediately above (at this block's own leftmost mi column) or
17172/// to the left (at its own topmost mi row) coded a transform at least as wide
17173/// as `own_side`.
17174fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
17175 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
17176 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
17177 usize::from(above) + usize::from(left)
17178}
17179
17180/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
17181/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
17182/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
17183/// inter path maintains), except that an *inter* neighbour contributes its
17184/// own BLOCK size rather than its transform size -- the two differ the moment
17185/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
17186/// approximation coincides with this only while every neighbour codes one
17187/// whole-block transform, which is exactly what `TxMode::Select` ends.
17188/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
17189/// r1): `get_tx_size_context` compares the neighbour ABOVE against
17190/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
17191/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
17192/// strip are two different numbers. The intra strip inside an inter frame read
17193/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
17194/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
17195/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
17196fn tx_size_context_txfm_rect(
17197 n: &Neighbours,
17198 (mi_r, mi_c): (usize, usize),
17199 own_w: usize,
17200 own_h: usize, fctx: &crate::decode::FrameCtx,
17201) -> usize {
17202 hit!(INTRA_IN_INTER_TXCTX_HITS);
17203 let has_above = mi_r > n.tile_row0_mi;
17204 let has_left = mi_c > n.tile_col0_mi;
17205 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
17206 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
17207 if has_above && n.above_inter[mi_c] {
17208 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
17209 }
17210 if has_left && n.left_inter[mi_r] {
17211 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
17212 }
17213 if crate::envflags::env_flag!("EC_TXCTX") {
17214 eprintln!(
17215 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
17216 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17217 above={above} left={left}",
17218 n.above_txfm[mi_c],
17219 n.left_txfm[mi_r],
17220 n.above_inter[mi_c],
17221 n.left_inter[mi_r],
17222 n.above_side_mi[mi_c],
17223 n.left_side_mi[mi_r],
17224 );
17225 }
17226 let ctx = match (has_above, has_left) {
17227 (true, true) => usize::from(above) + usize::from(left),
17228 (true, false) => usize::from(above),
17229 (false, true) => usize::from(left),
17230 (false, false) => 0,
17231 };
17232 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
17233 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
17234 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
17235 // intra in an inter frame" tally is green on the buggy code too (class
17236 // gate-blind-to-feature).
17237 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
17238 let (cw, ch) = (own_w.min(64), own_h.min(64));
17239 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
17240 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
17241 if ctx != stale {
17242 hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS);
17243 }
17244 }
17245 ctx
17246}
17247
17248/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
17249/// are written and read everywhere else with a raw mi index); the SUB-cell
17250/// division this pair used read a cell four blocks away, so the inter-neighbour
17251/// override above fired on the wrong neighbour -- the first divergence of the
17252/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
17253/// at the intra block right of an inter one).
17254fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
17255 let has_above = mi_r > n.tile_row0_mi;
17256 let has_left = mi_c > n.tile_col0_mi;
17257 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
17258 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
17259 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
17260 // `above_inter`/`left_inter` bands are written per MI unit
17261 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
17262 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
17263 // block whenever the neighbour column/row is not the cell's first. A
17264 // 16x16 intra block whose left neighbour is an inter block at mi row 4
17265 // then missed libaom's "an inter neighbour contributes its BLOCK size"
17266 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
17267 if has_above && n.above_inter[mi_c] {
17268 above = usize::from(n.above_side_mi[mi_c]) >= side;
17269 }
17270 if has_left && n.left_inter[mi_r] {
17271 left = usize::from(n.left_side_mi[mi_r]) >= side;
17272 }
17273 if crate::envflags::env_flag!("EC_TXCTX") {
17274 eprintln!(
17275 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
17276 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17277 above={above} left={left}",
17278 n.above_txfm[mi_c],
17279 n.left_txfm[mi_r],
17280 n.above_inter[mi_c],
17281 n.left_inter[mi_r],
17282 n.above_side_mi[mi_c],
17283 n.left_side_mi[mi_r],
17284 );
17285 }
17286 match (has_above, has_left) {
17287 (true, true) => usize::from(above) + usize::from(left),
17288 (true, false) => usize::from(above),
17289 (false, true) => usize::from(left),
17290 (false, false) => 0,
17291 }
17292}
17293
17294/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
17295/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
17296/// the transform's own side in pixels (`side >> depth`) -- this decoder's
17297/// four square categories (8/16/32/64) each halve at most twice, matching
17298/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
17299fn read_tx_size(
17300 dec: &mut SymbolDecoder,
17301 cdfs: &mut Cdfs,
17302 n: &Neighbours,
17303 at_mi: (usize, usize),
17304 side: usize,
17305 // lane-txselect: `get_tx_size_context`'s real context, for the callers
17306 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
17307 // key-frame path's own deblock-grid approximation.
17308 ctx_override: Option<usize>,
17309) -> usize {
17310 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
17311 // `get_tx_size_context`): a block wider than 64 still tops out at
17312 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
17313 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
17314 // never against its own 128 side (lane-sb128b r1).
17315 let max_tx = side.min(64);
17316 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
17317 let depth = match max_tx {
17318 8 => {
17319 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
17320 }
17321 16 => {
17322 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
17323 }
17324 32 => {
17325 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
17326 }
17327 64 => {
17328 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
17329 }
17330 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
17331 };
17332 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17333 let (rng, _) = dec.debug_state();
17334 let (mi_r, mi_c) = at_mi;
17335 eprintln!(
17336 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
17337 );
17338 }
17339 if depth != 0 {
17340 hit!(TX_DEPTH_HITS);
17341 }
17342 max_tx >> depth
17343}
17344
17345/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
17346/// `txfm_split` context -- a category from the block's own largest square
17347/// transform and whether this unit already sits below it, times three, plus
17348/// the two neighbour terms (whether the transform last written above/left of
17349/// this unit is narrower/shorter than the unit itself).
17350#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17351fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
17352 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
17353}
17354
17355/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
17356/// libaom's `txfm_partition_context` compares the above context against
17357/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
17358/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
17359/// side for a square transform, which is why the square form above is a
17360/// special case of this one.
17361pub(crate) fn txfm_partition_ctx_rect(
17362 above_px: u8,
17363 left_px: u8,
17364 blk_max_px: usize,
17365 tx_w: usize,
17366 tx_h: usize,
17367) -> usize {
17368 let above = usize::from(usize::from(above_px) < tx_w);
17369 let left = usize::from(usize::from(left_px) < tx_h);
17370 let tx_px = tx_w.max(tx_h);
17371 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
17372 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
17373 // `log2(px) - 2`.
17374 let max_tx = blk_max_px.min(64);
17375 let max_idx = max_tx.trailing_zeros() as usize - 2;
17376 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
17377 category * 3 + above + left
17378}
17379
17380/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
17381/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
17382/// resolved transform's own size.
17383#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17384fn txfm_partition_update(
17385 n: &mut Neighbours,
17386 at_mi: (usize, usize),
17387 tx_px: usize,
17388 txb_px: usize,
17389) {
17390 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
17391}
17392
17393/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
17394/// the left column records `tx_size_high` over the parent's own height and
17395/// the above row records `tx_size_wide` over its width.
17396/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
17397/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
17398/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
17399/// key frame writes neither (its readers use the deblock grid), so the
17400/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
17401/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
17402/// at the call site (the transform size comes back to them); the 1:4 arms
17403/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
17404/// so they call this where their own depth resolves. A no-op on a key frame
17405/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
17406///
17407/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
17408/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
17409/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
17410/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
17411/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
17412/// / early-return-skips-tail).
17413fn publish_txfm_bands_if_in_inter(
17414 n: &mut Neighbours,
17415 at_mi: (usize, usize),
17416 (tx_w, tx_h): (usize, usize),
17417 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
17418) {
17419 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
17420 return;
17421 }
17422 let (mi_r, mi_c) = at_mi;
17423 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17424 for i in 0..bw / MI {
17425 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17426 *cell = tx_w as u8;
17427 }
17428 }
17429 for i in 0..bh / MI {
17430 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17431 *cell = tx_h as u8;
17432 }
17433 }
17434}
17435
17436fn txfm_partition_update_rect(
17437 n: &mut Neighbours,
17438 (mi_r, mi_c): (usize, usize),
17439 (tx_w, tx_h): (usize, usize),
17440 (txb_w, txb_h): (usize, usize),
17441) {
17442 if crate::envflags::env_flag!("EC_TXUPD") {
17443 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
17444 }
17445 for i in 0..txb_h / MI {
17446 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17447 *cell = tx_h as u8;
17448 }
17449 }
17450 for i in 0..txb_w / MI {
17451 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17452 *cell = tx_w as u8;
17453 }
17454 }
17455}
17456
17457/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
17458/// same contexts -- a skipped *inter* block records its own block size rather
17459/// than its transform size.
17460fn set_txfm_ctxs(
17461 n: &mut Neighbours,
17462 (mi_r, mi_c): (usize, usize),
17463 tx_px: usize,
17464 w_mi: usize,
17465 h_mi: usize,
17466 skip_inter: bool,
17467) {
17468 if crate::envflags::env_flag!("EC_TXUPD") {
17469 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
17470 }
17471 let bw = if skip_inter { w_mi * MI } else { tx_px };
17472 let bh = if skip_inter { h_mi * MI } else { tx_px };
17473 for i in 0..w_mi {
17474 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17475 *cell = bw as u8;
17476 }
17477 }
17478 for i in 0..h_mi {
17479 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17480 *cell = bh as u8;
17481 }
17482 }
17483}
17484
17485/// The value libaom initialises both transform contexts to -- NOT zero:
17486/// `av1_zero_above_context` memsets the txfm row to
17487/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
17488/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17489/// pixels, so an unwritten neighbour reads as the *widest* possible
17490/// transform, not the narrowest.
17491pub(crate) const TXFM_CTX_INIT: u8 = 64;
17492
17493/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17494/// twice below its own largest transform.
17495const MAX_VARTX_DEPTH: usize = 2;
17496
17497/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
17498/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
17499/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
17500/// small ones, square everywhere else.
17501fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
17502 match (tx_w, tx_h) {
17503 (4, 4) => (4, 4),
17504 (8, 8) => (4, 4),
17505 (16, 16) => (8, 8),
17506 (32, 32) => (16, 16),
17507 (64, 64) => (32, 32),
17508 (4, 8) | (8, 4) => (4, 4),
17509 (8, 16) | (16, 8) => (8, 8),
17510 (16, 32) | (32, 16) => (16, 16),
17511 (32, 64) | (64, 32) => (32, 32),
17512 (4, 16) => (4, 8),
17513 (16, 4) => (8, 4),
17514 (8, 32) => (8, 16),
17515 (32, 8) => (16, 8),
17516 (16, 64) => (16, 32),
17517 (64, 16) => (32, 16),
17518 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
17519 }
17520}
17521
17522#[test]
17523fn sub_tx_size_map_matches_libaom() {
17524 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
17525 const TABLE: [((usize, usize), (usize, usize)); 19] = [
17526 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
17527 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
17528 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
17529 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
17530 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
17531 ];
17532 for (tx, want) in TABLE {
17533 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
17534 }
17535}
17536
17537/// The domain of var-tx leaf sizes, enumerated against the two refusals that
17538/// name a leaf "larger than 32x32" / "larger than 64x64".
17539///
17540/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
17541/// either the unit it was entered with or a `sub_tx_size_map` step below it:
17542/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
17543/// return. So the leaf set reachable from an entry unit is that unit plus the
17544/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
17545/// which this test enumerates, and over which no leaf is ever larger than the
17546/// entry.
17547///
17548/// That closes both refusals:
17549///
17550/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
17551/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
17552/// 64x64" names a leaf the tree cannot produce;
17553/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
17554/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
17555/// reached only when `side == 64`, and then the block is ONE unit whose only
17556/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
17557/// case the refusal is guarded by.
17558#[test]
17559fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
17560 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
17561 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
17562 out.push((depth, entry.0, entry.1));
17563 if depth == MAX_VARTX_DEPTH {
17564 return;
17565 }
17566 let sub = sub_tx_size_map(entry.0, entry.1);
17567 if sub == (4, 4) {
17568 out.push((depth + 1, 4, 4));
17569 return;
17570 }
17571 reachable(sub, depth + 1, out);
17572 }
17573
17574 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
17575 let mut leaves = Vec::new();
17576 reachable(entry, 0, &mut leaves);
17577 for (depth, w, h) in &leaves {
17578 assert!(
17579 w.max(h) <= &entry.0.max(entry.1),
17580 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
17581 entry.0,
17582 entry.1
17583 );
17584 }
17585 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
17586 if entry == (64, 64) {
17587 let above: Vec<&(usize, usize, usize)> =
17588 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
17589 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
17590 }
17591 }
17592
17593 // The entry size and ceiling each caller uses, over the block sides that
17594 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
17595 // enters at a fixed 64).
17596 for side in [8usize, 16, 32, 64, 128] {
17597 let max_tx = side.min(64);
17598 let ceiling = if side > 64 { 64 } else { 32 };
17599 let units = (side / max_tx) * (side / max_tx);
17600 if max_tx <= ceiling {
17601 continue;
17602 }
17603 assert_eq!(
17604 (side, units),
17605 (64, 1),
17606 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
17607 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
17608 );
17609 }
17610}
17611
17612/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
17613/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
17614/// max-transform-sized unit of an inter block, collecting the resolved leaf
17615/// transform units into `out` as `(row offset, col offset, side)` in mi units
17616/// -- exactly the order `decode_reconstruct_tx` later reads their
17617/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
17618/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
17619/// `max_block_high`).
17620#[allow(clippy::too_many_arguments)]
17621fn read_var_tx_size(
17622 dec: &mut SymbolDecoder,
17623 cdfs: &mut Cdfs,
17624 n: &mut Neighbours,
17625 at_mi: (usize, usize),
17626 blk_max_px: usize,
17627 (max_w_mi, max_h_mi): (usize, usize),
17628 (tx_w, tx_h): (usize, usize),
17629 depth: usize,
17630 blk_row: usize,
17631 blk_col: usize,
17632 out: &mut Vec<(usize, usize, usize, usize)>,
17633) {
17634 if blk_row >= max_h_mi || blk_col >= max_w_mi {
17635 return;
17636 }
17637 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
17638 if depth == MAX_VARTX_DEPTH {
17639 out.push((blk_row, blk_col, tx_w, tx_h));
17640 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17641 return;
17642 }
17643 let ctx = txfm_partition_ctx_rect(
17644 n.above_txfm[unit.1],
17645 n.left_txfm[unit.0],
17646 blk_max_px,
17647 tx_w,
17648 tx_h,
17649 );
17650 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17651 hit!(TXFM_SPLIT_READS);
17652 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17653 let (rng, _) = dec.debug_state();
17654 eprintln!(
17655 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
17656 unit.0,
17657 unit.1,
17658 u8::from(split)
17659 );
17660 }
17661 if !split {
17662 out.push((blk_row, blk_col, tx_w, tx_h));
17663 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17664 return;
17665 }
17666 hit!(TXFM_SPLIT_HITS);
17667 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17668 if (sub_w, sub_h) == (4, 4) {
17669 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
17670 // unit is marked 4x4 (raster order) without recursing.
17671 for row in 0..tx_h / MI {
17672 for col in 0..tx_w / MI {
17673 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
17674 out.push((blk_row + row, blk_col + col, 4, 4));
17675 }
17676 }
17677 }
17678 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
17679 return;
17680 }
17681 for row in (0..tx_h / MI).step_by(sub_h / MI) {
17682 for col in (0..tx_w / MI).step_by(sub_w / MI) {
17683 read_var_tx_size(
17684 dec,
17685 cdfs,
17686 n,
17687 at_mi,
17688 blk_max_px,
17689 (max_w_mi, max_h_mi),
17690 (sub_w, sub_h),
17691 depth + 1,
17692 blk_row + row,
17693 blk_col + col,
17694 out,
17695 );
17696 }
17697 }
17698}
17699
17700/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
17701/// branch): every block of a `TxMode::Select` inter frame codes its transform
17702/// size right after its own mode info -- an inter non-skip block through the
17703/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
17704/// every other block through the intra `tx_depth` symbol (a skipped inter
17705/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
17706/// block's own resolved transform side and the leaf list, the latter only
17707/// when the tree resolved to more than one transform unit.
17708#[allow(clippy::too_many_arguments)]
17709fn read_block_tx_size(
17710 dec: &mut SymbolDecoder,
17711 cdfs: &mut Cdfs,
17712 n: &mut Neighbours,
17713 at_mi: (usize, usize),
17714 side: usize,
17715 (mi_cols, mi_rows): (usize, usize),
17716 is_inter: bool,
17717 skip: bool, fctx: &crate::decode::FrameCtx,
17718) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17719 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
17720 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
17721 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
17722 if lossless(fctx) {
17723 let mut leaves = Vec::new();
17724 for row in 0..side / MI {
17725 for col in 0..side / MI {
17726 leaves.push((row, col, 4, 4));
17727 }
17728 }
17729 return Ok((4, Some(leaves)));
17730 }
17731 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17732 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
17733 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
17734 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
17735 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
17736 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
17737 if side > 64 {
17738 let step = 64 / MI;
17739 let mut leaves = Vec::new();
17740 for row in (0..side / MI).step_by(step) {
17741 for col in (0..side / MI).step_by(step) {
17742 leaves.push((row, col, 64, 64));
17743 }
17744 }
17745 return Ok((64, Some(leaves)));
17746 }
17747 return Ok((side, None));
17748 }
17749 let side_mi = side / MI;
17750 if is_inter && !skip {
17751 let max_tx = side.min(64);
17752 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
17753 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
17754 let mut leaves = Vec::new();
17755 let step = max_tx / MI;
17756 for row in (0..side_mi).step_by(step) {
17757 for col in (0..side_mi).step_by(step) {
17758 read_var_tx_size(
17759 dec,
17760 cdfs,
17761 n,
17762 at_mi,
17763 side,
17764 (max_w_mi, max_h_mi),
17765 (max_tx, max_tx),
17766 0,
17767 row,
17768 col,
17769 &mut leaves,
17770 );
17771 }
17772 }
17773 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
17774 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
17775 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
17776 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
17777 // which the mu-chunk reader above codes as their 32x32 coded corner.
17778 let leaf_ceiling = if side > 64 { 64 } else { 32 };
17779 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
17780 // Only a block wider than a superblock's own 64x64 max transform
17781 // reaches here; this crate has no 64-point *inter* coefficient
17782 // table set ([`inter_txbset_for`] stops at 32).
17783 return Err(unsupported(
17784 "an inter var-tx tree with a leaf transform larger than 32x32",
17785 ));
17786 }
17787 let resolved = leaves.last().map_or(side, |l| l.2);
17788 return Ok((resolved, (!single).then_some(leaves)));
17789 }
17790 let tx = if is_inter {
17791 side.min(64)
17792 } else {
17793 read_tx_size(
17794 dec,
17795 cdfs,
17796 n,
17797 at_mi,
17798 side,
17799 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
17800 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
17801 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
17802 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
17803 )
17804 };
17805 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
17806 if !is_inter && tx != side {
17807 // lane-intrainter r1: an intra block inside an inter frame whose
17808 // `tx_depth` split its luma transform codes exactly the key-frame
17809 // split path's transform units (`decode_block`'s multi-TU loop),
17810 // raster order over the block. Handed back in the same leaf shape the
17811 // inter var-tx tree uses, so the caller's per-TU luma loop, the
17812 // `record_split_luma` neighbour write-back and the per-TU deblock
17813 // edges are the ones it already runs for a var-tx inter block. A
17814 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
17815 // seeing `Some` here.
17816 let step = tx / MI;
17817 let mut leaves = Vec::new();
17818 for row in (0..side_mi).step_by(step) {
17819 for col in (0..side_mi).step_by(step) {
17820 leaves.push((row, col, tx, tx));
17821 }
17822 }
17823 hit_do! {
17824 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
17825 let mut h = c.get();
17826 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
17827 c.set(h);
17828 });
17829 }
17830 return Ok((tx, Some(leaves)));
17831 }
17832 Ok((tx, None))
17833}
17834
17835/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
17836/// decoder codes -- a 2:1 strip whose own max rect transform
17837/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
17838/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
17839/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
17840/// 64-point rect transform, and 16x8/8x16 needs
17841/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
17842/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
17843/// rect transform), neither of which exists yet -- both stay refused by name.
17844pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
17845 matches!(
17846 (w, h),
17847 // 2:1 strips whose transform is coded in full (lane-inter4).
17848 (32, 16) | (16, 32) | (16, 8) | (8, 16)
17849 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
17850 // codes all 64 of its positions, and its chroma pair is an 8x4 /
17851 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
17852 | (16, 4) | (4, 16)
17853 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
17854 // only the low 32 coefficients of a 64-length axis, so these read
17855 // exactly the truncated corner the INTRA superblock-strip path
17856 // already reads (`read_intra_mode_rect`), through
17857 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
17858 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
17859 // `tx_type` symbol is coded at all.
17860 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
17861 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
17862 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
17863 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
17864 // refused earlier ("an inter partition below 8x8").
17865 | (8, 4) | (4, 8)
17866 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
17867 // one rectangular transform -- `max_txsize_rect_lookup
17868 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
17869 // TX_64X64 units read through the mu-chunk loop, same as the
17870 // 128x128 NONE block's four.
17871 | (128, 64) | (64, 128)
17872 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
17873 // 10-bit film cuts and every measured 1080p offset stop on
17874 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
17875 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
17876 // positions, and its chroma pair is a 16x4 / 4x16 unit
17877 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
17878 | (32, 8) | (8, 32)
17879 )
17880}
17881
17882// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
17883// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
17884// the "rectangular ... has no ... here" refusals. `side` is the square context
17885// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
17886// `inter_piece!` derives `reject_residual` from exactly that inequality, so
17887// these triples are what decides whether those refusals can fire at all. Bit
17888// 31 is "a triple this table does not list", which is what makes the gate a
17889// census rather than a restatement of its own table.
17890pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
17891 (16, 16, 16),
17892 (32, 32, 32),
17893 (32, 16, 32),
17894 (32, 32, 16),
17895 (16, 8, 16),
17896 (16, 16, 8),
17897 (32, 8, 32),
17898 (64, 64, 64),
17899 (32, 32, 8),
17900 (64, 16, 64),
17901 (128, 128, 128),
17902 (64, 32, 64),
17903 (64, 64, 32),
17904 (16, 4, 16),
17905 (64, 64, 16),
17906 (16, 16, 4),
17907 (128, 128, 64),
17908 (128, 64, 128),
17909];
17910
17911/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
17912/// outside [`INTER_BLOCK_SHAPES`].
17913pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
17914
17915thread_local! {
17916 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
17917}
17918
17919/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
17920/// gate reading it sees only the streams it decoded itself).
17921pub fn inter_block_shape_mask() -> u32 {
17922 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
17923}
17924
17925/// Records one block's shape. The table is ordered by measured frequency over
17926/// the three witnesses the census gate decodes, so the common square shapes
17927/// leave the scan on their first comparison.
17928fn census_inter_block_shape(side: usize, w: usize, h: usize) {
17929 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
17930 Some(i) => 1u32 << i,
17931 None => INTER_BLOCK_SHAPE_UNLISTED,
17932 };
17933 let seen = inter_block_shape_mask();
17934 if seen & bit == 0 {
17935 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
17936 }
17937}
17938
17939/// The luma coefficient/`tx_type` table set of a whole-block rectangular
17940/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
17941/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
17942/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
17943/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
17944/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
17945/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
17946/// row (`txsize_sqr_map`), never the 16x16 one.
17947fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
17948 Ok(match (w, h) {
17949 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
17950 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
17951 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
17952 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
17953 // ALL16 otherwise -- both at the TX_4X4 row.
17954 (8, 4) | (4, 8) => {
17955 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17956 TxbSet::LumaRect8x4Inter
17957 } else {
17958 TxbSet::LumaRect8x4InterSet1
17959 }
17960 }
17961 (16, 4) | (4, 16) => {
17962 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17963 TxbSet::LumaRect16x4Inter
17964 } else {
17965 TxbSet::LumaRect16x4Inter1
17966 }
17967 }
17968 (16, 8) | (8, 16) => {
17969 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17970 TxbSet::LumaRect16x8Inter
17971 } else {
17972 TxbSet::LumaRect16x8InterSet1
17973 }
17974 }
17975 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
17976 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
17977 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
17978 // adjusted size, so the existing sets are bit-exact. Neither carries a
17979 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
17980 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
17981 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
17982 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
17983 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
17984 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
17985 (64, 32) | (32, 64) => TxbSet::Luma64,
17986 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
17987 _ => {
17988 return Err(unsupported(
17989 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
17990 ));
17991 }
17992 })
17993}
17994
17995/// The chroma table set of the same block's single rectangular chroma unit
17996/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
17997/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
17998/// the luma unit's.
17999fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
18000 Ok(match (w, h) {
18001 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
18002 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
18003 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
18004 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
18005 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
18006 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
18007 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
18008 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
18009 (32, 8) | (8, 32) => TxbSet::Chroma16,
18010 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
18011 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
18012 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
18013 (16, 4) | (4, 16) => TxbSet::Chroma8,
18014 _ => {
18015 return Err(unsupported(
18016 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
18017 ));
18018 }
18019 })
18020}
18021
18022/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
18023/// inter path reaches, from the block's TRUE footprint rather than the
18024/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
18025/// everything 32 and above -> 3.
18026fn size_group_wh(w: usize, h: usize) -> usize {
18027 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
18028 // `common_data.h:60`) is 0 for every block with a 4-px side
18029 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
18030 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
18031 match w.min(h) {
18032 0..=4 => 0,
18033 8 => 1,
18034 16 => 2,
18035 _ => 3,
18036 }
18037}
18038
18039#[test]
18040fn size_group_wh_matches_libaom_size_group_lookup() {
18041 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
18042 // transcribed values (common_data.h:60-62).
18043 const TABLE: [((usize, usize), usize); 22] = [
18044 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
18045 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
18046 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
18047 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
18048 ];
18049 for ((w, h), want) in TABLE {
18050 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
18051 }
18052}
18053
18054/// The default (2D) coefficient scan of a rectangular transform.
18055fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
18056 Ok(match (w, h) {
18057 (32, 16) => &SCAN_32X16,
18058 (16, 32) => &SCAN_16X32,
18059 (16, 8) => &SCAN_16X8,
18060 (8, 16) => &SCAN_8X16,
18061 (16, 4) => &SCAN_16X4,
18062 (4, 16) => &SCAN_4X16,
18063 (8, 4) => &SCAN_8X4,
18064 (4, 8) => &SCAN_4X8,
18065 (32, 8) => &SCAN_32X8,
18066 (8, 32) => &SCAN_8X32,
18067 _ => {
18068 return Err(unsupported(
18069 "a rectangular transform unit whose shape has no coefficient scan table here",
18070 ));
18071 }
18072 })
18073}
18074
18075/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
18076/// transform unit whose shape has no coefficient table set here" / "a
18077/// rectangular transform unit whose shape has no coefficient scan table here"
18078/// arms, enumerated against the MEASURED domain of the inter block path
18079/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
18080/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
18081///
18082/// What each helper is actually handed:
18083///
18084/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
18085/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
18086/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
18087/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
18088/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
18089/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
18090/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
18091/// unit, and only when that corner is not 32x32 (a square corner goes
18092/// through the square reader with `rect_shape = Some((w, h))`).
18093///
18094/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
18095/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
18096/// loop, which is why they are skipped below.
18097#[test]
18098fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
18099 let fctx = &crate::decode::FrameCtx::new();
18100 let corner_scan = |w: usize, h: usize| {
18101 let (cw, ch) = (w.min(32), h.min(32));
18102 if (cw, ch) == (32, 32) {
18103 return; // the square coefficient reader, not `rect_scan`
18104 }
18105 assert!(
18106 rect_scan(cw, ch).is_ok(),
18107 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
18108 );
18109 };
18110 let mut checked = 0;
18111 for &(side, w, h) in &INTER_BLOCK_SHAPES {
18112 if (w, h) == (side, side) || w.max(h) > 64 {
18113 continue;
18114 }
18115 assert!(
18116 rect_inter_luma_set(w, h, fctx).is_ok(),
18117 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
18118 );
18119 corner_scan(w, h);
18120 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
18121 // footprint for every other shape.
18122 let (cw, ch) = match (w, h) {
18123 (16, 4) => (8, 4),
18124 (4, 16) => (4, 8),
18125 _ => (w / 2, h / 2),
18126 };
18127 assert!(
18128 rect_inter_chroma_set(cw, ch).is_ok(),
18129 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
18130 );
18131 corner_scan(cw, ch);
18132 checked += 1;
18133 }
18134 assert_eq!(
18135 checked, 12,
18136 "the block-shape census changed: {checked} rect shapes reach the rect transform \
18137 tables, not the 12 this claim was measured over"
18138 );
18139 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
18140 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
18141 for (w, h) in [(8usize, 4usize), (4, 8)] {
18142 assert!(
18143 rect_inter_luma_set(w, h, fctx).is_ok(),
18144 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
18145 );
18146 corner_scan(w, h);
18147 }
18148}
18149
18150/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
18151/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
18152/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
18153/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
18154/// own width/height; a `0` leaves one whole-block rect transform unit
18155/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
18156/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
18157/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
18158/// every leaf of a split rect block is square and the existing square leaf
18159/// loop reconstructs it unchanged.
18160#[allow(clippy::too_many_arguments)]
18161fn read_block_tx_size_rect(
18162 dec: &mut SymbolDecoder,
18163 cdfs: &mut Cdfs,
18164 n: &mut Neighbours,
18165 at_mi: (usize, usize),
18166 (bw, bh): (usize, usize),
18167 (mi_cols, mi_rows): (usize, usize),
18168 skip: bool, fctx: &crate::decode::FrameCtx,
18169) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
18170 if lossless(fctx) {
18171 let mut leaves = Vec::new();
18172 for row in 0..bh / MI {
18173 for col in 0..bw / MI {
18174 leaves.push((row, col, 4, 4));
18175 }
18176 }
18177 return Ok(Some(leaves));
18178 }
18179 if skip {
18180 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
18181 // its own BLOCK size -- width above, height left -- not a transform.
18182 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
18183 return Ok(None);
18184 }
18185 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
18186 // `rect_inter_residual_supported` has already excluded everything above 32.
18187 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
18188 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
18189 // is TWO square top-level transform units side by side and a 64x128 one is
18190 // two stacked -- exactly what libaom `read_block_tx_size`
18191 // (decodeframe.c:1140) codes with its `idy/idx` loop over
18192 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
18193 // own `txfm_partition` symbol at depth 0.
18194 if bw.max(bh) > 64 {
18195 let tx = 64usize;
18196 let (max_w_mi, max_h_mi) = (
18197 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
18198 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
18199 );
18200 let mut leaves = Vec::new();
18201 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18202 for row in (0..bh / MI).step_by(tx / MI) {
18203 for col in (0..bw / MI).step_by(tx / MI) {
18204 leaves.push((row, col, tx, tx));
18205 }
18206 }
18207 for &(row, col, tw, th) in &leaves {
18208 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
18209 }
18210 return Ok(Some(leaves));
18211 }
18212 for row in (0..bh / MI).step_by(tx / MI) {
18213 for col in (0..bw / MI).step_by(tx / MI) {
18214 read_var_tx_size(
18215 dec,
18216 cdfs,
18217 n,
18218 at_mi,
18219 bw.max(bh),
18220 (max_w_mi, max_h_mi),
18221 (tx, tx),
18222 0,
18223 row,
18224 col,
18225 &mut leaves,
18226 );
18227 }
18228 }
18229 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
18230 return Err(unsupported(
18231 "an inter var-tx tree with a leaf transform larger than 64x64",
18232 ));
18233 }
18234 return Ok(Some(leaves));
18235 }
18236 let (tx_w, tx_h) = (bw, bh);
18237 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18238 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
18239 // transform, and `set_txfm_ctxs` records exactly what
18240 // `txfm_partition_update` would for that same unit.
18241 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18242 hit!(RECT_INTER_TU_HITS);
18243 return Ok(None);
18244 }
18245 let ctx = txfm_partition_ctx_rect(
18246 n.above_txfm[at_mi.1],
18247 n.left_txfm[at_mi.0],
18248 bw.max(bh),
18249 tx_w,
18250 tx_h,
18251 );
18252 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
18253 hit!(TXFM_SPLIT_READS);
18254 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18255 let (rng, _) = dec.debug_state();
18256 eprintln!(
18257 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
18258 at_mi.0,
18259 at_mi.1,
18260 u8::from(split)
18261 );
18262 }
18263 if !split {
18264 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18265 hit!(RECT_INTER_TU_HITS);
18266 return Ok(None);
18267 }
18268 hit!(TXFM_SPLIT_HITS);
18269 hit!(RECT_INTER_TXSPLIT_HITS);
18270 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
18271 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
18272 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
18273 // rect one and its leaves carry their own width and height.
18274 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
18275 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
18276 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
18277 let mut leaves = Vec::new();
18278 for row in (0..bh / MI).step_by(sub_h / MI) {
18279 for col in (0..bw / MI).step_by(sub_w / MI) {
18280 read_var_tx_size(
18281 dec,
18282 cdfs,
18283 n,
18284 at_mi,
18285 bw.max(bh),
18286 (max_w_mi, max_h_mi),
18287 (sub_w, sub_h),
18288 1,
18289 row,
18290 col,
18291 &mut leaves,
18292 );
18293 }
18294 }
18295 Ok(Some(leaves))
18296}
18297
18298/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
18299/// the coefficients are read with the rect coefficient machinery
18300/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
18301/// types), inverted with the rect inverse transform
18302/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
18303/// and added onto the top-left `w x h` of the block's own square-strided
18304/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
18305/// and the coded `tx_type`.
18306///
18307/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
18308/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
18309#[allow(clippy::too_many_arguments)]
18310fn read_inter_plane_rect(
18311 dec: &mut SymbolDecoder,
18312 cdfs: &mut Cdfs,
18313 set: TxbSet,
18314 (w, h): (usize, usize),
18315 stride: usize,
18316 plane_idx: usize,
18317 around: (bool, bool, i32),
18318 tx_mode: usize,
18319 // lane-wave1 step (i): unread -- this reader records its write
18320 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
18321 // stays in the signature so every call site still proves the plane is
18322 // exclusively held while its coefficients are parsed.
18323 _plane: &mut PlaneBuf<'static>,
18324 x: usize,
18325 y: usize,
18326 prediction: Pred<'_>,
18327 inherited_luma_tx_type: Option<TxType>,
18328 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
18329) -> Result<(Grid, TxType)> {
18330 let skip_ctx = if plane_idx == 0 {
18331 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
18332 // block; a var-tx leaf passes its own neighbour-table context.
18333 luma_skip_ctx.unwrap_or(0)
18334 } else {
18335 usize::from(around.0) + usize::from(around.1)
18336 };
18337 let mut coding = cdfs.txb(set, tx_mode);
18338 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
18339 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
18340 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
18341 // plane of a lossless block (the residual then goes through the WHT, so
18342 // the type only picks the scan, which is the default one).
18343 if lossless(fctx) {
18344 coding.tx_type = None;
18345 }
18346 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
18347 // the *longer* side of this rect transform.
18348 let default_tx_type = match inherited_luma_tx_type {
18349 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
18350 None => TxType::DctDct,
18351 };
18352 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
18353 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
18354 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
18355 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
18356 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
18357 // corner, zero-extended into the true `w x h` grid before the inverse
18358 // transform -- exactly what the intra superblock-strip path does. A
18359 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
18360 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
18361 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
18362 // rectangular shape (lane-sbpart r8).
18363 let (cw, ch) = (w.min(32), h.min(32));
18364 if plane_idx == 0 && w.max(h) == 64 {
18365 hit!(RECT64_INTER_TU_HITS);
18366 }
18367 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
18368 hit_do! {
18369 RECT32X8_INTER_TU_HITS.with(|c| {
18370 let mut v = c.get();
18371 v[usize::from(w == 8)] += 1;
18372 c.set(v);
18373 });
18374 }
18375 }
18376 let (corner, tx_type) = if (cw, ch) == (32, 32) {
18377 let scan32 = default_scan(TX32);
18378 read_coeffs(
18379 dec,
18380 &mut coding,
18381 &scan32,
18382 skip_ctx,
18383 dc_sign_ctx(around.2),
18384 default_tx_type,
18385 Some((w, h)),
18386 )?
18387 } else {
18388 read_coeffs_rect(
18389 dec,
18390 &mut coding,
18391 rect_scan(cw, ch)?,
18392 cw,
18393 ch,
18394 skip_ctx,
18395 dc_sign_ctx(around.2),
18396 default_tx_type,
18397 )?
18398 };
18399 let grid = extend_corner(corner, cw, ch, w, h);
18400 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
18401 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
18402 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
18403 }
18404 // `reconstruct_mc_rect` reads both buffers at the square prediction
18405 // stride, so the dense `w x h` residual is re-laid at that stride
18406 // (`TxParams::stride`) after the inverse transform.
18407 let tx = TxParams {
18408 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18409 stride, lossless: lossless(fctx),
18410 };
18411 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
18412 Ok((grid, tx_type))
18413}
18414
18415/// The coded `cw x ch` corner of a transform zero-extended into its true
18416/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
18417/// corner that coded nothing stays the shared zero grid -- no allocation
18418/// (lane-coefgrid).
18419fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
18420 if (cw, ch) == (w, h) {
18421 return corner;
18422 }
18423 if let Grid::Zero(_) = corner {
18424 return Grid::Zero(w * h);
18425 }
18426 let mut full = vec![0i32; w * h];
18427 for row in 0..ch {
18428 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
18429 }
18430 Grid::Own(full)
18431}
18432
18433/// A rect coefficient grid re-laid into the square `stride x stride` grid the
18434/// neighbour/deblock stamps downstream of the residual expect.
18435fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
18436 let mut full = vec![0i32; stride * stride];
18437 for row in 0..h {
18438 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
18439 }
18440 full
18441}
18442
18443/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
18444/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
18445/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
18446/// raster order, each reading its own coefficient context off the units
18447/// already decoded before it. Returns the block's luma grid (all-zero in the
18448/// split case, whose reconstruction has already happened unit by unit) and
18449/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
18450/// which for a split block lands on the top-left unit.
18451#[allow(clippy::too_many_arguments)]
18452fn read_inter_luma8(
18453 dec: &mut SymbolDecoder,
18454 cdfs: &mut Cdfs,
18455 neighbours: &mut Neighbours,
18456 leaf_mi: (usize, usize),
18457 y: &mut PlaneBuf<'static>,
18458 px: usize,
18459 py: usize,
18460 pred_y: Pred<'_>,
18461 mode_for_tx: usize,
18462 base_q_idx: u8,
18463 scan8: &[u16],
18464 scan4: &[u16],
18465 reduced_tx_set: bool,
18466 split: bool, fctx: &crate::decode::FrameCtx,
18467) -> Result<(Grid, TxType)> {
18468 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
18469 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
18470 let split = split || lossless(fctx);
18471 if !split {
18472 return read_inter_plane(
18473 dec,
18474 cdfs,
18475 if reduced_tx_set {
18476 TxbSet::Luma8Inter
18477 } else {
18478 TxbSet::Luma8InterSet1
18479 },
18480 scan8,
18481 0,
18482 neighbours.around_mi(leaf_mi, 8)[0],
18483 mode_for_tx,
18484 y,
18485 px,
18486 py,
18487 8,
18488 base_q_idx,
18489 pred_y,
18490 None,
18491 None, fctx,
18492 );
18493 }
18494 let mut first = TxType::DctDct;
18495 for tu_row in 0..2 {
18496 for tu_col in 0..2 {
18497 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18498 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
18499 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18500 let (tu_grid, tu_tx_type) = read_inter_plane(
18501 dec,
18502 cdfs,
18503 if reduced_tx_set {
18504 TxbSet::Luma4Inter
18505 } else {
18506 TxbSet::Luma4InterSet1
18507 },
18508 scan4,
18509 0,
18510 neighbours.around_mi(tu_mi, 4)[0],
18511 mode_for_tx,
18512 y,
18513 px + tu_col * 4,
18514 py + tu_row * 4,
18515 4,
18516 base_q_idx,
18517 tu_pred,
18518 None,
18519 Some(tu_skip_ctx), fctx,
18520 )?;
18521 if tu_row == 0 && tu_col == 0 {
18522 first = tu_tx_type;
18523 }
18524 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18525 }
18526 }
18527 Ok((Grid::Zero(64), first))
18528}
18529
18530/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
18531/// coefficient tables from -- the inter counterpart of [`txbset_for`].
18532/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
18533/// an inter block's chroma transform inherits the *colocated luma* unit's
18534/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
18535/// of the extended set the CHROMA transform size selects
18536/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
18537/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
18538/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
18539/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
18540/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
18541/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
18542/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
18543/// sync and only corrupted the inverse transform (one 64x64 superblock of
18544/// high-frequency chroma noise, luma bit-exact).
18545pub(crate) fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
18546 use TxType::*;
18547 let sqr_up = w.max(h);
18548 let sqr = w.min(h);
18549 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
18550 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
18551 let allowed: &[TxType] = if sqr_up > 32 {
18552 // EXT_TX_SET_DCTONLY
18553 &[DctDct]
18554 } else if sqr_up == 32 || reduced {
18555 // EXT_TX_SET_DCT_IDTX
18556 &[DctDct, Idtx]
18557 } else if sqr == 16 {
18558 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
18559 // the four 1D ADST/FLIPADST types.
18560 &[
18561 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
18562 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
18563 ]
18564 } else {
18565 // EXT_TX_SET_ALL16
18566 return t;
18567 };
18568 if allowed.contains(&t) { t } else { DctDct }
18569}
18570
18571fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18572 match tx_px {
18573 // lane-sb128c r1: a 128x128 inter block's own luma unit
18574 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
18575 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
18576 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
18577 // coincide -- exactly the set the whole-64x64 inter block already uses.
18578 64 => TxbSet::Luma64,
18579 32 => TxbSet::Luma32Inter,
18580 16 if reduced_tx_set => TxbSet::Luma16Inter,
18581 16 => TxbSet::Luma16InterSet1,
18582 8 if reduced_tx_set => TxbSet::Luma8Inter,
18583 8 => TxbSet::Luma8InterSet1,
18584 4 if reduced_tx_set => TxbSet::Luma4Inter,
18585 4 => TxbSet::Luma4InterSet1,
18586 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
18587 }
18588}
18589
18590/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
18591/// the only four sizes a `TxMode::Select` block's coded coefficient grid
18592/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
18593fn scan_for<'a>(
18594 tx_px: usize,
18595 scan32: &'a [u16],
18596 scan16: &'a [u16],
18597 scan8: &'a [u16],
18598 scan4: &'a [u16],
18599) -> &'a [u16] {
18600 match tx_px {
18601 32 => scan32,
18602 16 => scan16,
18603 8 => scan8,
18604 4 => scan4,
18605 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
18606 }
18607}
18608
18609/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
18610/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
18611/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
18612/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
18613/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
18614/// regardless of the flag (`av1_get_ext_tx_set_type`'s
18615/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
18616/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
18617/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
18618/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
18619/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
18620/// inter `ext_tx` sets, never the mode-indexed intra ones.
18621fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18622 match tx_px {
18623 64 => TxbSet::Luma64,
18624 32 => TxbSet::Luma32Inter,
18625 16 if reduced_tx_set => TxbSet::Luma16Inter,
18626 16 => TxbSet::Luma16InterSet1,
18627 8 if reduced_tx_set => TxbSet::Luma8Inter,
18628 8 => TxbSet::Luma8InterSet1,
18629 _ => TxbSet::Luma64,
18630 }
18631}
18632
18633fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18634 match tx_px {
18635 64 => TxbSet::Luma64,
18636 32 => TxbSet::Luma32,
18637 16 => TxbSet::Luma16,
18638 8 if reduced_tx_set => TxbSet::Luma8,
18639 8 => TxbSet::Luma8Set1,
18640 4 if reduced_tx_set => TxbSet::Luma4,
18641 4 => TxbSet::Luma4Set1,
18642 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
18643 }
18644}
18645
18646/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
18647/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
18648fn unit_log2(px: u32) -> i32 {
18649 if px == 0 {
18650 0
18651 } else {
18652 px.trailing_zeros() as i32 - 2
18653 }
18654}
18655
18656/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
18657/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
18658/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
18659/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
18660/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
18661/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
18662/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
18663/// block anywhere aborted the whole stream's decode before comparison).
18664fn lf_level(
18665 lf: &LoopFilterParams,
18666 plane_idx: usize,
18667 dir: usize,
18668 ref_frame: i8,
18669 delta_lf: i32,
18670 segment_id: u8, fctx: &crate::decode::FrameCtx,
18671) -> i32 {
18672 let base = i32::from(if plane_idx == 0 {
18673 lf.level[dir]
18674 } else if plane_idx == 1 {
18675 lf.level[2]
18676 } else {
18677 lf.level[3]
18678 });
18679 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
18680 // ref/mode delta scaling below, and regardless of `delta_enabled`
18681 // (that flag only gates `ref_deltas`/`mode_deltas`).
18682 let base = (base + delta_lf).clamp(0, 63);
18683 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
18684 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
18685 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
18686 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
18687 // for chroma.
18688 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18689 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
18690 // when the frame codes no segmentation (`seg_lf_active`), which is what
18691 // spares the deblock loop two thread-local reads per 4x4 edge.
18692 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
18693 Some(data) => (base + data).clamp(0, 63),
18694 None => base,
18695 };
18696 if !lf.delta_enabled {
18697 return base;
18698 }
18699 let scale = 1i32 << (base >> 5);
18700 let is_inter = ref_frame != 0;
18701 let is_globalmv = ref_frame < 0;
18702 let ref_idx = ref_frame.unsigned_abs() as usize;
18703 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
18704 if is_inter {
18705 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
18706 }
18707 lvl.clamp(0, 63)
18708}
18709
18710thread_local! {
18711 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
18712 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
18713 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
18714 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
18715 /// build per plane and pass serves the whole frame. The pipeline builds
18716 /// an `EdgeCtx` per superblock-row band rather than per frame, which
18717 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
18718 static LVL_CACHE: std::cell::RefCell<
18719 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
18720 > = const { std::cell::RefCell::new(Vec::new()) };
18721}
18722
18723/// `lf_level` over the whole `(base level, ref frame)` domain -- see
18724/// [`LVL_CACHE`]. `lf_level`'s own first step is
18725/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
18726/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
18727fn lvl_table(
18728 lf: &LoopFilterParams,
18729 plane_idx: usize,
18730 dir: usize,
18731 base0: i32,
18732 fctx: &crate::decode::FrameCtx,
18733) -> [[u8; 15]; 64] {
18734 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18735 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
18736 if let Some(t) = LVL_CACHE.with(|c| {
18737 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
18738 }) {
18739 return t;
18740 }
18741 let mut lvl = [[0u8; 15]; 64];
18742 for (b, row) in lvl.iter_mut().enumerate() {
18743 for (r, cell) in row.iter_mut().enumerate() {
18744 *cell =
18745 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
18746 }
18747 }
18748 LVL_CACHE.with(|c| {
18749 let mut c = c.borrow_mut();
18750 if c.len() >= 8 {
18751 c.remove(0);
18752 }
18753 c.push((key, lvl));
18754 });
18755 lvl
18756}
18757
18758/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18759/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18760/// that a coded block's transform is always its own full size -- so a TU
18761/// edge is always also a PU edge, and the "both sides skipped, not a PU
18762/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18763/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18764/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18765/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
18766/// seven values that used to be re-passed per 4-pixel edge group -- half of
18767/// them on the stack, into an `inline(never)` body -- plus libaom's
18768/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
18769/// filter level for every `(base level, ref frame)` pair once per frame
18770/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
18771struct EdgeCtx<'a> {
18772 lf: &'a LoopFilterParams,
18773 n: &'a Neighbours,
18774 fctx: &'a crate::decode::FrameCtx,
18775 plane_idx: usize,
18776 dir: usize,
18777 chroma: bool,
18778 seg_lf_active: bool,
18779 /// `delta_lf_grid`'s column for this plane and direction.
18780 delta_idx: usize,
18781 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
18782 /// chroma.
18783 step: usize,
18784 /// This pass's own `lf.level[..]`, the LUT's base.
18785 base0: i32,
18786 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
18787 /// override -- the whole domain, since a level is `0..=63` and a ref
18788 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
18789 /// entries and is indexed by the ref frame's magnitude).
18790 lvl: [[u8; 15]; 64],
18791}
18792
18793impl<'a> EdgeCtx<'a> {
18794 fn new(
18795 lf: &'a LoopFilterParams,
18796 n: &'a Neighbours,
18797 plane_idx: usize,
18798 dir: usize,
18799 chroma: bool,
18800 seg_lf_active: bool,
18801 fctx: &'a crate::decode::FrameCtx,
18802 ) -> Self {
18803 let base0 = i32::from(if plane_idx == 0 {
18804 lf.level[dir]
18805 } else if plane_idx == 1 {
18806 lf.level[2]
18807 } else {
18808 lf.level[3]
18809 });
18810 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
18811 Self {
18812 lf,
18813 n,
18814 fctx,
18815 plane_idx,
18816 dir,
18817 chroma,
18818 seg_lf_active,
18819 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
18820 step: if chroma { 2 } else { 1 },
18821 base0,
18822 lvl,
18823 }
18824 }
18825
18826 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
18827 /// override it (which is every frame that codes no segmentation).
18828 #[inline(always)]
18829 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
18830 if self.seg_lf_active {
18831 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
18832 }
18833 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
18834 debug_assert!((-7..=7).contains(&ref_frame));
18835 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
18836 i32::from(self.lvl[b][r])
18837 }
18838}
18839
18840/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18841/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18842/// that a coded block's transform is always its own full size -- so a TU
18843/// edge is always also a PU edge, and the "both sides skipped, not a PU
18844/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18845/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18846/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18847#[inline(always)]
18848fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
18849 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
18850 let cur_tx = if c.dir == 0 {
18851 tx_px_at(c.n, c.chroma, mi_r, mi_c)
18852 } else {
18853 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
18854 };
18855 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
18856 // test is a mask, not the hardware `divl` this used to emit (10.7% of
18857 // `edge_params`' own samples sat on that divide's result test).
18858 //
18859 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
18860 // the covering transform does not start at), so this head is inlined
18861 // into the deblock loops and only survivors pay the call and the
18862 // register-spilling prologue of the body below.
18863 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
18864 return None;
18865 }
18866 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
18867}
18868
18869/// [`edge_params`] past its transform-alignment gate.
18870#[inline(never)]
18871fn edge_params_body(
18872 c: &EdgeCtx,
18873 x0: usize,
18874 y0: usize,
18875 mi_r: usize,
18876 mi_c: usize,
18877 cur_tx: u32,
18878) -> Option<(u8, i32)> {
18879 let n = c.n;
18880 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18881 // The previous cell must keep the odd parity `plane_to_mi` just
18882 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
18883 // not the other half of this one.
18884 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
18885 (mi_r, mi_c - c.step)
18886 } else {
18887 (mi_r - c.step, mi_c)
18888 };
18889 let pv_tx = if c.dir == 0 {
18890 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18891 } else {
18892 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18893 };
18894 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
18895 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
18896 let pv_delta_lf =
18897 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
18898
18899 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
18900 // SKIPPED INTER blocks is filtered only when it is also a prediction
18901 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
18902 // omission of this term (on the stale invariant "a coded block's transform
18903 // is always its own full size", which var-tx broke) had us filtering an
18904 // interior 8-px lattice the reference never touches: on the pinned 192x68
18905 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
18906 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
18907 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
18908 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
18909 // edge of a sub-8x8 group is a prediction edge, even though the group's
18910 // bottom/right mi does not start there. Comparing mi origins instead is
18911 // the same test only while the block's own origin is aligned to its
18912 // size, which a 4x4 luma block read at the `| 1` mi is not.
18913 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18914 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
18915 let (org_px, dim_mi) = if c.dir == 0 {
18916 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
18917 } else {
18918 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
18919 };
18920 let pu_edge = if c.chroma {
18921 let plane_dim = (dim_mi * MI / 2).max(4);
18922 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
18923 } else {
18924 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
18925 };
18926 if !pu_edge
18927 && cur_ref != 0
18928 && pv_ref != 0
18929 && n.skip_at(mi_r, mi_c)
18930 && n.skip_at(pv_mi_r, pv_mi_c)
18931 {
18932 return None;
18933 }
18934 let (cur_seg, pv_seg) = if c.seg_lf_active {
18935 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
18936 } else {
18937 (0, 0)
18938 };
18939 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
18940 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
18941 if cur_level == 0 && pv_level == 0 {
18942 return None;
18943 }
18944 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
18945 let len: u8 = if c.chroma {
18946 if dim == 0 { 4 } else { 6 }
18947 } else {
18948 [4, 8, 14, 14, 14][dim]
18949 };
18950 let level = if cur_level != 0 { cur_level } else { pv_level };
18951 hit!(DEBLOCK_HITS);
18952 Some((len, level))
18953}
18954
18955/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
18956fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
18957 let sharpness = i32::from(sharpness);
18958 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
18959 let mut lim = level >> shift;
18960 if sharpness > 0 {
18961 lim = lim.min(9 - sharpness);
18962 }
18963 lim = lim.max(1);
18964 (2 * (level + 2) + lim, lim, level >> 4)
18965}
18966
18967#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
18968fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
18969 // libaom's `signed_char_clamp_high`: the clamp range scales with
18970 // `128 << (bit_depth - 8)` alongside the centering constant below.
18971 let scale = 1i32 << (bit_depth(fctx) - 8);
18972 v.clamp(-128 * scale, 128 * scale - 1)
18973}
18974
18975fn round_pow2(v: i32, n: u32) -> i32 {
18976 (v + (1 << (n - 1))) >> n
18977}
18978
18979/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
18980/// fallback.
18981fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
18982 if !mask {
18983 return [p1, p0, q0, q1];
18984 }
18985 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
18986 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
18987 // this kernel's eight clamps, and this kernel runs per deblocked sample.
18988 // Same bound, resolved once.
18989 let scale = 1i32 << (bit_depth(fctx) - 8);
18990 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
18991 let centre = 128i32 * scale;
18992 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
18993 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
18994 let filter = sclamp(outer + 3 * (qs0 - ps0));
18995 let filter1 = sclamp(filter + 4) >> 3;
18996 let filter2 = sclamp(filter + 3) >> 3;
18997 let oq0 = sclamp(qs0 - filter1) + centre;
18998 let op0 = sclamp(ps0 + filter2) + centre;
18999 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
19000 let oq1 = sclamp(qs1 - tap) + centre;
19001 let op1 = sclamp(ps1 + tap) + centre;
19002 [op1, op0, oq0, oq1]
19003}
19004
19005/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
19006/// `filter4`'s narrow taps.
19007#[allow(clippy::too_many_arguments)]
19008fn filter6(
19009 mask: bool,
19010 thresh: i32,
19011 flat: bool,
19012 p2: i32,
19013 p1: i32,
19014 p0: i32,
19015 q0: i32,
19016 q1: i32,
19017 q2: i32, fctx: &crate::decode::FrameCtx,
19018) -> [i32; 4] {
19019 if flat && mask {
19020 [
19021 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
19022 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
19023 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
19024 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
19025 ]
19026 } else {
19027 filter4(mask, thresh, p1, p0, q0, q1, fctx)
19028 }
19029}
19030
19031/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
19032#[allow(clippy::too_many_arguments)]
19033fn filter8(
19034 mask: bool,
19035 thresh: i32,
19036 flat: bool,
19037 p3: i32,
19038 p2: i32,
19039 p1: i32,
19040 p0: i32,
19041 q0: i32,
19042 q1: i32,
19043 q2: i32,
19044 q3: i32, fctx: &crate::decode::FrameCtx,
19045) -> [i32; 6] {
19046 if flat && mask {
19047 [
19048 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
19049 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
19050 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
19051 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
19052 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
19053 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
19054 ]
19055 } else {
19056 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
19057 [p2, op1, op0, oq0, oq1, q2]
19058 }
19059}
19060
19061/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
19062/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
19063/// way -- they are only ever taps here, never written).
19064#[allow(clippy::too_many_arguments)]
19065fn filter14(
19066 mask: bool,
19067 thresh: i32,
19068 flat: bool,
19069 flat2: bool,
19070 p6: i32,
19071 p5: i32,
19072 p4: i32,
19073 p3: i32,
19074 p2: i32,
19075 p1: i32,
19076 p0: i32,
19077 q0: i32,
19078 q1: i32,
19079 q2: i32,
19080 q3: i32,
19081 q4: i32,
19082 q5: i32,
19083 q6: i32, fctx: &crate::decode::FrameCtx,
19084) -> [i32; 12] {
19085 if flat2 && flat && mask {
19086 [
19087 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
19088 round_pow2(
19089 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
19090 4,
19091 ),
19092 round_pow2(
19093 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
19094 4,
19095 ),
19096 round_pow2(
19097 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
19098 4,
19099 ),
19100 round_pow2(
19101 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
19102 4,
19103 ),
19104 round_pow2(
19105 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
19106 4,
19107 ),
19108 round_pow2(
19109 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
19110 4,
19111 ),
19112 round_pow2(
19113 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
19114 4,
19115 ),
19116 round_pow2(
19117 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
19118 4,
19119 ),
19120 round_pow2(
19121 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
19122 4,
19123 ),
19124 round_pow2(
19125 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
19126 4,
19127 ),
19128 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
19129 ]
19130 } else {
19131 let [op2, op1, op0, oq0, oq1, oq2] =
19132 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
19133 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
19134 }
19135}
19136
19137/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
19138/// the first (`q0`) sample past the edge, `outer_stride` advances to the
19139/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
19140/// the next along the edge's own filtering direction.
19141#[allow(clippy::too_many_arguments)]
19142fn filter_edge(
19143 data: &mut [u16],
19144 base: usize,
19145 outer_stride: isize,
19146 tap_stride: isize,
19147 len: u8,
19148 level: i32,
19149 sharpness: u8, fctx: &crate::decode::FrameCtx,
19150) {
19151 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19152 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
19153 // every 8-bit threshold (including the flat masks' fixed `1`) is
19154 // compared against a raw pixel difference on the stream's own bit-depth
19155 // scale, so each is shifted left by `bit_depth - 8` before use.
19156 let shift = bit_depth(fctx) - 8;
19157 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
19158 let flat_thresh = 1i32 << shift;
19159 let smax = sample_max(fctx);
19160 for i in 0..4isize {
19161 let center = (base as isize + i * outer_stride) as usize;
19162 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
19163 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
19164 match len {
19165 4 => {
19166 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
19167 let mask = (p1 - p0).abs() <= limit
19168 && (q1 - q0).abs() <= limit
19169 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19170 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
19171 data[idx(-2)] = op1.clamp(0, smax) as u16;
19172 data[idx(-1)] = op0.clamp(0, smax) as u16;
19173 data[idx(0)] = oq0.clamp(0, smax) as u16;
19174 data[idx(1)] = oq1.clamp(0, smax) as u16;
19175 }
19176 6 => {
19177 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
19178 let mask = (p2 - p1).abs() <= limit
19179 && (p1 - p0).abs() <= limit
19180 && (q1 - q0).abs() <= limit
19181 && (q2 - q1).abs() <= limit
19182 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19183 let flat = (p1 - p0).abs() <= flat_thresh
19184 && (q1 - q0).abs() <= flat_thresh
19185 && (p2 - p0).abs() <= flat_thresh
19186 && (q2 - q0).abs() <= flat_thresh;
19187 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
19188 data[idx(-2)] = op1.clamp(0, smax) as u16;
19189 data[idx(-1)] = op0.clamp(0, smax) as u16;
19190 data[idx(0)] = oq0.clamp(0, smax) as u16;
19191 data[idx(1)] = oq1.clamp(0, smax) as u16;
19192 }
19193 8 => {
19194 let (p3, p2, p1, p0, q0, q1, q2, q3) =
19195 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
19196 let mask = (p3 - p2).abs() <= limit
19197 && (p2 - p1).abs() <= limit
19198 && (p1 - p0).abs() <= limit
19199 && (q1 - q0).abs() <= limit
19200 && (q2 - q1).abs() <= limit
19201 && (q3 - q2).abs() <= limit
19202 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19203 let flat = (p1 - p0).abs() <= flat_thresh
19204 && (q1 - q0).abs() <= flat_thresh
19205 && (p2 - p0).abs() <= flat_thresh
19206 && (q2 - q0).abs() <= flat_thresh
19207 && (p3 - p0).abs() <= flat_thresh
19208 && (q3 - q0).abs() <= flat_thresh;
19209 let [op2, op1, op0, oq0, oq1, oq2] =
19210 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
19211 data[idx(-3)] = op2.clamp(0, smax) as u16;
19212 data[idx(-2)] = op1.clamp(0, smax) as u16;
19213 data[idx(-1)] = op0.clamp(0, smax) as u16;
19214 data[idx(0)] = oq0.clamp(0, smax) as u16;
19215 data[idx(1)] = oq1.clamp(0, smax) as u16;
19216 data[idx(2)] = oq2.clamp(0, smax) as u16;
19217 }
19218 _ => {
19219 let (p6, p5, p4, p3, p2, p1, p0) =
19220 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
19221 let (q0, q1, q2, q3, q4, q5, q6) =
19222 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
19223 let mask = (p3 - p2).abs() <= limit
19224 && (p2 - p1).abs() <= limit
19225 && (p1 - p0).abs() <= limit
19226 && (q1 - q0).abs() <= limit
19227 && (q2 - q1).abs() <= limit
19228 && (q3 - q2).abs() <= limit
19229 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19230 let flat = (p1 - p0).abs() <= flat_thresh
19231 && (q1 - q0).abs() <= flat_thresh
19232 && (p2 - p0).abs() <= flat_thresh
19233 && (q2 - q0).abs() <= flat_thresh
19234 && (p3 - p0).abs() <= flat_thresh
19235 && (q3 - q0).abs() <= flat_thresh;
19236 let flat2 = (p4 - p0).abs() <= flat_thresh
19237 && (q4 - q0).abs() <= flat_thresh
19238 && (p5 - p0).abs() <= flat_thresh
19239 && (q5 - q0).abs() <= flat_thresh
19240 && (p6 - p0).abs() <= flat_thresh
19241 && (q6 - q0).abs() <= flat_thresh;
19242 let out = filter14(
19243 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
19244 q6, fctx,
19245 );
19246 for (k, v) in (-6..=5isize).zip(out) {
19247 data[idx(k)] = v.clamp(0, smax) as u16;
19248 }
19249 }
19250 }
19251 }
19252}
19253
19254/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
19255/// 4K decode's self time, spent almost entirely on the per-tap strided
19256/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
19257/// arithmetic). Nothing here is spec logic: the same masks, the same
19258/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
19259/// rounding, done for 16 edge lines at once.
19260///
19261/// 16-bit lanes are exact for every value these filters see. Samples are in
19262/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
19263/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
19264/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
19265/// wide kernels' weights each total 8 or 16, so their sums (at most
19266/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
19267/// rounding shift, which is the unsigned shift the scalar's non-negative sum
19268/// takes.
19269#[cfg(target_arch = "x86_64")]
19270#[allow(unsafe_code)]
19271#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
19272mod deblock_simd {
19273 use std::arch::x86_64::*;
19274
19275 /// `a <= b` lane-wise, as a full-width mask.
19276 ///
19277 /// # Safety
19278 /// Requires AVX2.
19279 #[target_feature(enable = "avx2")]
19280 #[inline]
19281 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
19282 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
19283 }
19284
19285 /// `|a - b|` lane-wise.
19286 ///
19287 /// # Safety
19288 /// Requires AVX2.
19289 #[target_feature(enable = "avx2")]
19290 #[inline]
19291 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
19292 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
19293 }
19294
19295 /// `signed_char_clamp_high`, lane-wise.
19296 ///
19297 /// # Safety
19298 /// Requires AVX2.
19299 #[target_feature(enable = "avx2")]
19300 #[inline]
19301 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
19302 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
19303 }
19304
19305 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
19306 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
19307 ///
19308 /// # Safety
19309 /// Requires AVX2.
19310 #[target_feature(enable = "avx2")]
19311 unsafe fn transpose16(t: &mut [__m256i; 16]) {
19312 let mut a = [_mm256_setzero_si256(); 16];
19313 for k in 0..8 {
19314 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
19315 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
19316 }
19317 let mut b = [_mm256_setzero_si256(); 16];
19318 for g in 0..4 {
19319 let s = 4 * g;
19320 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
19321 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
19322 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
19323 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
19324 }
19325 let mut c = [_mm256_setzero_si256(); 16];
19326 for g in 0..2 {
19327 let s = 8 * g;
19328 for j in 0..4 {
19329 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
19330 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
19331 }
19332 }
19333 for i in 0..8 {
19334 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
19335 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
19336 }
19337 }
19338
19339 /// The wide kernels' tap weights, in tap order and with the spec's
19340 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
19341 /// over `p3..q3`, `filter14` over `p6..q6`.
19342 const W6: [[i16; 6]; 4] = [
19343 [3, 2, 2, 1, 0, 0],
19344 [1, 2, 2, 2, 1, 0],
19345 [0, 1, 2, 2, 2, 1],
19346 [0, 0, 1, 2, 2, 3],
19347 ];
19348 const W8: [[i16; 8]; 6] = [
19349 [3, 2, 1, 1, 1, 0, 0, 0],
19350 [2, 1, 2, 1, 1, 1, 0, 0],
19351 [1, 1, 1, 2, 1, 1, 1, 0],
19352 [0, 1, 1, 1, 2, 1, 1, 1],
19353 [0, 0, 1, 1, 1, 2, 1, 2],
19354 [0, 0, 0, 1, 1, 1, 2, 3],
19355 ];
19356 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
19357 const W14: [[i16; 14]; 12] = [
19358 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
19359 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
19360 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
19361 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
19362 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
19363 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
19364 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
19365 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
19366 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
19367 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
19368 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
19369 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
19370 ];
19371
19372 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
19373 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
19374 /// below `1 << 16`, so the logical shift is the arithmetic one.
19375 ///
19376 /// # Safety
19377 /// Requires AVX2.
19378 ///
19379 /// lane-deblock: the tap count, the weights and the shift are all const
19380 /// here (they were slice parameters, which left the weight `match` as a
19381 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
19382 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
19383 #[target_feature(enable = "avx2")]
19384 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
19385 unsafe fn wsum<const N: usize, const SHIFT: i32>(
19386 taps: &[__m256i; N],
19387 w: &[i16; N],
19388 ) -> __m256i {
19389 let mut s = _mm256_setzero_si256();
19390 for i in 0..N {
19391 match w[i] {
19392 0 => {}
19393 1 => s = _mm256_add_epi16(s, taps[i]),
19394 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
19395 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
19396 }
19397 }
19398 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
19399 if SHIFT == 3 {
19400 _mm256_srli_epi16(s, 3)
19401 } else {
19402 _mm256_srli_epi16(s, 4)
19403 }
19404 }
19405
19406 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
19407 /// `t[8]`; the filtered taps are written back in place. Returns `false`
19408 /// when the filter mask is empty on every one of the 16 lines -- nothing
19409 /// was written and the caller can skip the whole write-back.
19410 ///
19411 /// # Safety
19412 /// Requires AVX2.
19413 ///
19414 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
19415 /// its own kernel holding only its own taps, and every wide row is
19416 /// clamped straight into `t` instead of into a shared twelve-entry
19417 /// result array (which the register allocator spilled -- 35% of this
19418 /// kernel's samples were `vmovdqa` to the stack).
19419 #[target_feature(enable = "avx2")]
19420 #[allow(clippy::too_many_arguments)]
19421 unsafe fn filter16<const LEN: u8>(
19422 t: &mut [__m256i; 16],
19423 blimit: i32,
19424 limit: i32,
19425 hev_thr: i32,
19426 flat_thresh: i32,
19427 scale: i32,
19428 smax: i32,
19429 ) -> bool {
19430 let lim = _mm256_set1_epi16(limit as i16);
19431 let blim = _mm256_set1_epi16(blimit as i16);
19432 let hthr = _mm256_set1_epi16(hev_thr as i16);
19433 let fthr = _mm256_set1_epi16(flat_thresh as i16);
19434 let zero = _mm256_setzero_si256();
19435 let smaxv = _mm256_set1_epi16(smax as i16);
19436 macro_rules! put {
19437 ($i:expr, $v:expr) => {
19438 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
19439 };
19440 }
19441 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
19442 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
19443
19444 // `highbd_filter_mask`: the neighbour steps this kernel's length
19445 // reaches, plus the shared `blimit` term.
19446 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
19447 let mut md = d1;
19448 if LEN >= 6 {
19449 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
19450 }
19451 if LEN >= 8 {
19452 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
19453 }
19454 let bl = _mm256_add_epi16(
19455 _mm256_slli_epi16(ad(p0, q0), 1),
19456 _mm256_srli_epi16(ad(p1, q1), 1),
19457 );
19458 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
19459 // lane-deblock2: an empty mask leaves every tap at its loaded value
19460 // (the flat masks are `& mask`, so they are empty too, and the final
19461 // clamp is the identity on samples that came out of the plane), so
19462 // the whole write-back -- including the vertical edge's second
19463 // transpose -- is dead.
19464 if _mm256_testz_si256(mask, mask) != 0 {
19465 return false;
19466 }
19467 let hev = _mm256_cmpgt_epi16(d1, hthr);
19468
19469 // `filter4`, in the centred domain.
19470 let centre = _mm256_set1_epi16((128 * scale) as i16);
19471 let lo = _mm256_set1_epi16((-128 * scale) as i16);
19472 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
19473 let ps1 = _mm256_sub_epi16(p1, centre);
19474 let ps0 = _mm256_sub_epi16(p0, centre);
19475 let qs0 = _mm256_sub_epi16(q0, centre);
19476 let qs1 = _mm256_sub_epi16(q1, centre);
19477 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
19478 let f = sclamp(
19479 _mm256_add_epi16(
19480 outer,
19481 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
19482 ),
19483 lo,
19484 hi,
19485 );
19486 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
19487 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
19488 let tap = _mm256_andnot_si256(
19489 hev,
19490 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
19491 );
19492 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
19493 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
19494 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
19495 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
19496 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
19497 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
19498 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
19499 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
19500 if LEN == 4 {
19501 put!(6, b_p1);
19502 put!(7, b_p0);
19503 put!(8, b_q0);
19504 put!(9, b_q1);
19505 return true;
19506 }
19507
19508 // `highbd_flat_mask4`, over the same reach as this length's mask.
19509 let mut fl = _mm256_max_epi16(
19510 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
19511 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
19512 );
19513 if LEN >= 8 {
19514 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
19515 }
19516 let flat = _mm256_and_si256(le(fl, fthr), mask);
19517 let any_flat = _mm256_testz_si256(flat, flat) == 0;
19518 if LEN == 6 {
19519 if any_flat {
19520 let taps = [p2, p1, p0, q0, q1, q2];
19521 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
19522 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
19523 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
19524 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
19525 } else {
19526 put!(6, b_p1);
19527 put!(7, b_p0);
19528 put!(8, b_q0);
19529 put!(9, b_q1);
19530 }
19531 return true;
19532 }
19533
19534 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
19535 let (o0, o1, o2, o3, o4, o5) = if any_flat {
19536 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
19537 (
19538 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
19539 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
19540 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
19541 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
19542 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
19543 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
19544 )
19545 } else {
19546 (p2, b_p1, b_p0, b_q0, b_q1, q2)
19547 };
19548 macro_rules! put8 {
19549 () => {
19550 put!(5, o0);
19551 put!(6, o1);
19552 put!(7, o2);
19553 put!(8, o3);
19554 put!(9, o4);
19555 put!(10, o5);
19556 };
19557 }
19558 if LEN == 8 {
19559 put8!();
19560 return true;
19561 }
19562
19563 let fl2 = _mm256_max_epi16(
19564 _mm256_max_epi16(
19565 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
19566 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
19567 ),
19568 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
19569 );
19570 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
19571 if _mm256_testz_si256(flat2, flat2) != 0 {
19572 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
19573 // taps they were loaded with, exactly as the blend would.
19574 put8!();
19575 return true;
19576 }
19577 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
19578 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
19579 // j is a constant vector with two negative and two positive
19580 // entries), so each output costs one add, one sub and the rounding
19581 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
19582 // become 44. Exact: every partial sum is taken mod 2^16 by
19583 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
19584 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
19585 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
19586 // it against `filter_edge` at 8/10/12-bit.
19587 let mut s = _mm256_add_epi16(
19588 _mm256_add_epi16(
19589 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
19590 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
19591 ),
19592 _mm256_add_epi16(
19593 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
19594 q0,
19595 ),
19596 );
19597 let add2 = |a, b| _mm256_add_epi16(a, b);
19598 macro_rules! row14 {
19599 ($idx:literal, $base:expr) => {
19600 put!(
19601 $idx,
19602 _mm256_blendv_epi8(
19603 $base,
19604 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
19605 flat2,
19606 )
19607 );
19608 };
19609 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
19610 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
19611 row14!($idx, $base);
19612 };
19613 }
19614 row14!(2, p5);
19615 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
19616 row14!(4, p3, add2(p2, q2), add2(p6, p5));
19617 row14!(5, o0, add2(p1, q3), add2(p6, p4));
19618 row14!(6, o1, add2(p0, q4), add2(p6, p3));
19619 row14!(7, o2, add2(q0, q5), add2(p6, p2));
19620 row14!(8, o3, add2(q1, q6), add2(p6, p1));
19621 row14!(9, o4, add2(q2, q6), add2(p5, p0));
19622 row14!(10, o5, add2(q3, q6), add2(p4, q0));
19623 row14!(11, q3, add2(q4, q6), add2(p3, q1));
19624 row14!(12, q4, add2(q5, q6), add2(p2, q2));
19625 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
19626 true
19627 }
19628
19629 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
19630 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
19631 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
19632 /// consecutive columns with each tap a whole row segment.
19633 ///
19634 /// # Safety
19635 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
19636 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
19637 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
19638 /// must be inside it.
19639 #[target_feature(enable = "avx2")]
19640 #[allow(clippy::too_many_arguments)]
19641 pub unsafe fn edge16(
19642 data: &mut [u16],
19643 base: usize,
19644 stride: usize,
19645 vertical: bool,
19646 len: u8,
19647 blimit: i32,
19648 limit: i32,
19649 hev_thr: i32,
19650 flat_thresh: i32,
19651 scale: i32,
19652 smax: i32,
19653 ) {
19654 let p = data.as_mut_ptr();
19655 let mut t = [_mm256_setzero_si256(); 16];
19656 // The taps this length reads, as `t` indices.
19657 let (lo, hi) = match len {
19658 4 => (6, 10),
19659 6 => (5, 11),
19660 8 => (4, 12),
19661 _ => (1, 15),
19662 };
19663 if vertical {
19664 for j in 0..16 {
19665 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
19666 }
19667 transpose16(&mut t);
19668 } else {
19669 let top = base - 8 * stride;
19670 for i in lo..hi {
19671 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
19672 }
19673 }
19674 // lane-deblock2: one monomorphised kernel per edge length, and an
19675 // empty filter mask returns without any write-back at all.
19676 let modified = match len {
19677 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19678 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19679 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19680 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19681 };
19682 if !modified {
19683 return;
19684 }
19685 if vertical {
19686 transpose16(&mut t);
19687 for j in 0..16 {
19688 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
19689 }
19690 } else {
19691 let top = base - 8 * stride;
19692 let (a, b) = match len {
19693 4 | 6 => (6, 10),
19694 8 => (5, 11),
19695 _ => (2, 14),
19696 };
19697 for i in a..b {
19698 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
19699 }
19700 }
19701 }
19702}
19703
19704/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
19705/// output. Returns `false` when this build or CPU has no kernel, leaving the
19706/// caller on the scalar path.
19707#[allow(unused_variables)]
19708fn filter_edge16(
19709 data: &mut [u16],
19710 base: usize,
19711 stride: usize,
19712 vertical: bool,
19713 len: u8,
19714 level: i32,
19715 sharpness: u8, fctx: &crate::decode::FrameCtx,
19716) -> bool {
19717 #[cfg(target_arch = "x86_64")]
19718 {
19719 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
19720 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19721 let shift = bit_depth(fctx) - 8;
19722 // SAFETY: the avx2 arm is reached only when the CPU reports it,
19723 // and `deblock_plane` checks the kernel's edge bounds.
19724 #[allow(unsafe_code)]
19725 unsafe {
19726 deblock_simd::edge16(
19727 data,
19728 base,
19729 stride,
19730 vertical,
19731 len,
19732 blimit << shift,
19733 limit << shift,
19734 hev_thr << shift,
19735 1 << shift,
19736 1 << shift,
19737 sample_max(fctx),
19738 )
19739 };
19740 return true;
19741 }
19742 }
19743 false
19744}
19745
19746/// One plane's worth of spec 7.14: every vertical edge across the plane,
19747/// then every horizontal edge (the order the spec and libaom both use).
19748fn deblock_plane(
19749 plane: &mut PlaneBuf<'static>,
19750 plane_idx: usize,
19751 lf: &LoopFilterParams,
19752 n: &Neighbours,
19753 frame_width: usize,
19754 frame_height: usize, fctx: &crate::decode::FrameCtx,
19755) {
19756 // spec 7.14's order: this plane's whole vertical pass, then its whole
19757 // horizontal one. lane-pipefilt split the two into one row-ranged
19758 // function so the per-superblock-row pipeline can run them a band at a
19759 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
19760 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
19761 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
19762}
19763
19764/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
19765/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
19766///
19767/// A row span is a legal cut of either pass because a band boundary is a
19768/// multiple of 16 rows and every edge's kernel stays inside its own
19769/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
19770/// what keep the two passes in spec order across bands.
19771#[allow(clippy::too_many_arguments)]
19772fn deblock_plane_span(
19773 plane: &mut PlaneBuf<'static>,
19774 plane_idx: usize,
19775 lf: &LoopFilterParams,
19776 n: &Neighbours,
19777 frame_width: usize,
19778 frame_height: usize,
19779 span_lo: usize,
19780 span_hi: usize,
19781 horz: bool,
19782 fctx: &crate::decode::FrameCtx,
19783) {
19784 let chroma = plane_idx != 0;
19785 // r7: libaom clips the deblock loop to the CODED frame's own
19786 // width/height, not the mi-aligned `true_width`/`true_height` margin
19787 // (the padding up to the next 8-pixel/superblock boundary that
19788 // reconstruction still fills in but the loop filter never visits).
19789 // Confirmed against the superres gate: with the margin included, the
19790 // last coded mi column's horizontal edges were filtered when libaom's
19791 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
19792 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
19793 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
19794 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
19795 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
19796 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
19797 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
19798 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
19799 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
19800 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
19801 // all in columns 64..67; frame 0 survived because that edge carried no
19802 // filter level there). r7's superres measurement is preserved: its frame
19803 // was already 8-aligned, so this bound equals `frame_width` there and
19804 // still excludes the superblock padding up to `true_width`.
19805 let (cw, ch) = if chroma {
19806 (frame_width.div_ceil(2), frame_height.div_ceil(2))
19807 } else {
19808 (frame_width, frame_height)
19809 };
19810 let (tw, th, stride) = (
19811 plane.true_width.min(cw),
19812 plane.true_height.min(ch),
19813 plane.width,
19814 );
19815 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
19816 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
19817 }
19818 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
19819 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
19820 // kernel. The swap is order-preserving: a filtered group overlaps only
19821 // groups along the edge it sits on -- the vertical pass's writes at
19822 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
19823 // dependence is on ascending `x0` within a row, which stays the outer
19824 // loop's order, and rows remain independent (horizontal pass mirrored).
19825 let rows = plane.data.len() / stride.max(1);
19826 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
19827 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
19828 // bands along the axis whose writes are disjoint. A vertical edge's
19829 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
19830 // row bands never touch each other; a horizontal edge's groups write rows
19831 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
19832 // read the mode-info grids immutably. The grouping a band starts with is
19833 // free: every 4-row (4-column) group's output is a pure function of that
19834 // group, whether it goes through `filter_edge16` with three neighbours or
19835 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
19836 // group ever straddles one.
19837 // lane-perf10 merge: the output plane is owned (perf10 made mutable
19838 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
19839 // the bands below never clone it concurrently.
19840 plane.data.to_mut();
19841 let threads = crate::par::filter_threads();
19842 let sp = crate::par::Shared::new(plane);
19843 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
19844 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
19845 Vec::new()
19846 } else {
19847 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
19848 .into_iter()
19849 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
19850 .collect()
19851 };
19852 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
19853 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
19854 // no other band touches (see `Shared`'s own corner-cut note).
19855 #[allow(unsafe_code)]
19856 let plane = unsafe { sp.get() };
19857 // lane-deblock2: this band's own level table and pass constants,
19858 // built once per band instead of re-derived per 4-pixel edge.
19859 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
19860 let mut x0 = 4usize;
19861 while x0 < tw {
19862 let mut y0 = y_lo;
19863 while y0 < y_hi {
19864 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
19865 let ps: [Option<(u8, i32)>; 4] =
19866 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
19867 if let Some((len, level)) = ps[0] {
19868 if ps.iter().all(|p| *p == ps[0])
19869 && filter_edge16(
19870 plane.data.to_mut(),
19871 y0 * stride + x0,
19872 stride,
19873 true,
19874 len,
19875 level,
19876 lf.sharpness, fctx,
19877 )
19878 {
19879 y0 += 16;
19880 continue;
19881 }
19882 }
19883 for (k, p) in ps.iter().enumerate() {
19884 if let Some((len, level)) = *p {
19885 filter_edge(
19886 plane.data.to_mut(),
19887 (y0 + 4 * k) * stride + x0,
19888 stride as isize,
19889 1,
19890 len,
19891 level,
19892 lf.sharpness, fctx,
19893 );
19894 }
19895 }
19896 y0 += 16;
19897 continue;
19898 }
19899 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
19900 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
19901 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
19902 }
19903 filter_edge(
19904 plane.data.to_mut(),
19905 y0 * stride + x0,
19906 stride as isize,
19907 1,
19908 len,
19909 level,
19910 lf.sharpness, fctx,
19911 );
19912 }
19913 y0 += 4;
19914 }
19915 x0 += 4;
19916 }
19917 });
19918 // The horizontal pass runs only after the WHOLE vertical pass of this
19919 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
19920 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
19921 Vec::new()
19922 } else {
19923 crate::par::bands(tw.div_ceil(16), threads)
19924 .into_iter()
19925 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19926 .collect()
19927 };
19928 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
19929 // SAFETY: this band writes only columns `x_lo..x_hi`.
19930 #[allow(unsafe_code)]
19931 let plane = unsafe { sp.get() };
19932 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
19933 let mut y0 = sp_lo.max(4);
19934 while y0 < sp_hi {
19935 let mut x0 = x_lo;
19936 while x0 < x_hi {
19937 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
19938 let ps: [Option<(u8, i32)>; 4] =
19939 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
19940 if let Some((len, level)) = ps[0] {
19941 if ps.iter().all(|p| *p == ps[0])
19942 && filter_edge16(
19943 plane.data.to_mut(),
19944 y0 * stride + x0,
19945 stride,
19946 false,
19947 len,
19948 level,
19949 lf.sharpness, fctx,
19950 )
19951 {
19952 x0 += 16;
19953 continue;
19954 }
19955 }
19956 for (k, p) in ps.iter().enumerate() {
19957 if let Some((len, level)) = *p {
19958 filter_edge(
19959 plane.data.to_mut(),
19960 y0 * stride + x0 + 4 * k,
19961 1,
19962 stride as isize,
19963 len,
19964 level,
19965 lf.sharpness, fctx,
19966 );
19967 }
19968 }
19969 x0 += 16;
19970 continue;
19971 }
19972 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
19973 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
19974 && plane_idx == 0
19975 && x0 == 44
19976 {
19977 eprintln!(
19978 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
19979 lf.sharpness
19980 );
19981 }
19982 filter_edge(
19983 plane.data.to_mut(),
19984 y0 * stride + x0,
19985 1,
19986 stride as isize,
19987 len,
19988 level,
19989 lf.sharpness, fctx,
19990 );
19991 }
19992 x0 += 4;
19993 }
19994 y0 += 4;
19995 } });
19996}
19997
19998/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
19999/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
20000/// restoration is active, and a fresh LR destination per plane -- freshly
20001/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
20002/// sample written also takes a first-touch page fault. The buffers are handed
20003/// back here instead and refilled in place.
20004///
20005/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
20006/// stay on one thread: the frame thread allocates the snapshots and a filter
20007/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
20008/// into the pool from whichever worker ran it), so a per-thread pool leaked
20009/// whole-plane buffers into every worker it touched -- 19 MB a set, times
20010/// every pool thread the decode ever created. One shared pool with a hard
20011/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
20012/// many threads cycle through it; anything over the cap is freed.
20013static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
20014
20015/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
20016/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
20017/// flight cycle through far fewer.
20018const SCRATCH_CAP: usize = 32;
20019
20020/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
20021/// CAPACITY so a chroma-sized request does not permanently promote a
20022/// luma-sized allocation (every pooled buffer would drift to the largest
20023/// size otherwise). `None` when the pool is empty.
20024fn scratch_take(n: usize) -> Option<Vec<u16>> {
20025 let mut p = PLANE_SCRATCH.lock().unwrap();
20026 if p.is_empty() {
20027 return None;
20028 }
20029 let fit = p
20030 .iter()
20031 .enumerate()
20032 .filter(|(_, v)| v.capacity() >= n)
20033 .min_by_key(|(_, v)| v.capacity())
20034 .map(|(i, _)| i);
20035 let i = match fit {
20036 Some(i) => i,
20037 // Nothing big enough: grow the largest rather than a small one.
20038 None => p
20039 .iter()
20040 .enumerate()
20041 .max_by_key(|(_, v)| v.capacity())
20042 .map(|(i, _)| i)
20043 .expect("the pool is not empty"),
20044 };
20045 Some(p.swap_remove(i))
20046}
20047
20048/// A pooled buffer holding a copy of `src`.
20049fn scratch_from(src: &[u16]) -> Vec<u16> {
20050 let mut v = scratch_take(src.len()).unwrap_or_default();
20051 v.clear();
20052 v.extend_from_slice(src);
20053 v
20054}
20055
20056/// An empty pooled buffer, for a caller that fills it itself.
20057fn scratch_empty() -> Vec<u16> {
20058 let mut v = scratch_take(0).unwrap_or_default();
20059 v.clear();
20060 v
20061}
20062
20063/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
20064/// for a caller that writes every element it later reads (lane-copy: the
20065/// post-deblock snapshot writes 4 rows in 64 and reads no other).
20066fn scratch_sized(n: usize) -> Vec<u16> {
20067 let mut v = scratch_take(n).unwrap_or_default();
20068 if v.len() > n {
20069 v.truncate(n);
20070 } else if v.len() < n {
20071 v.resize(n, 0);
20072 }
20073 v
20074}
20075
20076/// A plane's post-deblock snapshot, its samples taken from the pool (every
20077/// other field is `usize`).
20078///
20079/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
20080/// boundary substitution reads the post-deblock plane at just four rows
20081/// around each interior stripe boundary (`row` outside
20082/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
20083/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
20084/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
20085/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
20086/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
20087/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
20088/// the pooled buffer keeps whatever a previous frame left there -- an
20089/// initialised value that no reader ever reaches.
20090fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
20091 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
20092}
20093
20094fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
20095 let mut data = scratch_sized(p.data.len());
20096 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
20097 let stripe_h = 64usize >> ss_y;
20098 let offset = 8usize >> ss_y;
20099 let mut b = stripe_h - offset;
20100 while b < rows {
20101 let (lo, hi) = (b - 2, (b + 2).min(rows));
20102 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
20103 b += stripe_h;
20104 }
20105 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
20106}
20107
20108/// The pre-filter reconstruction of one coded frame, plus the per-block state
20109/// the loop filters read.
20110///
20111/// The encoder's filter search ([`crate::filter_search::pick_filters`])
20112/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
20113/// sets to score each one, and the entropy decode and reconstruction it
20114/// repeats are identical every time -- both filters run after it, on the
20115/// finished planes. That re-parse was 24% of the encoder's profile. A caller
20116/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
20117/// alone through [`replay_filters`]; the result is the same picture the full
20118/// decode would have returned, because it is the same two calls on a copy of
20119/// the same planes.
20120pub(crate) struct FilterReplay {
20121 y: PlaneBuf<'static>,
20122 u: PlaneBuf<'static>,
20123 v: PlaneBuf<'static>,
20124 neighbours: Neighbours,
20125 frame_width: usize,
20126 frame_height: usize,
20127 width: usize,
20128 height: usize,
20129 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
20130 /// stash the cropped return path leaves behind.
20131 true_width: usize,
20132 true_height: usize,
20133 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
20134 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
20135 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
20136 /// 1080p frame's wall in allocation, not in filtering. Recycled here
20137 /// instead; the pool holds at most the six planes one candidate has live.
20138 scratch: Vec<Vec<u16>>,
20139 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
20140 /// post-deblock rows loop restoration substitutes at its stripe
20141 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
20142 /// rows) -- what [`replay_restoration`] filters, instead of decoding
20143 /// the re-coded tile a second time.
20144 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
20145 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
20146 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
20147 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
20148 /// no deblocking level, so every candidate of it used to copy the three
20149 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
20150 /// destinations are kept and only the units the last candidate touched
20151 /// are restored -- the same bytes, since a unit nobody wrote still holds
20152 /// the deblocked sample it was copied from.
20153 work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20154 wrote: Vec<u8>,
20155 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
20156 /// new candidate can only write MORE units than the old one needs no
20157 /// restore at all, since every unit CDEF writes it writes from the
20158 /// post-deblock source alone.
20159 work_cdef: Option<CdefParams>,
20160 /// The last deblocked planes and the levels that produced them.
20161 /// Deblocking depends on nothing else the search moves, and the search
20162 /// fixes the levels before it walks the CDEF strengths, so every
20163 /// candidate after the first of a level pair replays CDEF alone.
20164 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20165}
20166
20167thread_local! {
20168 /// Set by [`arm_filter_replay`] for the span of one decode.
20169 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20170 /// What that decode captured, until [`clear_filter_replay`].
20171 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
20172 const { std::cell::RefCell::new(None) };
20173}
20174
20175/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
20176pub(crate) fn arm_filter_replay() {
20177 REPLAY_ARMED.set(true);
20178}
20179
20180/// Test-only: force every filter candidate through a full decode, so a gate
20181/// can hold the replay against the decode it stands in for
20182/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
20183#[cfg(test)]
20184static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
20185
20186#[cfg(test)]
20187pub(crate) fn set_filter_replay_disabled(off: bool) {
20188 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
20189}
20190
20191// Test-only: run the capture decode `replay_final` replaced as well, and
20192// hold its picture and its `FilterStages` against the replay's
20193// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
20194// Thread-local, not a global: the filter stage runs on the frame thread the
20195// test itself drives, and a process-wide flag would put every test encoding
20196// in parallel with this one through the extra decode too.
20197#[cfg(test)]
20198thread_local! {
20199 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20200}
20201
20202#[cfg(test)]
20203pub(crate) fn set_verify_final_replay(on: bool) {
20204 VERIFY_FINAL.set(on);
20205}
20206
20207#[cfg(test)]
20208pub(crate) fn verify_final_replay() -> bool {
20209 VERIFY_FINAL.get()
20210}
20211
20212/// Drop the armed flag and anything captured: the tile it belongs to is done.
20213pub(crate) fn clear_filter_replay() {
20214 REPLAY_ARMED.set(false);
20215 REPLAY.with_borrow_mut(|r| *r = None);
20216}
20217
20218/// The capture itself, called from the decoder's own pre-filter point. Owns
20219/// copies of the planes, since the caller filters them in place.
20220fn capture_filter_replay(
20221 y: &PlaneBuf<'_>,
20222 u: &PlaneBuf<'_>,
20223 v: &PlaneBuf<'_>,
20224 neighbours: &Neighbours,
20225 frame_width: usize,
20226 frame_height: usize,
20227 width: usize,
20228 height: usize,
20229 true_width: usize,
20230 true_height: usize,
20231) {
20232 if !REPLAY_ARMED.replace(false) {
20233 return;
20234 }
20235 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
20236 REPLAY.with_borrow_mut(|slot| {
20237 *slot = Some(FilterReplay {
20238 y: own(y),
20239 u: own(u),
20240 v: own(v),
20241 neighbours: neighbours.clone(),
20242 frame_width,
20243 frame_height,
20244 width,
20245 height,
20246 true_width,
20247 true_height,
20248 scratch: Vec::new(),
20249 work: None,
20250 wrote: Vec::new(),
20251 work_cdef: None,
20252 final_luma: None,
20253 deblocked: None,
20254 });
20255 });
20256}
20257
20258/// Restores, from the post-deblock cache, every sample the previous CDEF
20259/// candidate may have written: for each unit row, the column span between
20260/// its first and last written unit (a superset of the written units, which
20261/// is what makes the copy contiguous -- and never more than the whole-plane
20262/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
20263/// 4 for 4:2:0 chroma.
20264fn restore_written(
20265 dst: &mut PlaneBuf<'static>,
20266 src: &PlaneBuf<'_>,
20267 wrote: &[u8],
20268 mask: u8,
20269 unit_cols: usize,
20270 unit: usize,
20271) {
20272 let w = dst.width;
20273 if w == 0 || unit_cols == 0 || wrote.is_empty() {
20274 return;
20275 }
20276 let rows = dst.data.len() / w;
20277 let s: &[u16] = &src.data;
20278 let d = dst.data.to_mut();
20279 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
20280 for (i, row) in wr.chunks(unit_cols).enumerate() {
20281 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
20282 continue;
20283 };
20284 let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
20285 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
20286 let ur = ur0 + i;
20287 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
20288 for r in y0..y1 {
20289 let off = (r - ur0 * unit) * w;
20290 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
20291 }
20292 }
20293 };
20294 let urows = wrote.len() / unit_cols;
20295 let threads = crate::par::filter_threads().min(urows.max(1));
20296 if threads <= 1 {
20297 band(d, wrote, 0);
20298 return;
20299 }
20300 let per = urows.div_ceil(threads);
20301 let batch = crate::par::Batch::new("ec-av1-filter");
20302 for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
20303 {
20304 let band = &band;
20305 batch.submit(move || band(dc, wr, i * per));
20306 }
20307}
20308
20309/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
20310/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
20311/// allocator and the page fault handler out of the filter search.
20312fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
20313 let mut buf = scratch.pop().unwrap_or_default();
20314 let src: &[u16] = &p.data;
20315 let threads = crate::par::filter_threads();
20316 if buf.len() != src.len() || threads <= 1 {
20317 buf.clear();
20318 buf.extend_from_slice(src);
20319 } else {
20320 // A recycled buffer is already the right length, so the copy is a
20321 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
20322 // candidate is memory bandwidth, not arithmetic, and the halves are
20323 // disjoint `&mut` slices (no `par::Shared` needed).
20324 let per = src.len().div_ceil(threads);
20325 let batch = crate::par::Batch::new("ec-av1-filter");
20326 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
20327 batch.submit(move || dst.copy_from_slice(src));
20328 }
20329 }
20330 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
20331}
20332
20333/// The filter half of a captured decode, under new parameters: exactly the
20334/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
20335/// copy of the captured planes. `None` when nothing is captured (the caller
20336/// then decodes for real).
20337pub(crate) fn replay_filters(
20338 loop_filter: &LoopFilterParams,
20339 cdef: &CdefParams,
20340 fctx: &FrameCtx,
20341) -> Option<Picture> {
20342 #[cfg(test)]
20343 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20344 return None;
20345 }
20346 replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture)
20347}
20348
20349/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters,
20350/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage
20351/// used to reach this picture by decoding that re-coded tile a second time
20352/// (10% of a 4K frame's encode), only because the loop-restoration search
20353/// needs the decoder's own post-CDEF plane
20354/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls
20355/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter
20356/// planes in the same order, so it is the same bytes -- pinned by
20357/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which
20358/// runs the decode as well and holds picture and stages against it.
20359///
20360/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that
20361/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF
20362/// snapshot and handed the post-CDEF plane over for both stages.
20363pub(crate) fn replay_final(
20364 loop_filter: &LoopFilterParams,
20365 cdef: &CdefParams,
20366 idx_grid: &[u8],
20367 want_stages: bool,
20368 fctx: &FrameCtx,
20369) -> Option<(Picture, Option<FilterStages>)> {
20370 #[cfg(test)]
20371 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20372 return None;
20373 }
20374 replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx)
20375}
20376
20377fn replay_inner(
20378 loop_filter: &LoopFilterParams,
20379 cdef: &CdefParams,
20380 // `Some((cdef_idx grid, capture the filter stages))` for the final
20381 // replay; `None` for a scoring candidate, which always codes `bits == 0`.
20382 final_pass: Option<(&[u8], bool)>,
20383 fctx: &FrameCtx,
20384) -> Option<(Picture, Option<FilterStages>)> {
20385 REPLAY.with_borrow_mut(|slot| {
20386 let r = slot.as_mut()?;
20387 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
20388 // Set when the working planes ARE the deblocked planes (see below):
20389 // they go into the cache at the end, and the picture is cropped out
20390 // of them rather than taking their buffers.
20391 let mut share = false;
20392 let cpt = crate::par::timer(crate::par::S_COPY);
20393 let unit_cols = r.neighbours.mi_cols.div_ceil(2);
20394 let unit_rows = r.neighbours.mi_rows.div_ceil(2);
20395 let (mut y, mut u, mut v) = if hit {
20396 let work = r.work.take();
20397 let wrote = std::mem::take(&mut r.wrote);
20398 // `cdef_adjust_strength` is monotone in the strength it is given,
20399 // so a candidate whose primary strength is no lower and whose
20400 // secondary is zero only if the last one's was writes every unit
20401 // the last one wrote -- and writes it from the same post-deblock
20402 // source, so the samples under it need not be put back first.
20403 // Only while both candidates carry ONE strength pair (`bits ==
20404 // 0`, every scoring candidate) and read the same `cdef_idx` grid.
20405 let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
20406 let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
20407 (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
20408 superset(
20409 (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
20410 (old.y_pri_strength[0], old.y_sec_strength[0]),
20411 ),
20412 superset(
20413 (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
20414 (old.uv_pri_strength[0], old.uv_sec_strength[0]),
20415 ),
20416 ),
20417 _ => (false, false),
20418 };
20419 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
20420 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
20421 match work {
20422 Some((mut wy, mut wu, mut wv)) => {
20423 if !skip_y {
20424 restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
20425 }
20426 if !skip_uv {
20427 restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
20428 restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
20429 }
20430 (wy, wu, wv)
20431 }
20432 None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
20433 }
20434 } else {
20435 // The levels moved, so the cached deblocked planes are dead:
20436 // their buffers are this candidate's working copies.
20437 for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
20438 r.scratch.push(plane.data.into_owned());
20439 }
20440 r.work_cdef = None;
20441 if let Some((_, dy, du, dv)) = r.deblocked.take() {
20442 r.scratch.push(dy.data.into_owned());
20443 r.scratch.push(du.data.into_owned());
20444 r.scratch.push(dv.data.into_owned());
20445 }
20446 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
20447 let (mut y, mut u, mut v) =
20448 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
20449 let _t = crate::par::timer(crate::par::S_DEBLOCK);
20450 apply_deblock(
20451 &mut y,
20452 &mut u,
20453 &mut v,
20454 loop_filter,
20455 &r.neighbours,
20456 r.frame_width,
20457 r.frame_height,
20458 fctx,
20459 );
20460 // lane-av1cap2: an all-zero-strength CDEF writes no sample at
20461 // all ([`cdef_all_zero`]'s own early return), so THESE planes
20462 // are already this candidate's output -- they become the
20463 // deblock cache at the end instead of being copied into it
20464 // here, which is three ~6 MB copies less per candidate that
20465 // moves the levels (the whole deblocking half of the search:
20466 // its CDEF strengths are still (0,0)).
20467 share = cdef_all_zero(cdef);
20468 if !share {
20469 let scratch = &mut r.scratch;
20470 r.deblocked = Some((
20471 *loop_filter,
20472 pooled(&y, scratch),
20473 pooled(&u, scratch),
20474 pooled(&v, scratch),
20475 ));
20476 }
20477 (y, u, v)
20478 };
20479 drop(cpt);
20480 // The winner's `cdef_idx` literals live in the re-coded tile, which
20481 // nothing parses on this path -- hand the grid the encoder already
20482 // chose straight to the filter (`bits == 0` leaves the grid the last
20483 // parse sized, which is what every scoring candidate reads).
20484 if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) {
20485 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
20486 }
20487 let ct = crate::par::timer(crate::par::S_CDEF);
20488 let mut wrote = std::mem::take(&mut r.wrote);
20489 wrote.clear();
20490 wrote.resize(unit_cols * unit_rows, 0);
20491 r.work_cdef = Some(*cdef);
20492 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
20493 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
20494 });
20495 apply_cdef(
20496 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
20497 pre,
20498 Some(&mut wrote),
20499 );
20500 drop(ct);
20501 if final_pass.is_some_and(|(_, want)| want) {
20502 // The loop-restoration search runs on the stages above (where
20503 // post-CDEF stands in for post-deblock, as the capture decode
20504 // had it); the FILTER this frame ends up applying reads the
20505 // real post-deblock rows, which is what the decoder does.
20506 let snapshot = if share {
20507 // Nothing filtered these planes after the deblock, so they
20508 // are the post-deblock picture themselves.
20509 Some(plane_snapshot(&y, 0))
20510 } else {
20511 r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0))
20512 };
20513 let scratch = &mut r.scratch;
20514 r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d));
20515 }
20516 let stages = final_pass.and_then(|(_, want)| {
20517 want.then(|| FilterStages {
20518 deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20519 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20520 stride: [y.width, u.width, v.width],
20521 })
20522 });
20523 // The capture only happens on the shape whose tail is the two
20524 // filter calls and the crop (no superres, no loop restoration), so
20525 // what is left is that crop -- byte for byte the cropped return path
20526 // of the decode this replaces, wide-margin stash included.
20527 //
20528 // lane-av1fpar: the crop is why this arm exists at all. The capture
20529 // used to demand `frame == plane` dimensions, which no editor size
20530 // meets (1080 and 1608 both pad to a superblock row), so every
20531 // candidate of every frame at those sizes fell through to a full
20532 // re-decode -- 57% of a 1080p frame's wall.
20533 let (fw, fh) = (r.frame_width, r.frame_height);
20534 if fw == r.width && fh == r.height {
20535 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20536 r.wrote = Vec::new();
20537 r.work_cdef = None;
20538 if share {
20539 let picture = Picture {
20540 width: r.width,
20541 height: r.height,
20542 y: y.data.to_vec(),
20543 u: u.data.to_vec(),
20544 v: v.data.to_vec(),
20545 };
20546 r.deblocked = Some((*loop_filter, y, u, v));
20547 return Some((picture, stages));
20548 }
20549 return Some((
20550 Picture {
20551 width: r.width,
20552 height: r.height,
20553 y: y.data.into_owned(),
20554 u: u.data.into_owned(),
20555 v: v.data.into_owned(),
20556 },
20557 stages,
20558 ));
20559 }
20560 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
20561 let mut out = Vec::with_capacity(w * h);
20562 for row in 0..h {
20563 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20564 }
20565 out
20566 };
20567 let (tw, th) = (r.true_width, r.true_height);
20568 fctx.last_frame_wide_margin.with(|m| {
20569 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
20570 width: tw,
20571 height: th,
20572 y: crop(&y, tw, th),
20573 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
20574 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
20575 });
20576 });
20577 let out = Picture {
20578 width: fw,
20579 height: fh,
20580 y: crop(&y, fw, fh),
20581 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20582 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20583 };
20584 // The working planes outlive the crop: either they ARE the
20585 // deblocked planes this candidate's successors reuse, or they go
20586 // back to the pool.
20587 if share {
20588 r.wrote = Vec::new();
20589 r.work_cdef = None;
20590 r.deblocked = Some((*loop_filter, y, u, v));
20591 } else {
20592 // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20593 // next candidate, together with the map of what CDEF wrote.
20594 r.wrote = wrote;
20595 r.work = Some((y, u, v));
20596 }
20597 Some((out, stages))
20598 })
20599}
20600
20601/// lane-av1cap2: the loop-restoration half of the final replay. Once the
20602/// units are chosen the tile is coded a second time to carry them, and that
20603/// re-coded tile used to be DECODED to reach the restored reference frame
20604/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that
20605/// tile but the per-unit filters the encoder just picked: it is the
20606/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on
20607/// the post-CDEF plane the final replay produced, with the TRUE
20608/// post-deblock stripe-border rows -- the same call the decoder's
20609/// `apply_loop_restoration` makes, on the same input. Only luma moves: the
20610/// encoder never writes a chroma restoration type other than
20611/// `RESTORE_NONE`, whose kernel hands its input straight back.
20612///
20613/// Returns the cropped luma plane and refreshes the wide-margin stash's own
20614/// luma (restoration writes strictly inside `frame_width x frame_height`,
20615/// so the margin columns past it stand). `None` when nothing was captured
20616/// -- the caller then decodes for real.
20617pub(crate) fn replay_restoration(
20618 lr: &LoopRestorationParams,
20619 units: &[Option<crate::restoration::WienerInfo>],
20620 fctx: &FrameCtx,
20621) -> Option<Vec<u16>> {
20622 #[cfg(test)]
20623 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20624 return None;
20625 }
20626 REPLAY.with_borrow_mut(|slot| {
20627 let r = slot.as_mut()?;
20628 let (cdefed, deblocked) = r.final_luma.as_ref()?;
20629 let (fw, fh) = (r.frame_width, r.frame_height);
20630 let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
20631 let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]);
20632 if horz == 0 || units.len() != horz * vert {
20633 return None;
20634 }
20635 for (i, filter) in units.iter().enumerate() {
20636 if let Some(info) = filter {
20637 grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info));
20638 }
20639 }
20640 let stride = cdefed.width;
20641 let mut out = scratch_empty();
20642 crate::restoration::apply_loop_restoration_plane(
20643 &cdefed.data,
20644 &deblocked.data,
20645 stride,
20646 fw,
20647 fh,
20648 0,
20649 lr.frame_restoration_type[0],
20650 lr.loop_restoration_size[0],
20651 &grid,
20652 0,
20653 &mut out,
20654 None,
20655 fctx,
20656 );
20657 fctx.last_frame_wide_margin.with(|m| {
20658 if let Some(p) = m.borrow_mut().as_mut() {
20659 let tw = p.width;
20660 for row in 0..p.height.min(fh) {
20661 let n = tw.min(fw);
20662 p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]);
20663 }
20664 }
20665 });
20666 let mut y = Vec::with_capacity(fw * fh);
20667 for row in 0..fh {
20668 y.extend(out[row * stride..][..fw].iter().copied());
20669 }
20670 scratch_return(out);
20671 Some(y)
20672 })
20673}
20674
20675/// The output crop, taking the plane by value: a frame whose width is
20676/// already superblock-aligned (only its height is padded) has a padded
20677/// buffer whose stride equals the visible width, so the crop is a pure
20678/// truncation of the buffer we already own -- no full-plane copy at all
20679/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
20680/// serial tail). Any other shape falls back to the row-by-row copy.
20681fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
20682 let stride = plane.width;
20683 let mut data = plane.data.into_owned();
20684 if stride == w {
20685 data.truncate(w * h);
20686 return data;
20687 }
20688 let mut out = Vec::with_capacity(w * h);
20689 for row in 0..h {
20690 out.extend(data[row * stride..][..w].iter().copied());
20691 }
20692 out
20693}
20694
20695/// Hands a buffer back to the pool; the capacity is what is worth keeping.
20696/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
20697/// what keeps a pool shared by every thread from being an unbounded stash.
20698fn scratch_return(v: Vec<u16>) {
20699 let mut p = PLANE_SCRATCH.lock().unwrap();
20700 if p.len() < SCRATCH_CAP {
20701 p.push(v);
20702 }
20703}
20704
20705/// One CDEF mi-row band, as a real function rather than the body of the
20706/// `run_bands` closure: inside the closure the destination planes are
20707/// `&mut` references derived from a `par::Shared` raw pointer in the same
20708/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
20709/// re-loads through them on every tap. Reference parameters restore `noalias`
20710/// (lane-perf11 (a): -x% instructions at one filter thread).
20711#[allow(clippy::too_many_arguments)]
20712fn cdef_band(
20713 r_lo: usize,
20714 r_hi: usize,
20715 y: &mut PlaneBuf<'static>,
20716 u: &mut PlaneBuf<'static>,
20717 v: &mut PlaneBuf<'static>,
20718 src_y: &[u16],
20719 src_u: &[u16],
20720 src_v: &[u16],
20721 cdef: &CdefParams,
20722 skip_grid: &Neighbours,
20723 idx_grid: &[u8],
20724 sb_cols: usize,
20725 coeff_shift: i32,
20726 damping: i32,
20727 damping_uv: i32,
20728 (frame_w, frame_h): (usize, usize),
20729 fctx: &crate::decode::FrameCtx,
20730 // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
20731 // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
20732 // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
20733 // `cdef_adjust_strength` zeroes a unit's primary strength off its own
20734 // variance, so which units a candidate writes is not a function of its
20735 // strengths alone -- the encoder's filter replay reuses one destination
20736 // plane across candidates and needs the map to restore it.
20737 mut wrote: Option<&mut [u8]>,
20738) {
20739 let unit_cols = skip_grid.mi_cols.div_ceil(2);
20740 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
20741 if sb_cols == 0 {
20742 return 0;
20743 }
20744 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
20745 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
20746 };
20747 // One scratch window per plane kind, reused by every unit (8x8 luma and
20748 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
20749 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
20750 // AVX2 kernel taps the window in place with two-row loads that reach
20751 // past the last sample, and the tail stays zero for every unit.
20752 let mut win_y = [0i16; 256];
20753 let mut win_uv = [0i16; 256];
20754 let mut mi_r = r_lo;
20755 while mi_r < r_hi {
20756 let mut mi_c = 0usize;
20757 while mi_c < skip_grid.mi_cols {
20758 if skip_grid.is_skip_txfm(mi_r, mi_c) {
20759 hit!(CDEF_SKIPPED_UNITS);
20760 }
20761 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
20762 let sidx = strength_idx(mi_r, mi_c);
20763 let (ox, oy) = (mi_c * 4, mi_r * 4);
20764 // Nothing to do for this unit at all: the direction search is
20765 // only ever consumed through a strength, so a unit whose four
20766 // strengths are zero never needs its 8x8 window gathered.
20767 if cdef.y_pri_strength[sidx] == 0
20768 && cdef.y_sec_strength[sidx] == 0
20769 && cdef.uv_pri_strength[sidx] == 0
20770 && cdef.uv_sec_strength[sidx] == 0
20771 {
20772 mi_c += 2;
20773 continue;
20774 }
20775 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
20776 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
20777 // lane-cdef r1: the direction search reads the SAME padded
20778 // block the taps do -- libaom runs `cdef_find_dir` on the
20779 // prepared filter block (`cdef_block.c:296-320` over
20780 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
20781 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
20782 // Clamping to the last real sample instead made every straddling
20783 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
20784 // a different `adjust_strength`, hence a +-1 band at the crop edge.
20785 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
20786
20787 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
20788 // -- each plane zeroes the shared direction when *its own*
20789 // frame-level primary strength is 0, independent of the
20790 // per-block adjusted `t` and of the other plane's strength.
20791 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
20792 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
20793 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
20794 let t = cdef_adjust_strength(y_pri_strength, var);
20795 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
20796 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
20797 eprintln!(
20798 "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}"
20799 );
20800 }
20801 let enable_primary = t != 0;
20802 let enable_secondary = y_sec_strength != 0;
20803 if (ox + 8 > frame_w || oy + 8 > frame_h)
20804 && (enable_primary
20805 || enable_secondary
20806 || cdef.uv_pri_strength[sidx] != 0
20807 || cdef.uv_sec_strength[sidx] != 0)
20808 {
20809 hit!(CDEF_STRADDLE_UNITS);
20810 }
20811 if enable_primary || enable_secondary {
20812 cdef_filter_block(
20813 &win_y,
20814 y,
20815 ox,
20816 oy,
20817 8,
20818 8,
20819 t,
20820 y_sec_strength,
20821 y_dir,
20822 damping,
20823 damping,
20824 enable_primary,
20825 enable_secondary,
20826 coeff_shift, fctx,
20827 );
20828 }
20829
20830 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
20831 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
20832 let uv_dir = if t_uv != 0 { dir } else { 0 };
20833 let enable_primary_uv = t_uv != 0;
20834 let enable_secondary_uv = uv_sec_strength != 0;
20835 if let Some(w) = wrote.as_deref_mut() {
20836 let mark = u8::from(enable_primary || enable_secondary)
20837 | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
20838 w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
20839 }
20840 if enable_primary_uv || enable_secondary_uv {
20841 let (cox, coy) = (ox / 2, oy / 2);
20842 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
20843 let (tw, th) = (plane.true_width, plane.true_height);
20844 let stride = plane.width;
20845 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
20846 cdef_filter_block(
20847 &win_uv,
20848 plane,
20849 cox,
20850 coy,
20851 4,
20852 4,
20853 t_uv,
20854 uv_sec_strength,
20855 uv_dir,
20856 damping_uv,
20857 damping_uv,
20858 enable_primary_uv,
20859 enable_secondary_uv,
20860 coeff_shift, fctx,
20861 );
20862 }
20863 }
20864 }
20865 mi_c += 2;
20866 }
20867 mi_r += 2;
20868 }
20869}
20870
20871
20872// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
20873//
20874// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
20875// every plane's vertical deblock edges, then every plane's horizontal ones,
20876// then CDEF, then -- unpipelined -- superres and loop restoration).
20877// A band is 64 luma rows, one superblock row (a 128 superblock is two).
20878//
20879// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
20880// band r, so no filter may touch band r before band r+1 is reconstructed.
20881// Hence V(r) waits for `ready >= r + 2`.
20882// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
20883// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
20884// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
20885// side of the band boundary, so H(r-1)'s last edge reaches into band r,
20886// which the whole-frame order has already vertical-filtered -- V(r)
20887// before H(r-1) reproduces exactly that.
20888// * post-deblock finality: band j's own bottom rows are still rewritten by
20889// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
20890// only be taken after H(j+1).
20891// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
20892// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
20893//
20894// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
20895// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
20896// superres upscale, which is a whole-frame refusal for this path) stay in the
20897// frame thread's tail; the snapshot the pipeline built is what LR reads.
20898struct PipeQ {
20899 /// Bands whose reconstruction the frame thread has released.
20900 ready: usize,
20901 abort: bool,
20902}
20903
20904pub(crate) struct PipeSync {
20905 m: std::sync::Mutex<PipeQ>,
20906 cv: std::sync::Condvar,
20907}
20908
20909impl PipeSync {
20910 fn new() -> Self {
20911 Self {
20912 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
20913 cv: std::sync::Condvar::new(),
20914 }
20915 }
20916 fn note(&self, ready: usize) {
20917 let mut q = self.m.lock().unwrap();
20918 if ready > q.ready {
20919 q.ready = ready;
20920 self.cv.notify_all();
20921 }
20922 }
20923 /// Releases every remaining band (`abort` = the tile decoder is bailing
20924 /// out, so the worker returns instead of finishing the frame).
20925 fn close(&self, all: usize, abort: bool) {
20926 let mut q = self.m.lock().unwrap();
20927 q.ready = q.ready.max(all);
20928 q.abort |= abort;
20929 self.cv.notify_all();
20930 }
20931 /// `false` when the frame was aborted.
20932 fn wait_for(&self, want: usize) -> bool {
20933 let mut q = self.m.lock().unwrap();
20934 while q.ready < want && !q.abort {
20935 q = self.cv.wait(q).unwrap();
20936 }
20937 !q.abort
20938 }
20939}
20940
20941/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
20942/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
20943/// otherwise only the four rows around each stripe boundary that loop
20944/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
20945fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
20946 let w = src.width;
20947 if w == 0 {
20948 return;
20949 }
20950 let rows = src.data.len() / w;
20951 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
20952 if lo >= hi {
20953 return;
20954 }
20955 if full {
20956 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
20957 return;
20958 }
20959 let stripe_h = 64usize >> ss_y;
20960 let offset = 8usize >> ss_y;
20961 let mut b = stripe_h - offset;
20962 while b < rows {
20963 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
20964 if a < e {
20965 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
20966 }
20967 b += stripe_h;
20968 }
20969}
20970
20971/// Everything the pipeline worker needs that is not a plane or a grid.
20972struct PipeCfg<'a> {
20973 lf: &'a LoopFilterParams,
20974 cdef: &'a CdefParams,
20975 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
20976 /// entries of the superblock rows the pipeline has not reached; the Vec
20977 /// itself is sized once per frame, so the pointer stays valid.
20978 idx_grid: (*const u8, usize),
20979 sb_cols: usize,
20980 frame_w: usize,
20981 frame_h: usize,
20982 nbands: usize,
20983 cdef_on: bool,
20984 snap_on: bool,
20985}
20986
20987// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
20988// per frame and only ever written at indices the pipeline is three bands
20989// behind (see this module's dependency note).
20990#[allow(unsafe_code)]
20991unsafe impl Send for PipeCfg<'_> {}
20992
20993#[allow(unsafe_code)]
20994#[allow(clippy::too_many_arguments)]
20995fn pipe_run(
20996 sync: &PipeSync,
20997 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20998 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20999 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
21000 sn: crate::par::Shared<'_, Neighbours>,
21001 cfg: PipeCfg<'_>,
21002 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21003 lr_sync: Option<&PipeSync>,
21004 fctx: &crate::decode::FrameCtx,
21005) {
21006 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
21007 // is at least two behind, and the two ranges never meet -- see the
21008 // dependency note above and `Shared`'s own corner-cut.
21009 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21010 let n: &Neighbours = unsafe { sn.get() };
21011 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
21012 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21013 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
21014 let damping_uv = (damping - 1).max(0);
21015 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
21016 let nb = cfg.nbands;
21017 for k in 0..nb + 3 {
21018 if !sync.wait_for((k + 2).min(nb)) {
21019 if let Some(ls) = lr_sync {
21020 ls.close(nb, true);
21021 }
21022 return;
21023 }
21024 if k < nb {
21025 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
21026 }
21027 if k >= 1 && k - 1 < nb {
21028 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
21029 }
21030 if cfg.snap_on && k >= 2 && k - 2 < nb {
21031 let j = k - 2;
21032 if let Some((sy2, su2, sv2)) = snap.as_mut() {
21033 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
21034 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
21035 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
21036 }
21037 }
21038 if cfg.cdef_on && k >= 3 && k - 3 < nb {
21039 let j = k - 3;
21040 if let Some((sy2, su2, sv2)) = snap.as_ref() {
21041 cdef_rows(
21042 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
21043 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
21044 None,
21045 );
21046 }
21047 }
21048 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
21049 // them to the loop restoration worker.
21050 if let Some(ls) = lr_sync {
21051 ls.note(k.saturating_sub(2));
21052 }
21053 }
21054 if let Some(ls) = lr_sync {
21055 ls.close(nb, false);
21056 }
21057}
21058
21059/// The pipeline's loop restoration worker, a second task alongside
21060/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
21061/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
21062/// post-deblock snapshot at most two rows past `v_end` (see
21063/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
21064/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
21065/// iteration `band + 3` and the snapshot band one iteration earlier, so the
21066/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
21067/// indices being at most one band apart. Running it as its own worker (not
21068/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
21069/// critical path: serialised into that loop it measured ~1% slower than the
21070/// whole-frame form, which at least ran its RU rows across the filter pool.
21071#[allow(unsafe_code)]
21072fn pipe_run_lr(
21073 sync: &PipeSync,
21074 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
21075 su: crate::par::Shared<'_, PlaneBuf<'static>>,
21076 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
21077 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
21078 cfg: LrCfg<'_>,
21079 fctx: &crate::decode::FrameCtx,
21080) {
21081 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
21082 // and writes its own `out` buffers; the final swap happens after the
21083 // last CDEF band, which is `pipe_run`'s last plane write.
21084 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21085 let snap = unsafe { snap.get() };
21086 let grid = unsafe { &*cfg.lr_grid };
21087 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
21088 let dims = [
21089 (fw, fh, 0u32, y.width, y.data.len()),
21090 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
21091 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
21092 ];
21093 let mut planes: Vec<LrPlane> = Vec::new();
21094 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
21095 let rows = crate::restoration::lr_unit_rows(
21096 ph,
21097 cfg.lr.loop_restoration_size[p],
21098 ss,
21099 cfg.lr.frame_restoration_type[p],
21100 );
21101 if rows.is_empty() {
21102 continue;
21103 }
21104 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
21105 }
21106 for band in 0..cfg.nbands {
21107 if !sync.wait_for(band + 1) {
21108 return;
21109 }
21110 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
21111 for lp in &mut planes {
21112 let stripe = 64usize >> lp.ss;
21113 let r_lo = lp.next;
21114 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
21115 lp.next += 1;
21116 }
21117 if lp.next == r_lo {
21118 continue;
21119 }
21120 let (src, deb) = match lp.p {
21121 0 => (&y.data, &sy2.data),
21122 1 => (&u.data, &su2.data),
21123 _ => (&v.data, &sv2.data),
21124 };
21125 crate::restoration::apply_loop_restoration_plane(
21126 src,
21127 deb,
21128 lp.stride,
21129 lp.pw,
21130 lp.ph,
21131 lp.ss,
21132 cfg.lr.frame_restoration_type[lp.p],
21133 cfg.lr.loop_restoration_size[lp.p],
21134 grid,
21135 lp.p,
21136 &mut lp.out,
21137 Some((r_lo, lp.next)),
21138 fctx,
21139 );
21140 }
21141 }
21142 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
21143 // untouched by restoration and copied here, then the restored plane
21144 // takes the picture's place (the whole-frame path's own final swap).
21145 for mut lp in planes {
21146 let buf: &mut PlaneBuf<'static> = match lp.p {
21147 0 => &mut *y,
21148 1 => &mut *u,
21149 _ => &mut *v,
21150 };
21151 let tail = lp.ph * lp.stride;
21152 if tail < buf.data.len() {
21153 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
21154 }
21155 scratch_return(
21156 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
21157 );
21158 }
21159}
21160
21161/// Everything [`pipe_run_lr`] needs beyond the planes.
21162struct LrCfg<'a> {
21163 lr: &'a LoopRestorationParams,
21164 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
21165 /// many bands ahead of every unit this worker reads.
21166 lr_grid: *const crate::restoration::RestorationGrid,
21167 frame_w: usize,
21168 frame_h: usize,
21169 nbands: usize,
21170}
21171
21172// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
21173#[allow(unsafe_code)]
21174unsafe impl Send for LrCfg<'_> {}
21175
21176/// One plane's pipelined loop restoration state (see [`pipe_run`]).
21177struct LrPlane {
21178 p: usize,
21179 /// The restored plane, built band by band and swapped in at the end.
21180 out: Vec<u16>,
21181 rows: Vec<(u32, u32)>,
21182 /// The first RU row not yet restored.
21183 next: usize,
21184 pw: usize,
21185 ph: usize,
21186 ss: u32,
21187 stride: usize,
21188}
21189
21190/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
21191/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
21192/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
21193/// pointers into the frame's planes, so it may not outlive them).
21194struct PipeGuard<'a> {
21195 sync: std::sync::Arc<PipeSync>,
21196 batch: Option<crate::par::Batch<'a>>,
21197 nbands: usize,
21198 /// The loop restoration worker's own gate, aborted with the first one.
21199 lr_sync: Option<std::sync::Arc<PipeSync>>,
21200}
21201
21202impl PipeGuard<'_> {
21203 fn note(&self, bands: usize) {
21204 self.sync.note(bands);
21205 }
21206 fn finish(&mut self) {
21207 self.sync.close(self.nbands, false);
21208 // Dropping the batch waits the worker out.
21209 self.batch.take();
21210 }
21211}
21212
21213impl Drop for PipeGuard<'_> {
21214 fn drop(&mut self) {
21215 self.sync.close(self.nbands, true);
21216 if let Some(ls) = &self.lr_sync {
21217 ls.close(self.nbands, true);
21218 }
21219 }
21220}
21221
21222/// Leading superblock rows of the live tile's wavefront that are fully
21223/// reconstructed: parsed out to the last column and with every job that
21224/// carried a write finished. 0 when reconstruction is inline (no wavefront),
21225/// where the caller uses the parse position instead.
21226fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
21227 let st = fctx.wave.with(|w| w.borrow().clone());
21228 let Some(st) = st else { return 0 };
21229 let q = st.q.lock().unwrap();
21230 let mut n = 0;
21231 while n < q.rows.len() {
21232 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
21233 break;
21234 }
21235 n += 1;
21236 }
21237 n
21238}
21239
21240/// Frames whose loop filters ran pipelined, and frames that took the
21241/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
21242static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
21243static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
21244
21245/// Whether this frame's filters may run per superblock row. Everything that
21246/// reads the picture out of band order, or the pipeline's own inputs out of
21247/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
21248/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
21249/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
21250/// frame row is only complete after the last tile column's own parse), and
21251/// every pixel-dump / stage-skip debug flag, whose whole point is the
21252/// unpipelined stage boundary. The pipeline also stays off unless some
21253/// threading is on -- at (1, 1) the filters would run on a worker thread for
21254/// nothing and the crate's `thread_local!` gate counters would miss them.
21255fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
21256 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
21257 return false;
21258 }
21259 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
21260 return false;
21261 }
21262 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
21263 return false;
21264 }
21265 if fctx.seg.with(|s| s.borrow().enabled) {
21266 return false;
21267 }
21268 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
21269 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
21270 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
21271 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
21272 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
21273 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
21274 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
21275 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
21276 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
21277 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
21278 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
21279 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
21280}
21281
21282/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
21283/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
21284/// never enters `apply_cdef`, so it calls this itself).
21285fn cdef_scan_counters(skip_grid: &Neighbours) {
21286 let _ = skip_grid;
21287 hit_do! {
21288 let mut r = 0usize;
21289 while r < skip_grid.mi_rows {
21290 let mut c = 0usize;
21291 while c < skip_grid.mi_cols {
21292 if (0..2).any(|rr| {
21293 (0..2).any(|cc| {
21294 !skip_grid
21295 .blk_grid
21296 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21297 .map_or(true, |x| x.written)
21298 })
21299 }) {
21300 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
21301 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
21302 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
21303 }
21304 }
21305 let cell = |rr: usize, cc: usize| {
21306 skip_grid
21307 .blk_grid
21308 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21309 .is_some_and(|x| x.skip)
21310 };
21311 let first = cell(0, 0);
21312 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
21313 hit!(CDEF_MIXED_SKIP_UNITS);
21314 }
21315 c += 2;
21316 }
21317 r += 2;
21318 }
21319 }
21320}
21321
21322/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
21323/// means "no filtering at all" whenever the single (index 0) strength pair
21324/// is all-zero, the fast path every existing gate stream takes.
21325fn cdef_all_zero(cdef: &CdefParams) -> bool {
21326 cdef.bits == 0
21327 && cdef.y_pri_strength[0] == 0
21328 && cdef.y_sec_strength[0] == 0
21329 && cdef.uv_pri_strength[0] == 0
21330 && cdef.uv_sec_strength[0] == 0
21331}
21332
21333/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
21334/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
21335/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
21336/// row range's own pixels.
21337#[allow(clippy::too_many_arguments)]
21338fn cdef_rows(
21339 y: &mut PlaneBuf<'static>,
21340 u: &mut PlaneBuf<'static>,
21341 v: &mut PlaneBuf<'static>,
21342 src_y: &[u16],
21343 src_u: &[u16],
21344 src_v: &[u16],
21345 cdef: &CdefParams,
21346 skip_grid: &Neighbours,
21347 idx_grid: &[u8],
21348 sb_cols: usize,
21349 coeff_shift: i32,
21350 damping: i32,
21351 damping_uv: i32,
21352 (frame_w, frame_h): (usize, usize),
21353 r_lo0: usize,
21354 r_hi0: usize, fctx: &crate::decode::FrameCtx,
21355 // See [`cdef_band`]. Shared because the bands below write disjoint unit
21356 // ROWS of it, exactly as they write disjoint plane rows.
21357 wrote: Option<crate::par::Shared<'_, [u8]>>,
21358) {
21359 let mi_rows = skip_grid.mi_rows;
21360 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
21361 if lo >= hi {
21362 return;
21363 }
21364 let (sy, su, sv) = (
21365 crate::par::Shared::new(y),
21366 crate::par::Shared::new(u),
21367 crate::par::Shared::new(v),
21368 );
21369 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
21370 .into_iter()
21371 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
21372 .collect();
21373 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
21374 // SAFETY: this band writes only the plane rows its own mi rows cover,
21375 // disjoint from every other band's (see `Shared`).
21376 #[allow(unsafe_code)]
21377 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21378 // SAFETY: this band marks only the unit rows its own mi rows cover,
21379 // disjoint from every other band's (see `Shared`).
21380 #[allow(unsafe_code)]
21381 let wr = wrote.as_ref().map(|w| unsafe { w.get() });
21382 cdef_band(
21383 r_lo,
21384 r_hi,
21385 y,
21386 u,
21387 v,
21388 src_y,
21389 src_u,
21390 src_v,
21391 cdef,
21392 skip_grid,
21393 idx_grid,
21394 sb_cols,
21395 coeff_shift,
21396 damping,
21397 damping_uv,
21398 (frame_w, frame_h),
21399 fctx,
21400 wr,
21401 );
21402 });
21403}
21404
21405fn apply_cdef(
21406 y: &mut PlaneBuf<'static>,
21407 u: &mut PlaneBuf<'static>,
21408 v: &mut PlaneBuf<'static>,
21409 cdef: &CdefParams,
21410 skip_grid: &Neighbours,
21411 // This frame header's own CROPPED luma size, for the straddling-unit
21412 // counter only -- CDEF itself walks the mi-rounded plane.
21413 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21414 // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter
21415 // starts by copying all three (~19 MB at 4K). The encoder's filter
21416 // replay already holds an untouched copy of exactly those planes -- its
21417 // post-deblock cache, which is where the working planes were copied FROM
21418 // -- so it hands them straight in and the copy does not happen. `None`
21419 // (every decode) copies as before.
21420 src: Option<(&[u16], &[u16], &[u16])>,
21421 // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
21422 // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
21423 // before the call.
21424 mut wrote: Option<&mut [u8]>,
21425) {
21426 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
21427 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
21428 return;
21429 }
21430 cdef_scan_counters(skip_grid);
21431 // `cdef.bits == 0` still means "no filtering at all" whenever the single
21432 // (index 0) strength pair is all-zero -- the fast path every existing
21433 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
21434 // at every index, but that is rare enough not to special-case; the
21435 // per-superblock lookup below degrades to the same index-0 read anyway
21436 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
21437 if cdef_all_zero(cdef) {
21438 return;
21439 }
21440 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
21441 // One entry per superblock (a few hundred at 4K), so this clone is not
21442 // one of the per-frame copies lane-perf6 pooled below.
21443 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
21444 let owned = src.is_none();
21445 let (src_y, src_u, src_v) = match src {
21446 Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)),
21447 None => (
21448 std::borrow::Cow::Owned(scratch_from(&y.data)),
21449 std::borrow::Cow::Owned(scratch_from(&u.data)),
21450 std::borrow::Cow::Owned(scratch_from(&v.data)),
21451 ),
21452 };
21453 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
21454 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
21455 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21456 let damping = i32::from(cdef.damping) + coeff_shift;
21457 let damping_uv = (damping - 1).max(0);
21458 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
21459 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
21460 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
21461 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
21462 // disjoint row range of all three planes.
21463 cdef_rows(
21464 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
21465 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21466 wrote.as_deref_mut().map(crate::par::Shared::new),
21467 );
21468 if owned {
21469 scratch_return(src_y.into_owned());
21470 scratch_return(src_u.into_owned());
21471 scratch_return(src_v.into_owned());
21472 }
21473}
21474
21475/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
21476/// restoration on both tile paths: hands the encoder's restoration search the
21477/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
21478/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
21479/// a capture is worth three plane copies and nothing else -- and when the
21480/// capture flag is off (every decode but that search) it is worth a bool.
21481fn capture_stages(
21482 y: &PlaneBuf<'_>,
21483 u: &PlaneBuf<'_>,
21484 v: &PlaneBuf<'_>,
21485 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21486 fctx: &FrameCtx,
21487) {
21488 if !fctx.capture_stages.get() {
21489 return;
21490 }
21491 // Without an active restoration type the decoder took no pre-CDEF
21492 // snapshot; the post-CDEF plane then stands in for it, which is exact
21493 // everywhere but LR's own 3-row stripe borders (the encoder's search
21494 // always asks with a type set, so this is the defensive arm).
21495 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
21496 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
21497 None => p.data.to_vec(),
21498 };
21499 *fctx.stages.borrow_mut() = Some(FilterStages {
21500 deblocked: [db(0, y), db(1, u), db(2, v)],
21501 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
21502 stride: [y.width, u.width, v.width],
21503 });
21504}
21505
21506/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
21507/// ordering note: libaom also runs `superres_post_decode` between the two,
21508/// but this decoder never implements super-resolution, so there is nothing
21509/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
21510/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
21511/// restoration's stripe-boundary rows read from it instead of the
21512/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
21513#[allow(clippy::too_many_arguments)]
21514fn apply_loop_restoration(
21515 y: &mut PlaneBuf<'static>,
21516 u: &mut PlaneBuf<'static>,
21517 v: &mut PlaneBuf<'static>,
21518 deblocked_y: &PlaneBuf<'_>,
21519 deblocked_u: &PlaneBuf<'_>,
21520 deblocked_v: &PlaneBuf<'_>,
21521 lr: &LoopRestorationParams,
21522 grid: &crate::restoration::RestorationGrid,
21523 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
21524 // restoration is the ONE post-decode filter that does NOT run over the
21525 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
21526 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
21527 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
21528 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
21529 // -- and asserts it equals the buffer's CROP width
21530 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
21531 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
21532 // that cropped edge before any unit is filtered. Deblock and CDEF DO
21533 // walk the mi grid, which is why passing `true_width`/`true_height`
21534 // here went unnoticed until a frame whose size is not a multiple of 8
21535 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
21536 // read this decoder's own decoded samples at columns 68..71 where
21537 // libaom reads column 67 replicated -- +-1 over the straddling band
21538 // (class av1-truesize-lane: true frame size vs mi-rounded).
21539 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21540) {
21541 let mut out = scratch_empty();
21542 crate::restoration::apply_loop_restoration_plane(
21543 &y.data,
21544 &deblocked_y.data,
21545 y.width,
21546 frame_w,
21547 frame_h,
21548 0,
21549 lr.frame_restoration_type[0],
21550 lr.loop_restoration_size[0],
21551 grid,
21552 0,
21553 &mut out, None, fctx,
21554 );
21555 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
21556 let mut out = scratch_empty();
21557 crate::restoration::apply_loop_restoration_plane(
21558 &u.data,
21559 &deblocked_u.data,
21560 u.width,
21561 frame_w.div_ceil(2),
21562 frame_h.div_ceil(2),
21563 1,
21564 lr.frame_restoration_type[1],
21565 lr.loop_restoration_size[1],
21566 grid,
21567 1,
21568 &mut out, None, fctx,
21569 );
21570 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
21571 let mut out = scratch_empty();
21572 crate::restoration::apply_loop_restoration_plane(
21573 &v.data,
21574 &deblocked_v.data,
21575 v.width,
21576 frame_w.div_ceil(2),
21577 frame_h.div_ceil(2),
21578 1,
21579 lr.frame_restoration_type[2],
21580 lr.loop_restoration_size[2],
21581 grid,
21582 2,
21583 &mut out, None, fctx,
21584 );
21585 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
21586}
21587
21588/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
21589/// returning the picture it reconstructs to.
21590///
21591/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
21592/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
21593/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
21594/// `compute_image_size` derives one from the other, but not losslessly: a
21595/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
21596/// what the reconstruction is cropped to on the way out, mirroring
21597/// [`crate::encode::crop_encoded`].
21598///
21599/// # Errors
21600/// Returns an error when a block's partition, mode, skip flag or transform
21601/// type is anything this decoder does not reconstruct (round 2: inter, tx
21602/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
21603/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
21604/// or when the tile payload runs out of the symbols this decode expects (a
21605/// genuinely foreign stream).
21606#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21607pub(crate) fn decode_key_frame_tile(
21608 data: &[u8],
21609 mi_cols: u32,
21610 mi_rows: u32,
21611 base_q_idx: u8,
21612 frame_width: u32,
21613 frame_height: u32,
21614 enable_filter_intra: bool,
21615 cdef: &CdefParams,
21616 loop_filter: &LoopFilterParams,
21617 tx_select: bool,
21618 reduced_tx_set: bool,
21619 allow_screen_content_tools: bool,
21620 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
21621) -> Result<Picture> {
21622 decode_key_frame_tile_lr(
21623 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
21624 cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
21625 &LoopRestorationParams::default(), fctx,
21626 )
21627}
21628
21629/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
21630/// 5.9.20) instead of the no-restoration default -- the per-unit filters
21631/// themselves live in the tile payload, so the header is all this needs.
21632#[allow(clippy::too_many_arguments)]
21633pub(crate) fn decode_key_frame_tile_lr(
21634 data: &[u8],
21635 mi_cols: u32,
21636 mi_rows: u32,
21637 base_q_idx: u8,
21638 frame_width: u32,
21639 frame_height: u32,
21640 enable_filter_intra: bool,
21641 cdef: &CdefParams,
21642 loop_filter: &LoopFilterParams,
21643 tx_select: bool,
21644 reduced_tx_set: bool,
21645 allow_screen_content_tools: bool,
21646 allow_intrabc: bool,
21647 lr: &LoopRestorationParams,
21648 fctx: &crate::decode::FrameCtx,
21649) -> Result<Picture> {
21650 let single_tile = TileInfo {
21651 mi_col_starts: vec![0, mi_cols],
21652 mi_row_starts: vec![0, mi_rows],
21653 ..TileInfo::default()
21654 };
21655 decode_key_frame_tiles_lr(
21656 &[data],
21657 &single_tile,
21658 mi_cols,
21659 mi_rows,
21660 base_q_idx,
21661 frame_width,
21662 frame_height,
21663 enable_filter_intra,
21664 cdef,
21665 loop_filter,
21666 tx_select,
21667 reduced_tx_set,
21668 allow_screen_content_tools,
21669 allow_intrabc,
21670 lr,
21671 fctx,
21672 )
21673}
21674
21675/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
21676/// encoder's own filter search hands back one payload per tile plus the
21677/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
21678/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
21679#[allow(clippy::too_many_arguments)]
21680pub(crate) fn decode_key_frame_tiles_lr(
21681 tiles: &[&[u8]],
21682 tile_info: &TileInfo,
21683 mi_cols: u32,
21684 mi_rows: u32,
21685 base_q_idx: u8,
21686 frame_width: u32,
21687 frame_height: u32,
21688 enable_filter_intra: bool,
21689 cdef: &CdefParams,
21690 loop_filter: &LoopFilterParams,
21691 tx_select: bool,
21692 reduced_tx_set: bool,
21693 allow_screen_content_tools: bool,
21694 allow_intrabc: bool,
21695 lr: &LoopRestorationParams,
21696 fctx: &crate::decode::FrameCtx,
21697) -> Result<Picture> {
21698 let delta = DeltaParams::default();
21699 decode_key_frame_tile_with_cdfs(
21700 tiles,
21701 tile_info,
21702 mi_cols,
21703 mi_rows,
21704 base_q_idx,
21705 crate::quant::QuantDeltas::default(),
21706 frame_width,
21707 frame_height,
21708 enable_filter_intra,
21709 false,
21710 cdef,
21711 loop_filter,
21712 lr,
21713 None,
21714 tx_select,
21715 reduced_tx_set,
21716 allow_screen_content_tools,
21717 allow_intrabc,
21718 delta, fctx,
21719 )
21720 .map(|(picture, _)| picture)
21721}
21722
21723 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
21724 /// the mi-aligned `true_width`, set by the most recent
21725 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
21726 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
21727 /// their reconstructed buffer down from the same mi-aligned extent, so
21728 /// they share this one slot. See each function's own comment at its
21729 /// write site. `None` when there was no margin to save.
21730
21731/// The margin the most recent key- or inter-frame tile decode stashed
21732/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
21733/// reads this immediately after the call, before any other frame
21734/// decode can overwrite it.
21735#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21736pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
21737 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
21738}
21739
21740/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
21741/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
21742/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
21743/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
21744/// since a key frame's own header always forces `primary_ref_frame ==
21745/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
21746/// alongside the picture, for the caller to save into whichever reference
21747/// slots this frame's `refresh_frame_flags` names.
21748/// The order the 64x64 superblock quadrants of a tile are decoded in.
21749///
21750/// At `sb_size == 64` this is plain raster order over the tile's own
21751/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
21752/// each 128x128 superblock in raster order and visits its four 64x64
21753/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
21754/// 64-level bodies must run in that nested order. `row_start` marks the first
21755/// item of each *superblock* row (where the left neighbour context resets),
21756/// `sb_start` the first item of each superblock (where the 128 root's own
21757/// loop-restoration units and partition symbol are read).
21758fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
21759 let mut out = Vec::new();
21760 if !sb128 {
21761 for r in r0..r1 {
21762 for c in c0..c1 {
21763 out.push((r, c, c == c0, true));
21764 }
21765 }
21766 return out;
21767 }
21768 let mut r = r0;
21769 while r < r1 {
21770 let mut first_in_row = true;
21771 let mut c = c0;
21772 while c < c1 {
21773 let mut first_in_sb = true;
21774 for qr in 0..2 {
21775 for qc in 0..2 {
21776 let (rr, cc) = (r + qr, c + qc);
21777 if rr >= r1 || cc >= c1 {
21778 continue;
21779 }
21780 out.push((rr, cc, first_in_row, first_in_sb));
21781 first_in_row = false;
21782 first_in_sb = false;
21783 }
21784 }
21785 c += 2;
21786 }
21787 r += 2;
21788 }
21789 out
21790}
21791
21792// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
21793// the inter tile loop. Its loop-restoration units are read once for the whole
21794// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
21795// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
21796// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
21797// decoder codes, the other seven arms refuse by name.
21798thread_local! {
21799 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
21800 /// whole 128x128 block (lane-sb128b r1's gate counter).
21801 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21802 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
21803 /// when the bottom half is out of frame) -- lane-sb128c r7.
21804 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21805 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
21806 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21807 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
21808 /// only shape a 1080p (mi_rows = 270) stream reaches.
21809 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21810 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21811 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
21812 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
21813 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
21814}
21815
21816/// [`PART128_AB_HITS`], for a gate's own before/after delta.
21817pub(crate) fn part128_ab_hits() -> [usize; 4] {
21818 PART128_AB_HITS.with(std::cell::Cell::get)
21819}
21820
21821/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
21822#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21823pub(crate) fn part128_none_hits() -> usize {
21824 PART128_NONE_HITS.with(std::cell::Cell::get)
21825}
21826
21827/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
21828#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21829pub(crate) fn part128_horz_hits() -> usize {
21830 PART128_HORZ_HITS.with(std::cell::Cell::get)
21831}
21832
21833/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
21834#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21835pub(crate) fn part128_vert_hits() -> usize {
21836 PART128_VERT_HITS.with(std::cell::Cell::get)
21837}
21838
21839/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
21840pub(crate) fn part128_edge_horz_hits() -> usize {
21841 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
21842}
21843
21844/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
21845pub(crate) fn part128_edge_vert_hits() -> usize {
21846 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
21847}
21848
21849thread_local! {
21850 /// How many CHROMA transform units were coded inside a block whose uv
21851 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
21852 /// block, four per plane).
21853 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21854}
21855
21856/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
21857#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21858pub(crate) fn chroma_split_tx_hits() -> usize {
21859 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
21860}
21861
21862fn read_sb128_root(
21863 dec: &mut SymbolDecoder,
21864 cdfs: &mut Cdfs,
21865 neighbours: &Neighbours,
21866 lr: &LoopRestorationParams,
21867 lr_grid: &mut crate::restoration::RestorationGrid,
21868 lr_reference: &mut [(
21869 crate::restoration::WienerInfo,
21870 crate::restoration::SgrprojInfo,
21871 ); 3],
21872 sb_r: u32,
21873 sb_c: u32,
21874 mi_cols: u32,
21875 mi_rows: u32, fctx: &crate::decode::FrameCtx,
21876) -> Result<usize> {
21877 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
21878 crate::restoration::read_lr(
21879 dec,
21880 cdfs,
21881 lr,
21882 lr_grid,
21883 lr_reference,
21884 mi_r128,
21885 mi_c128,
21886 SB_MI * 2, fctx,
21887 );
21888 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
21889 let ctx128 = neighbours.partition_ctx(at128, 128);
21890 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
21891 let part128 = if has_cols128 && has_rows128 {
21892 hit!(PART128_SYMBOLS);
21893 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
21894 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21895 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
21896 }
21897 p
21898 } else {
21899 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
21900 // partition, they are not a forced split -- exactly the discarded-bit
21901 // defect the 64 root carries a comment about at `partition_w64`'s
21902 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
21903 // VERT (cols out of frame), which the refusal below then names
21904 // instead of silently reconstructing a split.
21905 hit!(PART128_GATHERED_SYMBOLS);
21906 match (has_cols128, has_rows128) {
21907 (true, false) => {
21908 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
21909 PARTITION_SPLIT
21910 } else {
21911 hit!(PART128_EDGE_HORZ_HITS);
21912 PARTITION_HORZ
21913 }
21914 }
21915 (false, true) => {
21916 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
21917 PARTITION_SPLIT
21918 } else {
21919 hit!(PART128_EDGE_VERT_HITS);
21920 PARTITION_VERT
21921 }
21922 }
21923 _ => {
21924 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
21925 bump_edge_both_cut(3);
21926 PARTITION_SPLIT
21927 }
21928 }
21929 };
21930 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
21931 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
21932 // four AB shapes) still need the rect/AB machinery at this size.
21933 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
21934 // both tile paths. The four AB shapes (libaom `decode_partition`'s
21935 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
21936 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
21937 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
21938 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
21939 // which stops at VERT_B).
21940 match part128 {
21941 PARTITION_SPLIT => hit!(PART128_SPLIT_HITS),
21942 PARTITION_NONE => hit!(PART128_NONE_HITS),
21943 PARTITION_HORZ => hit!(PART128_HORZ_HITS),
21944 PARTITION_VERT => hit!(PART128_VERT_HITS),
21945 // lane-sb128c r9: the four AB shapes at the 128 root -- one
21946 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
21947 // paths below in libaom `decode_partition`'s own visit order.
21948 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
21949 hit_do! {
21950 PART128_AB_HITS.with(|c| {
21951 let mut h = c.get();
21952 h[p - PARTITION_HORZ_A] += 1;
21953 c.set(h);
21954 });
21955 }
21956 }
21957 _ => {
21958 return Err(unsupported(
21959 "a 128x128 superblock partition value outside the 8-symbol alphabet",
21960 ));
21961 }
21962 }
21963 Ok(part128)
21964}
21965
21966pub(crate) fn decode_key_frame_tile_with_cdfs(
21967 tiles: &[&[u8]],
21968 tile_info: &TileInfo,
21969 mi_cols: u32,
21970 mi_rows: u32,
21971 base_q_idx: u8,
21972 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
21973 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
21974 // tile alongside [`CURRENT_Q_IDX`].
21975 deltas: crate::quant::QuantDeltas,
21976 frame_width: u32,
21977 frame_height: u32,
21978 enable_filter_intra: bool,
21979 enable_edge_filter: bool,
21980 cdef: &CdefParams,
21981 loop_filter: &LoopFilterParams,
21982 lr: &LoopRestorationParams,
21983 initial_cdfs: Option<Cdfs>,
21984 tx_select: bool,
21985 reduced_tx_set: bool,
21986 allow_screen_content_tools: bool,
21987 allow_intrabc: bool,
21988 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
21989 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
21990 // `stream.rs` still refuses a frame with `lf_present` set before this
21991 // function is ever called.
21992 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
21993) -> Result<(Picture, Cdfs)> {
21994 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
21995 // only, so a key frame decoded after an inter frame on this thread would
21996 // otherwise inherit it and read its `tx_depth` context off the inter
21997 // frame's stale `TXFM_CONTEXT` bands.
21998 fctx.tx_select_inter.with(|c| c.set(false));
21999 if mi_cols == 0 || mi_rows == 0 {
22000 return Err(unsupported("a frame with no mode-info grid"));
22001 }
22002 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
22003 let sb128 = sb128(fctx);
22004 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
22005 fctx.intrabc_mi_grid.with(|g| {
22006 *g.borrow_mut() = allow_intrabc.then(|| {
22007 (
22008 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
22009 mi_cols as usize,
22010 mi_rows as usize,
22011 )
22012 });
22013 });
22014 fctx.intrabc_dv.with(|c| c.set(None));
22015 fctx.cdef_bits.with(|c| c.set(cdef.bits));
22016 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
22017 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
22018 fctx.delta_q_present.with(|c| c.set(delta.q_present));
22019 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
22020 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
22021 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
22022 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
22023 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
22024 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
22025 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
22026
22027 let mut y = PlaneBuf {
22028 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
22029 width,
22030 height,
22031 true_width,
22032 true_height,
22033 tile_x0: 0,
22034 tile_y0: 0,
22035 tile_x1: width,
22036 tile_y1: height,
22037 };
22038 let mut u = PlaneBuf {
22039 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
22040 width: width / 2,
22041 height: height / 2,
22042 true_width: true_width / 2,
22043 true_height: true_height / 2,
22044 tile_x0: 0,
22045 tile_y0: 0,
22046 tile_x1: width / 2,
22047 tile_y1: height / 2,
22048 };
22049 let mut v = PlaneBuf {
22050 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
22051 width: width / 2,
22052 height: height / 2,
22053 true_width: true_width / 2,
22054 true_height: true_height / 2,
22055 tile_x0: 0,
22056 tile_y0: 0,
22057 tile_x1: width / 2,
22058 tile_y1: height / 2,
22059 };
22060
22061 let scan32 = default_scan(TX32);
22062 let scan16 = default_scan(TX16);
22063 let scan8 = default_scan(TX8);
22064 let scan4 = default_scan(TX4);
22065
22066 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
22067 let mut result_cdfs = base_cdfs.clone();
22068 let mut neighbours = Neighbours::new(
22069 cols32 as usize * 2,
22070 rows32 as usize * 2,
22071 mi_cols as usize,
22072 mi_rows as usize, fctx,
22073 );
22074 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
22075 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
22076 // loop restoration runs after the superres upscale.
22077 let mut lr_grid = crate::restoration::RestorationGrid::new(
22078 lr,
22079 superres(fctx).map_or(frame_width, |(w, _)| w),
22080 frame_height,
22081 );
22082
22083 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
22084 // own byte range and its own fresh copy of the frame's initial CDFs
22085 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
22086 // `context_update_tile_id` has its end-of-tile adapted table kept as the
22087 // frame's own output (spec `exit_symbol`) -- every other tile's
22088 // adaptation is discarded, matching the refusal this replaces.
22089 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
22090 let tile_num = tile_idx as u32;
22091 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
22092 let mi_row0 = tile_info.mi_row_starts[trow as usize];
22093 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
22094 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
22095 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
22096 // Tile boundaries are always superblock-aligned in mi units (spec
22097 // 5.9.15's uniform/non-uniform derivation both only ever emit
22098 // multiples of the superblock's own mi size), so plain division is
22099 // exact here -- no rounding needed.
22100 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
22101 // tile boundary) are always superblock-aligned by spec 5.9.15; the
22102 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
22103 // last entry) is not, so the upper bound needs `div_ceil` the same
22104 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
22105 // trailing partial superblock row/column in scope.
22106 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
22107 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
22108
22109 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
22110 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
22111 // once per frame. Carried across a tile boundary, the loop-restoration
22112 // coefficients of the next tile decode off the previous tile's
22113 // reference -- same symbol count, so entropy and reconstruction stay
22114 // exact and only the filtered pixels of every tile after the first
22115 // are wrong.
22116 let mut lr_reference = [(
22117 crate::restoration::WienerInfo::default(),
22118 crate::restoration::SgrprojInfo::default(),
22119 ); 3];
22120 let mut cdfs = base_cdfs.clone();
22121 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
22122 // `base_q_idx` at the top of every tile, not once per frame.
22123 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
22124 fctx.quant_deltas.with(|c| c.set(deltas));
22125 fctx.current_delta_lf.with(|c| c.set([0; 4]));
22126 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22127 eprintln!(
22128 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
22129 tile_bytes.len(),
22130 &tile_bytes[..tile_bytes.len().min(8)]
22131 );
22132 }
22133 let mut dec = SymbolDecoder::new(tile_bytes);
22134 crate::census::register_cdfs(&cdfs);
22135 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
22136 y.set_tile_origin(
22137 mi_col0 as usize * 4,
22138 mi_row0 as usize * 4,
22139 (mi_col1 as usize * 4).min(y.width),
22140 (mi_row1 as usize * 4).min(y.height),
22141 );
22142 u.set_tile_origin(
22143 mi_col0 as usize * 2,
22144 mi_row0 as usize * 2,
22145 (mi_col1 as usize * 2).min(u.width),
22146 (mi_row1 as usize * 2).min(u.height),
22147 );
22148 v.set_tile_origin(
22149 mi_col0 as usize * 2,
22150 mi_row0 as usize * 2,
22151 (mi_col1 as usize * 2).min(v.width),
22152 (mi_row1 as usize * 2).min(v.height),
22153 );
22154 hit!(TILE_HITS);
22155
22156 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
22157 // its one block covers all four 64x64 quadrants, so the remaining three
22158 // visits of this superblock code nothing at all.
22159 let mut sb128_none = false;
22160 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
22161 // are performed at their push sites (nothing reaches the queue below).
22162 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
22163 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
22164 // when `sb128`, since a 128 block writes across its four 64x64 visits).
22165 let wave_shift = u32::from(sb128);
22166 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
22167 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
22168 (
22169 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
22170 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
22171 )
22172 } else {
22173 (0, 0)
22174 };
22175 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
22176 let waving = fctx.wave.with(|w| w.borrow().is_some());
22177 let mut wave_job = (0usize, 0usize);
22178 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
22179 // lane-wave1: the previous superblock's recorded writes -- handed to
22180 // the wavefront workers, or replayed here at one recon thread (where
22181 // the queue is empty, every write having run at its push site).
22182 if waving {
22183 if sb_start {
22184 wave_submit(fctx, wave_job.0, wave_job.1);
22185 wave_job = (
22186 (sb_r >> wave_shift) as usize - wave_r0,
22187 (sb_c >> wave_shift) as usize - wave_c0,
22188 );
22189 }
22190 } else {
22191 flush_recon(fctx, &mut y, &mut u, &mut v);
22192 }
22193 if row_start {
22194 neighbours.start_row();
22195 }
22196 if sb_start {
22197 sb128_none = false;
22198 }
22199 if sb128_none {
22200 continue;
22201 }
22202 {
22203 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
22204 // once for the whole 128x128 (spec 5.11.57 is called with the
22205 // superblock's own size), then one partition symbol off the
22206 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
22207 // recurses into the four 64x64 quadrants this decoder codes.
22208 if sb128 && sb_start {
22209 let part128 = read_sb128_root(
22210 &mut dec,
22211 &mut cdfs,
22212 &neighbours,
22213 lr,
22214 &mut lr_grid,
22215 &mut lr_reference,
22216 sb_r,
22217 sb_c,
22218 mi_cols,
22219 mi_rows, fctx,
22220 )?;
22221 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
22222 // lane-sb128c r9: the four AB shapes at the 128 root.
22223 // libaom `decode_partition` (decodeframe.c) codes each as
22224 // two `bsize2` (64x64) squares plus one `subsize`
22225 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
22226 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
22227 // half; VERT_B = left half, TR, BR. AB values only come
22228 // from the FULL alphabet symbol, which is only read when
22229 // both halves of the root are inside the frame, so no
22230 // piece needs libaom's `i > 0` frame-edge break (a piece
22231 // may still overhang the bottom/right, which
22232 // `PlaneBuf::reconstruct`'s r8 clip handles).
22233 sb128_none = true;
22234 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22235 let (br, bc) = (at128.0 + 4, at128.1 + 4);
22236 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22237 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
22238 // BR), so only they switch libaom's `has_tr_vert_*` /
22239 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
22240 let _vert_ab =
22241 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
22242 .then(crate::encode::Reach::vert_ab_partition);
22243 // One `cdef_idx` literal per CODED BLOCK, at the first
22244 // non-skip one of each 64x64 CDEF unit; the 128x64 /
22245 // 64x128 half covers two units and its read lands in the
22246 // unit holding its origin, so that value is copied to the
22247 // other one (libaom: every mi of the block points at the
22248 // same `MB_MODE_INFO`).
22249 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
22250 fctx.cdef_idx_grid.with(|g| {
22251 let mut g = g.borrow_mut();
22252 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22253 if cols == 0 {
22254 return;
22255 }
22256 let (si, di) = (
22257 (q_r + src.0) * cols + q_c + src.1,
22258 (q_r + dst.0) * cols + q_c + dst.1,
22259 );
22260 if q_c + src.1 < cols
22261 && q_c + dst.1 < cols
22262 && si < g.len()
22263 && di < g.len()
22264 {
22265 g[di] = g[si];
22266 }
22267 });
22268 };
22269 macro_rules! square64 {
22270 ($at:expr) => {{
22271 fctx.cdef_transmitted.with(|c| c.set(false));
22272 decode_block(
22273 &mut dec,
22274 &mut cdfs,
22275 &mut neighbours,
22276 $at,
22277 SB,
22278 TxbSet::Luma64,
22279 TxbSet::Chroma32,
22280 TX32,
22281 TX32,
22282 (&scan32, &scan32),
22283 false,
22284 &mut y,
22285 &mut u,
22286 &mut v,
22287 base_q_idx,
22288 enable_filter_intra,
22289 allow_screen_content_tools,
22290 allow_intrabc,
22291 &scan32,
22292 &scan16,
22293 &scan8,
22294 &scan4,
22295 tx_select,
22296 reduced_tx_set, fctx,
22297 )?
22298 }};
22299 }
22300 macro_rules! half128 {
22301 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
22302 fctx.cdef_transmitted.with(|c| c.set(false));
22303 decode_block_128rect(
22304 &mut dec,
22305 &mut cdfs,
22306 &mut neighbours,
22307 $at,
22308 $bw,
22309 $bh,
22310 &mut y,
22311 &mut u,
22312 &mut v,
22313 base_q_idx,
22314 enable_filter_intra,
22315 allow_screen_content_tools,
22316 tx_select,
22317 reduced_tx_set, fctx,
22318 )?;
22319 cdef_copy($src, $dst);
22320 }};
22321 }
22322 match part128 {
22323 PARTITION_HORZ_A => {
22324 square64!(at128);
22325 square64!((at128.0, bc));
22326 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
22327 }
22328 PARTITION_HORZ_B => {
22329 half128!(at128, 128, 64, (0, 0), (0, 1));
22330 square64!((br, at128.1));
22331 square64!((br, bc));
22332 }
22333 PARTITION_VERT_A => {
22334 square64!(at128);
22335 square64!((br, at128.1));
22336 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
22337 }
22338 _ => {
22339 half128!(at128, 64, 128, (0, 0), (1, 0));
22340 square64!((at128.0, bc));
22341 square64!((br, bc));
22342 }
22343 }
22344 continue;
22345 }
22346 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
22347 // lane-sb128c r8: libaom `decode_partition`
22348 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
22349 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
22350 // plus a second one at (mi_row + hbs, mi_col) only
22351 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
22352 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
22353 // = 16 mi. Both halves together cover the whole root, so
22354 // the remaining three 64x64 quadrant visits code nothing
22355 // (same flag the NONE arm sets).
22356 sb128_none = true;
22357 let horz = part128 == PARTITION_HORZ;
22358 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22359 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
22360 for i in 0..2 {
22361 let at = if horz {
22362 (at128.0 + i * 4, at128.1)
22363 } else {
22364 (at128.0, at128.1 + i * 4)
22365 };
22366 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
22367 if i > 0
22368 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
22369 {
22370 break;
22371 }
22372 // Each half reads its OWN `cdef_idx` literal
22373 // (libaom `read_cdef` keys the `-1` test on the
22374 // block's own `MB_MODE_INFO`, and the two halves have
22375 // different ones).
22376 fctx.cdef_transmitted.with(|c| c.set(false));
22377 decode_block_128rect(
22378 &mut dec,
22379 &mut cdfs,
22380 &mut neighbours,
22381 at,
22382 bw,
22383 bh,
22384 &mut y,
22385 &mut u,
22386 &mut v,
22387 base_q_idx,
22388 enable_filter_intra,
22389 allow_screen_content_tools,
22390 tx_select,
22391 reduced_tx_set, fctx,
22392 )?;
22393 }
22394 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
22395 // unit it covers (the inter path's own fan-out).
22396 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22397 fctx.cdef_idx_grid.with(|g| {
22398 let mut g = g.borrow_mut();
22399 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22400 if cols == 0 {
22401 return;
22402 }
22403 for (src, dst) in if horz {
22404 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
22405 } else {
22406 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
22407 } {
22408 let (si, di) = (
22409 (q_r + src.0) * cols + q_c + src.1,
22410 (q_r + dst.0) * cols + q_c + dst.1,
22411 );
22412 if q_c + src.1 < cols
22413 && q_c + dst.1 < cols
22414 && si < g.len()
22415 && di < g.len()
22416 {
22417 g[di] = g[si];
22418 }
22419 }
22420 });
22421 continue;
22422 }
22423 if part128 == PARTITION_NONE {
22424 // One 128x128 intra block: four TX_64X64 luma units and a
22425 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
22426 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
22427 // block). No CfL, no filter intra, no palette at this size --
22428 // [`read_intra_mode`]'s own size gates already say so.
22429 sb128_none = true;
22430 fctx.cdef_transmitted.with(|c| c.set(false));
22431 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22432 decode_block(
22433 &mut dec,
22434 &mut cdfs,
22435 &mut neighbours,
22436 at128,
22437 SB * 2,
22438 TxbSet::Luma64,
22439 TxbSet::Chroma32,
22440 TX32,
22441 TX32,
22442 (&scan32, &scan32),
22443 false,
22444 &mut y,
22445 &mut u,
22446 &mut v,
22447 base_q_idx,
22448 enable_filter_intra,
22449 allow_screen_content_tools,
22450 allow_intrabc,
22451 &scan32,
22452 &scan16,
22453 &scan8,
22454 &scan4,
22455 tx_select,
22456 reduced_tx_set, fctx,
22457 )?;
22458 // libaom writes one `cdef_strength` into the block's own
22459 // `MB_MODE_INFO`, which every mi cell of the block --
22460 // hence all four 64x64 CDEF units -- points at; our grid
22461 // is per-unit, so the read (which only ever lands in the
22462 // top-left unit, `read_cdef`'s index 0) is copied across.
22463 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22464 fctx.cdef_idx_grid.with(|g| {
22465 let mut g = g.borrow_mut();
22466 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22467 if cols > 0 && q_r * cols + q_c < g.len() {
22468 let idx = g[q_r * cols + q_c];
22469 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
22470 let i = (q_r + dr) * cols + q_c + dc;
22471 if q_c + dc < cols && i < g.len() {
22472 g[i] = idx;
22473 }
22474 }
22475 }
22476 });
22477 continue;
22478 }
22479 }
22480 if !sb128 {
22481 crate::restoration::read_lr(
22482 &mut dec,
22483 &mut cdfs,
22484 lr,
22485 &mut lr_grid,
22486 &mut lr_reference,
22487 sb_r * SB_MI,
22488 sb_c * SB_MI,
22489 SB_MI, fctx,
22490 );
22491 }
22492 fctx.cdef_transmitted.with(|c| c.set(false));
22493 let at = (sb_r as usize * 4, sb_c as usize * 4);
22494 let ctx = neighbours.partition_ctx(at, SB);
22495 let (has_cols, has_rows) = (
22496 sb_c * SB_MI + SB_MI / 2 < mi_cols,
22497 sb_r * SB_MI + SB_MI / 2 < mi_rows,
22498 );
22499 // Recomputed at this superblock's own half (spec
22500 // `decode_partition`): a full alphabet symbol when both halves are
22501 // inside the true frame, a single gathered bit when just one is
22502 // (the superblock cannot be left whole, so this is forced split),
22503 // and nothing at all (SPLIT inferred, no bits) when neither is —
22504 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
22505 // three-way write exactly.
22506 let part = if has_cols && has_rows {
22507 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
22508 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22509 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
22510 }
22511 p
22512 } else {
22513 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
22514 // the unmerged lane-golomb r1): the gathered bit IS the
22515 // partition -- libaom `ec_read_partition_impl` returns
22516 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
22517 // Forcing SPLIT desynced the last superblock row of every
22518 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
22519 // the first block of that row.
22520 match (has_cols, has_rows) {
22521 (true, false) => {
22522 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22523 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
22524 bump_edge32(4 + b.min(1) as usize);
22525 bump_edge_part(b.min(1) as usize);
22526 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22527 }
22528 (false, true) => {
22529 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22530 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
22531 bump_edge32(4 + b.min(1) as usize);
22532 bump_edge_part(b.min(1) as usize);
22533 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22534 }
22535 _ => {
22536 bump_edge_both_cut(2);
22537 PARTITION_SPLIT
22538 }
22539 }
22540 };
22541 match part {
22542 PARTITION_NONE => {
22543 decode_block(
22544 &mut dec,
22545 &mut cdfs,
22546 &mut neighbours,
22547 at,
22548 SB,
22549 TxbSet::Luma64,
22550 TxbSet::Chroma32,
22551 TX32,
22552 TX32,
22553 (&scan32, &scan32),
22554 false,
22555 &mut y,
22556 &mut u,
22557 &mut v,
22558 base_q_idx,
22559 enable_filter_intra,
22560 allow_screen_content_tools,
22561 allow_intrabc,
22562 &scan32,
22563 &scan16,
22564 &scan8,
22565 &scan4,
22566 tx_select,
22567 reduced_tx_set, fctx,
22568 )?;
22569 }
22570 PARTITION_SPLIT => {
22571 for q in 0..4 {
22572 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
22573 if r32 >= rows32 || c32 >= cols32 {
22574 continue;
22575 }
22576 let at32 = (r32 as usize * 2, c32 as usize * 2);
22577 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
22578 let (has_cols32, has_rows32) = (
22579 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
22580 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
22581 );
22582 let part32 = if has_cols32 && has_rows32 {
22583 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
22584 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22585 let (rng, _) = dec.debug_state();
22586 eprintln!(
22587 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
22588 r32 * BLOCK_MI,
22589 c32 * BLOCK_MI
22590 );
22591 }
22592 p
22593 } else {
22594 // lane-hgkf r1: the 32-level frame-edge bit is the
22595 // partition too (same libaom reader as the
22596 // superblock level above).
22597 match (has_cols32, has_rows32) {
22598 (true, false) => {
22599 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22600 let b = dec.symbol_fixed(&gather(
22601 &cdfs.partition_w32[ctx32],
22602 VERT_ALIKE,
22603 ));
22604 bump_edge32(b.min(1) as usize);
22605 bump_edge_part(2 + b.min(1) as usize);
22606 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22607 }
22608 (false, true) => {
22609 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22610 let b = dec.symbol_fixed(&gather(
22611 &cdfs.partition_w32[ctx32],
22612 HORZ_ALIKE,
22613 ));
22614 bump_edge32(b.min(1) as usize);
22615 bump_edge_part(2 + b.min(1) as usize);
22616 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22617 }
22618 _ => {
22619 bump_edge_both_cut(1);
22620 PARTITION_SPLIT
22621 }
22622 }
22623 };
22624 match part32 {
22625 PARTITION_NONE => {
22626 decode_block(
22627 &mut dec,
22628 &mut cdfs,
22629 &mut neighbours,
22630 at32,
22631 BLOCK,
22632 TxbSet::Luma32,
22633 TxbSet::Chroma16,
22634 TX32,
22635 TX16,
22636 (&scan32, &scan16),
22637 true,
22638 &mut y,
22639 &mut u,
22640 &mut v,
22641 base_q_idx,
22642 enable_filter_intra,
22643 allow_screen_content_tools,
22644 allow_intrabc,
22645 &scan32,
22646 &scan16,
22647 &scan8,
22648 &scan4,
22649 tx_select,
22650 reduced_tx_set, fctx,
22651 )?;
22652 }
22653 PARTITION_SPLIT => {
22654 for sub in 0..4 {
22655 let (sr, sc) =
22656 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
22657 if (sr as u32) * SUB_MI >= mi_rows
22658 || (sc as u32) * SUB_MI >= mi_cols
22659 {
22660 continue;
22661 }
22662 let (has_cols16, has_rows16) = (
22663 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
22664 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
22665 );
22666 let at16 = (sr, sc);
22667 let ctx16 = neighbours.partition_ctx(at16, SUB);
22668 if has_cols16 && has_rows16 {
22669 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
22670 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22671 eprintln!(
22672 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
22673 at16.0, at16.1
22674 );
22675 }
22676 if part16 == PARTITION_NONE {
22677 decode_block(
22678 &mut dec,
22679 &mut cdfs,
22680 &mut neighbours,
22681 at16,
22682 SUB,
22683 TxbSet::Luma16,
22684 TxbSet::Chroma8,
22685 TX16,
22686 TX8,
22687 (&scan16, &scan8),
22688 true,
22689 &mut y,
22690 &mut u,
22691 &mut v,
22692 base_q_idx,
22693 enable_filter_intra,
22694 allow_screen_content_tools,
22695 allow_intrabc,
22696 &scan32,
22697 &scan16,
22698 &scan8,
22699 &scan4,
22700 tx_select,
22701 reduced_tx_set, fctx,
22702 )?;
22703 continue;
22704 }
22705 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
22706 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
22707 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
22708 // `decode_partition` visit order (decodeframe.c):
22709 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
22710 // HORZ_B: top 16x8, BL 8x8, BR 8x8
22711 // VERT_A: TL 8x8, BL 8x8, right 8x16
22712 // VERT_B: left 8x16, TR 8x8, BR 8x8
22713 // The squares go through `decode_leaf8`, the strip through
22714 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
22715 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
22716 // used refuses the non-skip case at this size). Both writers keep
22717 // mi-granular mode/skip/palette records, so a later block's
22718 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
22719 // 16x16 cell.
22720 //
22721 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
22722 // top-right neighbour is the partition's own not-yet-decoded
22723 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
22724 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
22725 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
22726 let arm = part16 - PARTITION_HORZ_A;
22727 bump_ab16(arm);
22728 if part16 == PARTITION_VERT_B {
22729 hit!(VERT_B_INTRA_HITS);
22730 }
22731 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
22732 Some(crate::encode::Reach::vert_ab_partition())
22733 } else {
22734 None
22735 };
22736 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
22737 macro_rules! ab_leaf8 {
22738 ($mi:expr, $prev:expr) => {
22739 decode_leaf8(
22740 &mut dec,
22741 &mut cdfs,
22742 &mut neighbours,
22743 at16,
22744 $mi,
22745 (&scan8, &scan4),
22746 $prev,
22747 &mut y,
22748 &mut u,
22749 &mut v,
22750 base_q_idx,
22751 enable_filter_intra,
22752 allow_screen_content_tools,
22753 allow_intrabc,
22754 tx_select,
22755 reduced_tx_set, fctx,
22756 )?
22757 };
22758 }
22759 macro_rules! ab_strip {
22760 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
22761 decode_leaf_rect(
22762 &mut dec,
22763 &mut cdfs,
22764 &mut neighbours,
22765 at16,
22766 $mi,
22767 $bw,
22768 $bh,
22769 $prev,
22770 &mut y,
22771 &mut u,
22772 &mut v,
22773 enable_filter_intra,
22774 allow_screen_content_tools,
22775 base_q_idx,
22776 tx_select,
22777 reduced_tx_set, fctx,
22778 )?
22779 };
22780 }
22781 let tl = (mi_row0, mi_col0);
22782 let tr = (mi_row0, mi_col0 + 2);
22783 let bl = (mi_row0 + 2, mi_col0);
22784 let br = (mi_row0 + 2, mi_col0 + 2);
22785 let mut done: Vec<((usize, usize), usize)> = Vec::new();
22786 match part16 {
22787 PARTITION_HORZ_A => {
22788 let m_tl = ab_leaf8!(tl, done.last().copied());
22789 done.push((tl, m_tl));
22790 let m_tr = ab_leaf8!(tr, done.last().copied());
22791 done.push((tr, m_tr));
22792 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
22793 done.push((bl, m_bot));
22794 }
22795 PARTITION_HORZ_B => {
22796 let m_top = ab_strip!(tl, 16, 8, None);
22797 done.push((tl, m_top));
22798 let m_bl = ab_leaf8!(bl, done.last().copied());
22799 done.push((bl, m_bl));
22800 let m_br = ab_leaf8!(br, done.last().copied());
22801 done.push((br, m_br));
22802 }
22803 PARTITION_VERT_A => {
22804 let m_tl = ab_leaf8!(tl, done.last().copied());
22805 done.push((tl, m_tl));
22806 let m_bl = ab_leaf8!(bl, done.last().copied());
22807 done.push((bl, m_bl));
22808 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
22809 done.push((tr, m_right));
22810 }
22811 _ => {
22812 let m_left = ab_strip!(tl, 8, 16, None);
22813 done.push((tl, m_left));
22814 let m_tr = ab_leaf8!(tr, done.last().copied());
22815 done.push((tr, m_tr));
22816 let m_br = ab_leaf8!(br, done.last().copied());
22817 done.push((br, m_br));
22818 }
22819 }
22820 // Same coarse-slot write-back the real SPLIT path takes: the
22821 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
22822 // sub-block on the parent's bottom / right edge (the mi-exact map
22823 // above wins wherever it has an entry).
22824 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
22825 continue;
22826 }
22827 if part16 == PARTITION_HORZ {
22828 hit!(HORZ_VERT_INTRA_HITS);
22829 let (mi_row0, mi_col0) = (
22830 sr as u32 * SUB_MI,
22831 sc as u32 * SUB_MI,
22832 );
22833 let top = (mi_row0 as usize, mi_col0 as usize);
22834 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
22835 let mode_top = decode_leaf_rect(
22836 &mut dec,
22837 &mut cdfs,
22838 &mut neighbours,
22839 at16,
22840 top,
22841 16,
22842 8,
22843 None,
22844 &mut y,
22845 &mut u,
22846 &mut v,
22847 enable_filter_intra,
22848 allow_screen_content_tools,
22849 base_q_idx,
22850 tx_select,
22851 reduced_tx_set, fctx,
22852 )?;
22853 let mode_bot = decode_leaf_rect(
22854 &mut dec,
22855 &mut cdfs,
22856 &mut neighbours,
22857 at16,
22858 bot,
22859 16,
22860 8,
22861 Some((top, mode_top)),
22862 &mut y,
22863 &mut u,
22864 &mut v,
22865 enable_filter_intra,
22866 allow_screen_content_tools,
22867 base_q_idx,
22868 tx_select,
22869 reduced_tx_set, fctx,
22870 )?;
22871 neighbours.above_mode[sc] = mode_bot;
22872 neighbours.left_mode[sr] = mode_bot;
22873 continue;
22874 }
22875 if part16 == PARTITION_VERT {
22876 hit!(HORZ_VERT_INTRA_HITS);
22877 let (mi_row0, mi_col0) = (
22878 sr as u32 * SUB_MI,
22879 sc as u32 * SUB_MI,
22880 );
22881 let left = (mi_row0 as usize, mi_col0 as usize);
22882 let right = (mi_row0 as usize, mi_col0 as usize + 2);
22883 let mode_left = decode_leaf_rect(
22884 &mut dec,
22885 &mut cdfs,
22886 &mut neighbours,
22887 at16,
22888 left,
22889 8,
22890 16,
22891 None,
22892 &mut y,
22893 &mut u,
22894 &mut v,
22895 enable_filter_intra,
22896 allow_screen_content_tools,
22897 base_q_idx,
22898 tx_select,
22899 reduced_tx_set, fctx,
22900 )?;
22901 let mode_right = decode_leaf_rect(
22902 &mut dec,
22903 &mut cdfs,
22904 &mut neighbours,
22905 at16,
22906 right,
22907 8,
22908 16,
22909 Some((left, mode_left)),
22910 &mut y,
22911 &mut u,
22912 &mut v,
22913 enable_filter_intra,
22914 allow_screen_content_tools,
22915 base_q_idx,
22916 tx_select,
22917 reduced_tx_set, fctx,
22918 )?;
22919 neighbours.above_mode[sc] = mode_right;
22920 neighbours.left_mode[sr] = mode_right;
22921 continue;
22922 }
22923 if part16 == PARTITION_HORZ_4
22924 || part16 == PARTITION_VERT_4
22925 {
22926 decode_rect4_16(
22927 &mut dec,
22928 &mut cdfs,
22929 &mut neighbours,
22930 at16,
22931 part16 == PARTITION_HORZ_4,
22932 &mut y,
22933 &mut u,
22934 &mut v,
22935 enable_filter_intra,
22936 allow_screen_content_tools,
22937 base_q_idx,
22938 tx_select,
22939 reduced_tx_set, fctx,
22940 )?;
22941 continue;
22942 }
22943 // lane-r14 r2 (verifier note): every
22944 // one of the 10 symbols this CDF can
22945 // produce is handled above, so SPLIT
22946 // is the only value that reaches
22947 // here -- the refusal that used to
22948 // stand here was unreachable and is
22949 // gone from `refusal_inventory`.
22950 debug_assert_eq!(part16, PARTITION_SPLIT);
22951 // A real (non-straddle) SPLIT of a
22952 // whole 16x16 into four 8x8 leaves --
22953 // the same recursion the straddle
22954 // path below already runs when the
22955 // true frame edge forces it, just
22956 // over all four positions instead of
22957 // the one or two the edge leaves.
22958 let (mi_row0, mi_col0) =
22959 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22960 // Each 8x8 leaf's intra-mode context
22961 // must see its own siblings: the
22962 // bottom-left leaf's ABOVE neighbour
22963 // is leaf 0, not the previously
22964 // decoded leaf 1 (and the bottom-right
22965 // leaf's above is leaf 1, while
22966 // `prev_leaf` only ever carried the
22967 // immediately preceding one). The
22968 // coarse `above_mode`/`left_mode`
22969 // arrays hold one slot per 16x16, so
22970 // the sibling modes are swapped in
22971 // around each leaf call and restored
22972 // after; the loop tail writes the last
22973 // leaf's mode as before.
22974 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22975 for i in 0..4 {
22976 let (mr, mc) =
22977 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
22978 let leaf_mi = (mr as usize, mc as usize);
22979 let li = i as usize;
22980 let saved_modes =
22981 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22982 if li >= 2 {
22983 if let Some((below, _)) = sib_modes[li - 2] {
22984 neighbours.above_mode[sc] = below;
22985 }
22986 }
22987 if li % 2 == 1 {
22988 if let Some((_, right)) = sib_modes[li - 1] {
22989 neighbours.left_mode[sr] = right;
22990 }
22991 }
22992 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22993 let part8 =
22994 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22995 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22996 eprintln!(
22997 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
22998 );
22999 }
23000 let leaf_mode = if part8 == PARTITION_NONE {
23001 decode_leaf8(
23002 &mut dec,
23003 &mut cdfs,
23004 &mut neighbours,
23005 at16,
23006 leaf_mi,
23007 (&scan8, &scan4),
23008 None,
23009 &mut y,
23010 &mut u,
23011 &mut v,
23012 base_q_idx,
23013 enable_filter_intra,
23014 allow_screen_content_tools,
23015 allow_intrabc,
23016 tx_select,
23017 reduced_tx_set, fctx,
23018 ).map(|m| (m, m))?
23019 } else if part8 == PARTITION_SPLIT {
23020 decode_leaf_split4(
23021 &mut dec,
23022 &mut cdfs,
23023 &mut neighbours,
23024 at16,
23025 leaf_mi,
23026 &scan4,
23027 None,
23028 &mut y,
23029 &mut u,
23030 &mut v,
23031 base_q_idx,
23032 enable_filter_intra,
23033 allow_intrabc,
23034 reduced_tx_set, fctx,
23035 )?
23036 } else if part8 == PARTITION_HORZ
23037 || part8 == PARTITION_VERT
23038 {
23039 decode_leaf_rect8(
23040 &mut dec,
23041 &mut cdfs,
23042 &mut neighbours,
23043 at16,
23044 leaf_mi,
23045 part8 == PARTITION_VERT,
23046 &scan4,
23047 &mut y,
23048 &mut u,
23049 &mut v,
23050 base_q_idx,
23051 enable_filter_intra,
23052 allow_intrabc,
23053 tx_select,
23054 reduced_tx_set, fctx,
23055 )?
23056 } else {
23057 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
23058 };
23059 neighbours.above_mode[sc] = saved_modes.0;
23060 neighbours.left_mode[sr] = saved_modes.1;
23061 sib_modes[li] = Some(leaf_mode);
23062 }
23063 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
23064 neighbours.above_mode[sc] = below;
23065 }
23066 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
23067 neighbours.left_mode[sr] = right;
23068 }
23069 continue;
23070 }
23071 // The true edge falls inside this 16x16
23072 // leaf itself (mod-32==8 target sizes,
23073 // lane-av1-rect): one axis only -- an 8x8
23074 // leaf never itself straddles, so the
23075 // block splits cleanly along whichever
23076 // axis is short.
23077 // lane-edgeboth r1: when the true frame
23078 // edge cuts BOTH axes libaom's
23079 // `decode_partition` takes
23080 // `else if (!has_rows && !has_cols)
23081 // partition = PARTITION_SPLIT;` -- no
23082 // symbol of any kind is read, and the four
23083 // 8x8 children are then visited by the
23084 // same loop below, whose
23085 // `mr < mi_rows && mc < mi_cols` filter IS
23086 // libaom's own
23087 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
23088 // early return, so the three out-of-frame
23089 // quadrants get no neighbour or tx-grid
23090 // write.
23091 if !has_cols16 && !has_rows16 {
23092 bump_edge_both_cut(0);
23093 } else {
23094 // lane-golomb r1 (class
23095 // `parsed-then-discarded`): the gathered
23096 // bit IS the partition -- 0 names
23097 // PARTITION_HORZ (resp. VERT), only 1 is
23098 // SPLIT (libaom `ec_read_partition_impl`).
23099 // This path can only walk the four SPLIT
23100 // leaves, so a 0 refuses by name instead
23101 // of desyncing.
23102 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
23103 let edge_split = if has_cols16 {
23104 dec.symbol_fixed(&gather(
23105 &cdfs.partition_w16[ctx16],
23106 VERT_ALIKE,
23107 ))
23108 } else {
23109 dec.symbol_fixed(&gather(
23110 &cdfs.partition_w16[ctx16],
23111 HORZ_ALIKE,
23112 ))
23113 };
23114 // lane-hgkf r1: slots 2/3 of
23115 // [`EDGE_PART_HITS`], the gate's proof the
23116 // non-SPLIT edge arm actually decoded.
23117 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
23118 if edge_split == 0 {
23119 // lane-oddh r1: the strip IS decodable
23120 // -- libaom's `decode_partition` codes
23121 // only the FIRST half of an edge
23122 // HORZ/VERT (the second call is
23123 // guarded by the same has_rows/
23124 // has_cols test that made the
23125 // partition non-square), so one
23126 // 16x8 (resp. 8x16) strip covers the
23127 // whole visible band of a frame whose
23128 // height (resp. width) is 8 mod 16 --
23129 // the user's 3840x1608 film.
23130 hit!(HORZ_VERT_INTRA_HITS);
23131 hit!(EDGE_RECT_STRIP_HITS);
23132 let (mi_row0, mi_col0) =
23133 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23134 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
23135 let mode = decode_leaf_rect(
23136 &mut dec,
23137 &mut cdfs,
23138 &mut neighbours,
23139 at16,
23140 (mi_row0 as usize, mi_col0 as usize),
23141 bw,
23142 bh,
23143 None,
23144 &mut y,
23145 &mut u,
23146 &mut v,
23147 enable_filter_intra,
23148 allow_screen_content_tools,
23149 base_q_idx,
23150 tx_select,
23151 reduced_tx_set, fctx,
23152 )?;
23153 neighbours.above_mode[sc] = mode;
23154 neighbours.left_mode[sr] = mode;
23155 continue;
23156 }
23157 }
23158 let (mi_row0, mi_col0) =
23159 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23160 let leaf_positions: Vec<(u32, u32)> = (0..4)
23161 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
23162 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
23163 .collect();
23164 // See the sibling-mode note in the clean
23165 // SPLIT path above.
23166 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
23167 for (mr, mc) in leaf_positions {
23168 let leaf_mi = (mr as usize, mc as usize);
23169 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
23170 as usize;
23171 let saved_modes =
23172 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
23173 if li >= 2 {
23174 if let Some((below, _)) = sib_modes[li - 2] {
23175 neighbours.above_mode[sc] = below;
23176 }
23177 }
23178 if li % 2 == 1 {
23179 if let Some((_, right)) = sib_modes[li - 1] {
23180 neighbours.left_mode[sr] = right;
23181 }
23182 }
23183 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
23184 let pre8 = dec.debug_state().0;
23185 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
23186 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23187 eprintln!(
23188 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
23189 );
23190 }
23191 let leaf_mode = if part8 == PARTITION_NONE {
23192 decode_leaf8(
23193 &mut dec,
23194 &mut cdfs,
23195 &mut neighbours,
23196 at16,
23197 leaf_mi,
23198 (&scan8, &scan4),
23199 None,
23200 &mut y,
23201 &mut u,
23202 &mut v,
23203 base_q_idx,
23204 enable_filter_intra,
23205 allow_screen_content_tools,
23206 allow_intrabc,
23207 tx_select,
23208 reduced_tx_set, fctx,
23209 ).map(|m| (m, m))?
23210 } else if part8 == PARTITION_SPLIT {
23211 decode_leaf_split4(
23212 &mut dec,
23213 &mut cdfs,
23214 &mut neighbours,
23215 at16,
23216 leaf_mi,
23217 &scan4,
23218 None,
23219 &mut y,
23220 &mut u,
23221 &mut v,
23222 base_q_idx,
23223 enable_filter_intra,
23224 allow_intrabc,
23225 reduced_tx_set, fctx,
23226 )?
23227 } else if part8 == PARTITION_HORZ
23228 || part8 == PARTITION_VERT
23229 {
23230 decode_leaf_rect8(
23231 &mut dec,
23232 &mut cdfs,
23233 &mut neighbours,
23234 at16,
23235 leaf_mi,
23236 part8 == PARTITION_VERT,
23237 &scan4,
23238 &mut y,
23239 &mut u,
23240 &mut v,
23241 base_q_idx,
23242 enable_filter_intra,
23243 allow_intrabc,
23244 tx_select,
23245 reduced_tx_set, fctx,
23246 )?
23247 } else {
23248 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
23249 };
23250 neighbours.above_mode[sc] = saved_modes.0;
23251 neighbours.left_mode[sr] = saved_modes.1;
23252 sib_modes[li] = Some(leaf_mode);
23253 }
23254 // `record()`'s `above_mode`/`left_mode`
23255 // write is a no-op at an 8x8 leaf's own
23256 // side, so force the write once the whole
23257 // 16x16 slot's leaves are done, from the
23258 // last leaf (mirrors the writer's r15
23259 // fix).
23260 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
23261 neighbours.above_mode[sc] = below;
23262 }
23263 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
23264 neighbours.left_mode[sr] = right;
23265 }
23266 }
23267 }
23268 PARTITION_HORZ => {
23269 // lane-intradisp r1: two true 32x16 strips.
23270 decode_block_rect(
23271 &mut dec,
23272 &mut cdfs,
23273 &mut neighbours,
23274 at32,
23275 32,
23276 16,
23277 &mut y,
23278 &mut u,
23279 &mut v,
23280 enable_filter_intra,
23281 allow_screen_content_tools,
23282 base_q_idx,
23283 tx_select,
23284 reduced_tx_set, fctx,
23285 )?;
23286 if !has_rows32 {
23287 bump_edge32(2);
23288 }
23289 // lane-hgkf r1: at the frame edge only the first half of the strip is
23290 // coded (libaom `decode_partition` guards the second half with the same
23291 // test that made this partition non-square).
23292 if has_rows32 {
23293 decode_block_rect(
23294 &mut dec,
23295 &mut cdfs,
23296 &mut neighbours,
23297 (at32.0 + 1, at32.1),
23298 32,
23299 16,
23300 &mut y,
23301 &mut u,
23302 &mut v,
23303 enable_filter_intra,
23304 allow_screen_content_tools,
23305 base_q_idx,
23306 tx_select,
23307 reduced_tx_set, fctx,
23308 )?;
23309 }
23310 }
23311 PARTITION_VERT => {
23312 // lane-intradisp r1: mirror of PARTITION_HORZ
23313 // above with width/height swapped.
23314 decode_block_rect(
23315 &mut dec,
23316 &mut cdfs,
23317 &mut neighbours,
23318 at32,
23319 16,
23320 32,
23321 &mut y,
23322 &mut u,
23323 &mut v,
23324 enable_filter_intra,
23325 allow_screen_content_tools,
23326 base_q_idx,
23327 tx_select,
23328 reduced_tx_set, fctx,
23329 )?;
23330 if !has_cols32 {
23331 bump_edge32(3);
23332 }
23333 // lane-hgkf r1: at the frame edge only the first half of the strip is
23334 // coded (libaom `decode_partition` guards the second half with the same
23335 // test that made this partition non-square).
23336 if has_cols32 {
23337 decode_block_rect(
23338 &mut dec,
23339 &mut cdfs,
23340 &mut neighbours,
23341 (at32.0, at32.1 + 1),
23342 16,
23343 32,
23344 &mut y,
23345 &mut u,
23346 &mut v,
23347 enable_filter_intra,
23348 allow_screen_content_tools,
23349 base_q_idx,
23350 tx_select,
23351 reduced_tx_set, fctx,
23352 )?;
23353 }
23354 }
23355 PARTITION_HORZ_A => {
23356 // lane-part32 r1: two 16x16 squares on top +
23357 // a true 32x16 strip below (mirrors
23358 // decode_inter_block's cd6cb6d HORZ_A: TL,
23359 // TR, bottom strip).
23360 hit!(INTRA_HORZ_A_HITS);
23361 decode_block(
23362 &mut dec,
23363 &mut cdfs,
23364 &mut neighbours,
23365 at32,
23366 SUB,
23367 TxbSet::Luma16,
23368 TxbSet::Chroma8,
23369 TX16,
23370 TX8,
23371 (&scan16, &scan8),
23372 true,
23373 &mut y,
23374 &mut u,
23375 &mut v,
23376 base_q_idx,
23377 enable_filter_intra,
23378 allow_screen_content_tools,
23379 allow_intrabc,
23380 &scan32,
23381 &scan16,
23382 &scan8,
23383 &scan4,
23384 tx_select,
23385 reduced_tx_set, fctx,
23386 )?;
23387 decode_block(
23388 &mut dec,
23389 &mut cdfs,
23390 &mut neighbours,
23391 (at32.0, at32.1 + 1),
23392 SUB,
23393 TxbSet::Luma16,
23394 TxbSet::Chroma8,
23395 TX16,
23396 TX8,
23397 (&scan16, &scan8),
23398 true,
23399 &mut y,
23400 &mut u,
23401 &mut v,
23402 base_q_idx,
23403 enable_filter_intra,
23404 allow_screen_content_tools,
23405 allow_intrabc,
23406 &scan32,
23407 &scan16,
23408 &scan8,
23409 &scan4,
23410 tx_select,
23411 reduced_tx_set, fctx,
23412 )?;
23413 decode_block_rect(
23414 &mut dec,
23415 &mut cdfs,
23416 &mut neighbours,
23417 (at32.0 + 1, at32.1),
23418 32,
23419 16,
23420 &mut y,
23421 &mut u,
23422 &mut v,
23423 enable_filter_intra,
23424 allow_screen_content_tools,
23425 base_q_idx,
23426 tx_select,
23427 reduced_tx_set, fctx,
23428 )?;
23429 }
23430 PARTITION_HORZ_B => {
23431 // lane-part32 r1: a true 32x16 strip on top +
23432 // two 16x16 squares below (mirrors HORZ_A
23433 // with the strip/squares order flipped, same
23434 // shape as libaom decode_partition's HORZ_B).
23435 hit!(INTRA_HORZ_B_HITS);
23436 decode_block_rect(
23437 &mut dec,
23438 &mut cdfs,
23439 &mut neighbours,
23440 at32,
23441 32,
23442 16,
23443 &mut y,
23444 &mut u,
23445 &mut v,
23446 enable_filter_intra,
23447 allow_screen_content_tools,
23448 base_q_idx,
23449 tx_select,
23450 reduced_tx_set, fctx,
23451 )?;
23452 decode_block(
23453 &mut dec,
23454 &mut cdfs,
23455 &mut neighbours,
23456 (at32.0 + 1, at32.1),
23457 SUB,
23458 TxbSet::Luma16,
23459 TxbSet::Chroma8,
23460 TX16,
23461 TX8,
23462 (&scan16, &scan8),
23463 true,
23464 &mut y,
23465 &mut u,
23466 &mut v,
23467 base_q_idx,
23468 enable_filter_intra,
23469 allow_screen_content_tools,
23470 allow_intrabc,
23471 &scan32,
23472 &scan16,
23473 &scan8,
23474 &scan4,
23475 tx_select,
23476 reduced_tx_set, fctx,
23477 )?;
23478 decode_block(
23479 &mut dec,
23480 &mut cdfs,
23481 &mut neighbours,
23482 (at32.0 + 1, at32.1 + 1),
23483 SUB,
23484 TxbSet::Luma16,
23485 TxbSet::Chroma8,
23486 TX16,
23487 TX8,
23488 (&scan16, &scan8),
23489 true,
23490 &mut y,
23491 &mut u,
23492 &mut v,
23493 base_q_idx,
23494

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