forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust379.9 MiB35bdf35Tahinli2 months ago3757 commits

decode.rs24024 lines, 2.5 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, MAX_SEGMENTS,
27 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
28};
29use ec_core::{Error, Result};
30
31// lane-av112bit: the 12-bit warp refusal that used to stand at all three
32// warp decision sites (compound, 16x16+, 8x8 leaf) was an inline literal
33// (refusal_inventory.rs extracts refusal strings from the decode source);
34// it named the real gap: warp's reduce bits inherited the 12-bit
35// `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86) and no
36// witness existed.
37// lane-av112bitw lifted it from all three sites: `warp::warp_round_0`
38// implements the bump (`round_0 += max(bd + FILTER_BITS - round_0 - 14, 0)`,
39// 5 at 12 bits), and the single-ref witness plus the rotating-mandelbrot
40// compound-warp witness are both byte-exact vs ffmpeg. Compound inter
41// itself was lifted by lane-av112bitc before that (the combines absorb the
42// CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`).
43
44/// Per-frame decode state, one instance per decoded stream (lane-thread1).
45///
46/// Every field here used to be a `thread_local!` static, which made a decode a
47/// function of the calling THREAD's history rather than of the bitstream alone
48/// -- and made frame-parallel decoding impossible, since a worker thread sees
49/// empty state. The cells keep exactly the interior mutability the statics
50/// had, so every read/write site is byte-identical; what changes is WHERE the
51/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
52/// the decode call graph.
53///
54/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
55/// exactly one thread's decode, and is never shared between workers.
56/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
57/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
58/// (pre-restoration) samples, at the decoder's own plane stride.
59pub(crate) struct FilterStages {
60 /// Post-deblock, pre-CDEF planes (Y, U, V).
61 pub(crate) deblocked: [Vec<u16>; 3],
62 /// Post-CDEF, pre-restoration planes (Y, U, V).
63 pub(crate) cdefed: [Vec<u16>; 3],
64 /// Each plane's stride (and so its width in the buffers above).
65 pub(crate) stride: [usize; 3],
66}
67
68/// Takes whatever the last capturing decode left (see
69/// [`FrameCtx::capture_stages`]).
70#[allow(dead_code)] // read from the encoder's loop restoration search
71pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
72 fctx.stages.borrow_mut().take()
73}
74
75pub(crate) struct FrameCtx {
76 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
77 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
78 /// restoration search (spec 7.17 reads both: the stripe interior from
79 /// the post-CDEF plane, its 3-row border from the post-deblock one).
80 /// Off for every decode but that search, and off it costs one bool read
81 /// per frame and not a single copy.
82 pub(crate) capture_stages: std::cell::Cell<bool>,
83 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
84 pub(crate) sb128_flag: std::cell::Cell<bool>,
85 /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
86 /// motion compensation of THIS frame runs, already resolved to a kernel.
87 /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
88 /// trial and recon could only ever build a REGULAR prediction whatever
89 /// the frame header said; it lives here (and is copied by
90 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
91 /// kernel the frame header wrote instead of the default.
92 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
93 /// lane-lossless: this frame's per-segment lossless table -- libaom's
94 /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header
95 /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero
96 /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`).
97 /// Every block-decoder rule that reads [`decode::lossless`] resolves it
98 /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard
99 /// transform on every plane, the dropped `tx_type` symbol and the narrowed
100 /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`),
101 /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow
102 /// the SEGMENT, so a frame whose segments disagree codes lossless and
103 /// lossy blocks side by side.
104 pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>,
105 /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2).
106 /// When set, the tile reader must not adapt any CDF it reads, or its
107 /// tables drift away from the encoder's and the frame desyncs mid-tile
108 /// (libaom: `allow_update_cdf = allow_update_cdf &&
109 /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`).
110 pub(crate) disable_cdf_update: std::cell::Cell<bool>,
111 pub(crate) cdef_bits: std::cell::Cell<u8>,
112 pub(crate) bit_depth: std::cell::Cell<u8>,
113 /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec
114 /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as
115 /// `av1_num_planes(cm)` and every chroma read site is guarded by
116 /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`,
117 /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes
118 /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma
119 /// coefficients on any block. Set once per frame from the sequence header
120 /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread
121 /// that last saw a 4:2:0 one never inherits the wrong plane count.
122 pub(crate) mono_chrome: std::cell::Cell<bool>,
123 /// lane-av1-444: sequence subsampling_x/y. 1,1 is 4:2:0; 0,0 is 4:4:4.
124 pub(crate) subsampling_x: std::cell::Cell<u8>,
125 pub(crate) subsampling_y: std::cell::Cell<u8>,
126 pub(crate) superres: std::cell::Cell<(u32, u32)>,
127 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
128 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
129 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
130 pub(crate) delta_q_present: std::cell::Cell<bool>,
131 pub(crate) delta_q_res: std::cell::Cell<i32>,
132 pub(crate) current_q_idx: std::cell::Cell<i32>,
133 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
134 /// lane-av1-qmatrix: this frame's quantisation-matrix LEVEL per plane,
135 /// straight from spec 5.9.12's `qm_y`/`qm_u`/`qm_v` (the parsed 4-bit
136 /// value IS the table level -- libaom `quant_params->qmatrix_level_y/u/v`,
137 /// decodeframe.c:1902-1917; the `aom_get_qmlevel` formula that maps
138 /// base_q_idx onto a level is encoder-side only). 15 is libaom's flat
139 /// sentinel (`NUM_QM_LEVELS - 1`, stored as NULL tables) and the default
140 /// every `using_qmatrix == 0` frame keeps, so a matrix-free stream
141 /// selects no matrix.
142 pub(crate) qm_levels: std::cell::Cell<[u8; 3]>,
143 pub(crate) delta_lf_present: std::cell::Cell<bool>,
144 pub(crate) delta_lf_res: std::cell::Cell<i32>,
145 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
146 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
147 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
148 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
149 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
150 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
151 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
152 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
153 pub(crate) cur_segment_id: std::cell::Cell<u8>,
154 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
155 pub(crate) tx_select_inter: std::cell::Cell<bool>,
156 /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only
157 /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame
158 /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame
159 /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this
160 /// decoder's inter-side publishing was wired. See
161 /// [`Neighbours::fill_lf_grid_rect`]'s band publish.
162 pub(crate) intra_only: std::cell::Cell<bool>,
163 /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame
164 /// (intra included). [`Self::tx_select_inter`] cannot stand in for it:
165 /// an intrabc block rides an INTRA frame, but libaom still reads its
166 /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`.
167 pub(crate) tx_select_frame: std::cell::Cell<bool>,
168 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
169 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
170 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
171 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
172 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
173 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
174 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
175 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
176 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
177 pub(crate) inter_last_mc:
178 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
179 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
180 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
181 pub(crate) reach_sb_px: std::cell::Cell<usize>,
182 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
183 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
184 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
185 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
186 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
187 /// so a superblock's records do not regrow the vector from nothing.
188 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
189 /// lane-recoparse: the coefficient grids of the recorded ops above, one
190 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
191 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
192 /// before the op is published, read only by whoever replays that op, and
193 /// handed over WITH the ops at every drain point ([`wave_submit`],
194 /// [`flush_recon`]), so offsets are always relative to the live arena.
195 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
196 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
197 /// path (a submitted job's arena travels to its worker instead).
198 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
199 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
200 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
201 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
202 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
203 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
204 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
205 /// `None` while the queue is in use (wavefront workers) and outside a
206 /// tile. See [`push_op`].
207 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
208 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
209 /// writes are handed to, at more than one reconstruction thread.
210 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
211 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
212 /// thread last handed a superblock to the wavefront.
213 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
214}
215
216impl std::fmt::Debug for FrameCtx {
217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 f.write_str("FrameCtx")
219 }
220}
221
222impl FrameCtx {
223 /// A fresh context, every field at the default its thread-local
224 /// predecessor was born with.
225 pub(crate) fn new() -> Self {
226 Self {
227 // A DECODER context is seeded from the stream alone: every real
228 // decode overwrites this from the parsed sequence header
229 // (`set_sb128`, stream.rs). The encoder's own contexts start at
230 // the size this process encodes -- see [`FrameCtx::for_encoder`].
231 sb128_flag: std::cell::Cell::new(false),
232 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
233 lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]),
234 disable_cdf_update: std::cell::Cell::new(false),
235 cdef_bits: std::cell::Cell::new(0),
236 bit_depth: std::cell::Cell::new(8),
237 mono_chrome: std::cell::Cell::new(false),
238 subsampling_x: std::cell::Cell::new(1),
239 subsampling_y: std::cell::Cell::new(1),
240 superres: std::cell::Cell::new((0, 8)),
241 cdef_transmitted: std::cell::Cell::new(false),
242 cdef_sb_cols: std::cell::Cell::new(0),
243 capture_stages: std::cell::Cell::new(false),
244 stages: std::cell::RefCell::new(None),
245 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
246 delta_q_present: std::cell::Cell::new(false),
247 delta_q_res: std::cell::Cell::new(1),
248 current_q_idx: std::cell::Cell::new(0),
249 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
250 y_dc: 0,
251 u_dc: 0,
252 u_ac: 0,
253 v_dc: 0,
254 v_ac: 0,
255 }),
256 qm_levels: std::cell::Cell::new([crate::qm::NUM_QM_LEVELS as u8 - 1; 3]),
257 delta_lf_present: std::cell::Cell::new(false),
258 delta_lf_res: std::cell::Cell::new(1),
259 delta_lf_multi: std::cell::Cell::new(false),
260 current_delta_lf: std::cell::Cell::new([0; 4]),
261 seg: std::cell::RefCell::new(SegmentationParams::default()),
262 seg_ids: std::cell::RefCell::new(Vec::new()),
263 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
264 seg_mi_dims: std::cell::Cell::new((0, 0)),
265 above_seg_pred: std::cell::RefCell::new(Vec::new()),
266 left_seg_pred: std::cell::RefCell::new(Vec::new()),
267 cur_segment_id: std::cell::Cell::new(0),
268 seg_tile_origin: std::cell::Cell::new((0, 0)),
269 tx_select_inter: std::cell::Cell::new(false),
270 tx_select_frame: std::cell::Cell::new(false),
271 intra_only: std::cell::Cell::new(false),
272 reduced_tx_set_inter: std::cell::Cell::new(false),
273 enable_filter_intra_inter: std::cell::Cell::new(false),
274 palette_pred: std::cell::RefCell::new(None),
275 intrabc_mi_grid: std::cell::RefCell::new(None),
276 intrabc_dv: std::cell::Cell::new(None),
277 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
278 intrabc_chroma_tx: std::cell::Cell::new(None),
279 intra_in_inter_mode: std::cell::Cell::new(None),
280 inter_strip_chroma: std::cell::Cell::new(None),
281 inter_last_mc: std::cell::Cell::new(None),
282 enable_edge_filter: std::cell::Cell::new(false),
283 last_frame_wide_margin: std::cell::RefCell::new(None),
284 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
285 grain_bit_depth: std::cell::Cell::new(8),
286 recon_ops: std::cell::RefCell::new(Vec::new()),
287 recon_spare: std::cell::RefCell::new(Vec::new()),
288 coeff_arena: std::cell::RefCell::new(Vec::new()),
289 coeff_spare: std::cell::RefCell::new(Vec::new()),
290 pred_arena: std::cell::RefCell::new(Vec::new()),
291 pred_spare: std::cell::RefCell::new(Vec::new()),
292 recon_planes: std::cell::Cell::new(None),
293 wave: std::cell::RefCell::new(None),
294 wave_mark: std::cell::Cell::new(None),
295 }
296 }
297
298 /// A context for the ENCODER's own trial decodes: it starts at the
299 /// superblock size this process encodes (`crate::encode::sb128_on`) so
300 /// the mode search's `Reach` and the filter search's internal decodes
301 /// agree with the tile writer. A decoder never reads that knob -- doing
302 /// so coupled every decode to the encoder's process-global and raced the
303 /// 128-superblock decode gates against the encoder witness.
304 pub(crate) fn for_encoder() -> Self {
305 let ctx = Self::new();
306 let on = crate::encode::sb128_on();
307 ctx.sb128_flag.set(on);
308 ctx.reach_sb_px
309 .set(if on { 128 } else { crate::encode::SUPERBLOCK });
310 ctx
311 }
312}
313
314/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
315/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
316/// `with` still wins for the scratch pools and gate counters that stay
317/// thread-local.
318pub(crate) trait WithRef {
319 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
320 f(self)
321 }
322}
323impl<T: ?Sized> WithRef for T {}
324
325/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
326///
327/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
328/// and the post-decode filter chain reads exactly these fields: the bit depth
329/// (every kernel's clamp and threshold shift), the segmentation table
330/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
331/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
332/// default -- a field that turns out to be read after all shows up as a hash
333/// mismatch in
334/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
335pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
336 let out = FrameCtx::new();
337 out.bit_depth.set(fctx.bit_depth.get());
338 out.mono_chrome.set(fctx.mono_chrome.get());
339 out.subsampling_x.set(fctx.subsampling_x.get());
340 out.subsampling_y.set(fctx.subsampling_y.get());
341 out.interp_filter.set(fctx.interp_filter.get());
342 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
343 out.superres.set(fctx.superres.get());
344 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
345 out.seg.replace(fctx.seg.borrow().clone());
346 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
347 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
348 // worker (`encode::search_tiles`) gets its context from here, so dropping
349 // it made every worker search at 64 while the calling thread searched at
350 // 128 -- the bytes a frame came out as then depended on the tile thread
351 // count under `EC_AV1_SB128`.
352 out.sb128_flag.set(fctx.sb128_flag.get());
353 out.reach_sb_px.set(fctx.reach_sb_px.get());
354 out
355}
356
357use crate::cdf;
358use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
359use crate::encode::{Picture, Reach};
360use crate::intra::predict;
361use crate::mc;
362use crate::msac::SymbolDecoder;
363use crate::mvstack::{
364 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
365 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
366 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx, single_ref_p1_ctx,
367 single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
368 uni_comp_ref_p1_ctx,
369};
370use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
371use crate::transform::{TxType, dequant_and_inverse_typed_wh};
372
373const PARTITION_NONE: usize = 0;
374const PARTITION_HORZ: usize = 1;
375const PARTITION_VERT: usize = 2;
376const PARTITION_SPLIT: usize = 3;
377const PARTITION_HORZ_A: usize = 4;
378const PARTITION_HORZ_B: usize = 5;
379const PARTITION_VERT_A: usize = 6;
380const PARTITION_VERT_B: usize = 7;
381const PARTITION_HORZ_4: usize = 8;
382const PARTITION_VERT_4: usize = 9;
383const SB_MI: u32 = 16;
384const BLOCK_MI: u32 = 8;
385
386// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
387// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
388// superblock's own top-left mi?", the loop-restoration read's unit span, the
389// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
390// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
391// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
392// inside a 128 superblock).
393thread_local! {
394 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
395 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
396 /// prints gigabytes otherwise). Unset = every frame, as before.
397 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
398 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
399}
400
401/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
402/// that frame's DECODE-order index.
403pub fn set_coeff_trace_frame(idx: usize) {
404 COEFF_TRACE_FRAME.with(|c| {
405 if c.get().is_none() {
406 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
407 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
408 // unset: keep tracing every frame, as before this rung existed
409 Err(_) => usize::MAX - 1,
410 };
411 c.set(Some(want));
412 }
413 });
414 COEFF_TRACE_CUR.with(|c| c.set(idx));
415 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
416 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
417 }
418}
419
420pub(crate) fn coeff_trace_on() -> bool {
421 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
422 return false;
423 }
424 match COEFF_TRACE_FRAME.with(|c| c.get()) {
425 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
426 // env var unset: trace every frame.
427 None => true,
428 Some(w) if w >= usize::MAX - 1 => true,
429 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
430 }
431}
432
433/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
434pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
435 fctx.sb128_flag.with(|c| c.set(v));
436 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
437}
438
439/// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame
440/// from `stream.rs`).
441pub(crate) fn set_lossless_per_seg(table: [bool; MAX_SEGMENTS], fctx: &crate::decode::FrameCtx) {
442 fctx.lossless_per_seg.with(|c| c.set(table));
443}
444
445/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`.
446/// The table is computed once per frame (libaom `decodeframe.c:5205`:
447/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the
448/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule
449/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the
450/// BLOCK's own segment id, which the spec-order `segment_id` read sets before
451/// any mode/transform symbol of the block. A frame whose segments disagree
452/// codes TX_4X4/WHT blocks and normal blocks side by side.
453pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
454 let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get()));
455 fctx.lossless_per_seg.with(|c| c.get())[seg_id]
456}
457
458/// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
459/// `stream.rs`).
460pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) {
461 fctx.disable_cdf_update.with(|c| c.set(v));
462}
463
464/// This frame's `disable_cdf_update`, for the tile readers --
465/// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update).
466pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
467 fctx.disable_cdf_update.with(|c| c.get())
468}
469
470/// The transform side a block of `side` pixels codes: its own (capped at the
471/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's
472/// `read_tx_size` returns TX_4X4 before it looks at anything else
473/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
474/// TX_4X4;`).
475pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
476 if lossless(fctx) { 4 } else { px }
477}
478
479/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
480/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block
481/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
482/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
483/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
484pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
485 if lossless(fctx) {
486 // `is_cfl_allowed`: at lossless CfL is available only when the
487 // partition size equals the transform size -- the CHROMA plane block
488 // must be a single TX_4X4. True for an 8x8 partition at 4:2:0 (its
489 // plane block is 4x4) and for 4x4 partitions; FALSE for an 8x8
490 // partition at 4:4:4, whose plane block is 8x8 -- that partition
491 // reads the 13-symbol uv_mode CDF, and reading the CFL alphabet
492 // there desynced the tile from the leaf's own uv_mode symbol (class
493 // `wrong-alphabet-same-value`).
494 (bw >> ss_x(fctx)).max(4) == 4 && (bh >> ss_y(fctx)).max(4) == 4
495 } else {
496 bw <= 32 && bh <= 32
497 }
498}
499
500fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
501 fctx.sb128_flag.with(|c| c.get())
502}
503
504/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
505pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
506 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
507}
508
509// How many real 128-level partition symbols this decoder has read, and how
510// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
511// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
512thread_local! {
513 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
514 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
515 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
516}
517
518/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
519/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
520/// 5.11.4), which this decoder used to read and throw away.
521#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
522pub(crate) fn part128_gathered_symbols() -> usize {
523 PART128_GATHERED_SYMBOLS.with(|c| c.get())
524}
525
526/// Current value of [`PART128_SYMBOLS`].
527#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
528pub(crate) fn part128_symbols() -> usize {
529 PART128_SYMBOLS.with(|c| c.get())
530}
531
532/// Current value of [`PART128_SPLIT_HITS`].
533#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
534pub(crate) fn part128_split_hits() -> usize {
535 PART128_SPLIT_HITS.with(|c| c.get())
536}
537
538/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
539/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
540/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
541/// the 64/32 levels sum 6.
542pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
543 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
544 [32768 - split, 32768, 0]
545}
546
547/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
548pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
549pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
550
551// How many `use_filter_intra` symbols this decoder has read as `1`, across
552// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
553// tests read (before/after, not the absolute value) to prove a stream
554// actually exercised the filter-intra predictor rather than silently
555// skipping it.
556thread_local! {
557 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
558 const { std::cell::Cell::new(0) };
559}
560
561/// Current value of [`FILTER_INTRA_HITS`].
562#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
563pub(crate) fn filter_intra_hits() -> usize {
564 FILTER_INTRA_HITS.with(|c| c.get())
565}
566
567// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
568// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
569// `read_filter_intra_mode_info` call), which no gate exercised before this
570// round -- every inter gate recipe passed `--enable-filter-intra=0`.
571thread_local! {
572 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
573 const { std::cell::Cell::new(0) };
574}
575
576/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
577#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
578pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
579 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
580}
581
582// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
583// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
584// arms refused a nonzero luma delta before this round, and no inter gate
585// enabled `--enable-angle-delta` (aomenc's own default is 1).
586thread_local! {
587 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
588 const { std::cell::Cell::new(0) };
589 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
590 const { std::cell::Cell::new(0) };
591}
592
593/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
595pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
596 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
597}
598
599/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
601pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
602 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
603}
604
605// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
606// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
607// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
608// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
609thread_local! {
610 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
611 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
612 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
613}
614
615thread_local! {
616 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
617}
618
619/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
620/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
621#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
622pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
623 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
624}
625
626/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
627/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
629pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
630 (
631 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
632 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
633 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
634 )
635}
636
637// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
638// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
639// frame-level flag through the recursive block decode -- `0` (the default)
640// makes every call a true no-op, matching every existing gate stream's
641// `cdef_bits == 0` behaviour exactly.
642// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
643// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
644// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
645// blocks every non-8-bit stream from reaching a decode call, so this is `8`
646// on every path that runs today -- threading it now (rather than the literal
647// `8`) is stage 1 of widening past that refusal without re-deriving every
648// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
649// depth (this decoder's own internal choice, matches dav1d/libaom).
650/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
651/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
652pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
653 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
654}
655/// The current stream's bit depth, for callers (e.g. dequant) that need the
656/// raw value rather than the derived clamp bound.
657pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
658 fctx.bit_depth.with(std::cell::Cell::get)
659}
660/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
661/// [`crate::stream`]'s decode loop.
662pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
663 fctx.bit_depth.with(|c| c.set(bit_depth));
664}
665
666/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
667/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
668/// symbol or chroma coefficient and the output picture is luma only.
669pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
670 fctx.mono_chrome.with(std::cell::Cell::get)
671}
672
673/// Sets [`mono`] for the current thread, called once per frame from
674/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
675pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
676 fctx.mono_chrome.with(|c| c.set(mono_chrome));
677}
678
679/// Sequence subsampling. Set once per frame from stream.rs, like set_mono.
680pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) {
681 fctx.subsampling_x.set(ss_x);
682 fctx.subsampling_y.set(ss_y);
683}
684
685#[inline]
686pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize {
687 fctx.subsampling_x.get() as usize
688}
689
690#[inline]
691pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize {
692 fctx.subsampling_y.get() as usize
693}
694
695/// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim.
696#[inline]
697pub(crate) fn round_ss(dim: usize, ss: usize) -> usize {
698 (dim + ((1usize << ss) >> 1)) >> ss
699}
700
701/// This frame's superres state: `(upscaled_width, superres_denom)`, or
702/// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
703/// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
704/// `read_lr`'s unit corners and the pixel filters themselves -- works in
705/// UPSCALED coordinates while deblock and CDEF work in downscaled ones
706/// (libaom `av1_superres_upscale` in `decodeframe.c`, and
707/// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
708/// superres arms). Set once per frame from [`crate::stream`]'s decode
709/// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
710/// so a later frame never inherits it.
711
712/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
713/// `denom` 8) for a frame that is not superres-scaled.
714pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
715 fctx.superres.with(|c| c.set((upscaled_width, denom)));
716}
717
718/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
719/// (libaom `av1_superres_scaled`), else `None`.
720pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
721 let (w, d) = fctx.superres.with(std::cell::Cell::get);
722 (w > 0 && d != 8).then_some((w, d))
723}
724// Whether this superblock's single CDEF unit (this decoder has no 128x128
725// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
726// read -- reset to `false` at the top of each superblock in the two tile
727// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
728// Number of superblock columns in the current tile's grid, so
729// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
730// [`CDEF_IDX_GRID`].
731// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
732// which of the header's `1 << cdef.bits` strength pairs applies to that
733// superblock's samples.
734// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
735// has read, across every call on the current thread -- the gate's proof that a
736// `cdef_bits > 0` stream actually reached the new reader rather than every
737// superblock coincidentally being all-skip.
738thread_local! {
739 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
740}
741
742// How many times a warp was suppressed for one PLANE because that plane's own
743// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
744// reconinter.c) -- the gate's proof that a stream really carries the shape,
745// since the square `side`/`chroma_side` can be 8 or more while the plane's
746// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
747thread_local! {
748 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
749}
750
751/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
752#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
753pub(crate) fn warp_plane_suppress_hits() -> usize {
754 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
755}
756
757/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
758/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
759/// block dimensions decide it -- never the square `side`/`chroma_side`, which
760/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
761/// bigger than the real block in one axis.
762pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
763 if w >= 8 && h >= 8 {
764 return true;
765 }
766 hit!(WARP_PLANE_SUPPRESS_HITS);
767 false
768}
769
770/// Current value of [`CDEF_IDX_HITS`].
771#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
772pub(crate) fn cdef_idx_hits() -> usize {
773 CDEF_IDX_HITS.with(|c| c.get())
774}
775
776// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
777// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
778// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
779// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
780// instead of from the coarse 16x16 cell.
781thread_local! {
782 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
783 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
784 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
785}
786
787/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
789pub(crate) fn intra_in_inter_txctx_hits() -> usize {
790 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
791}
792
793/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
795pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
796 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
797}
798
799/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
800#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
801pub(crate) fn edge_filter_mi_fix_hits() -> usize {
802 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
803}
804
805// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
806// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
807// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
808// true no-op, matching every existing gate stream's `delta_q_present == 0`
809// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
810// The running quantizer index (spec `CurrentQIndex`, libaom
811// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
812// top of every tile (spec `decode_tile`), carried across superblocks within
813// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
814// dequantization call sites instead of the frame-constant `base_q_idx`.
815// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
816// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
817// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
818// back at every dequantization call site keyed on which plane it is doing.
819// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
820// read, across every call on the current thread -- the gate's proof that a
821// `delta_q_present` stream actually reached the new reader.
822thread_local! {
823 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
824}
825
826/// Current value of [`DELTA_Q_HITS`].
827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
828pub(crate) fn delta_q_hits() -> usize {
829 DELTA_Q_HITS.with(|c| c.get())
830}
831
832/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
833/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
834/// one), so it is always `0` here.
835fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
836 let d = fctx.quant_deltas.with(|c| c.get());
837 match plane_idx {
838 0 => (d.y_dc, 0),
839 1 => (d.u_dc, d.u_ac),
840 _ => (d.v_dc, d.v_ac),
841 }
842}
843
844/// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels
845/// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed
846/// `quantization_params`. Called from `stream.rs` at the frame header, where
847/// the refusal this lane lifted used to sit.
848pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) {
849 fctx.qm_levels.with(|c| c.set(levels));
850}
851
852/// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix`
853/// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s
854/// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same
855/// way the site already evaluates its quantizer index. `None` dequantises
856/// flat (the only behaviour before lane-av1-qmatrix):
857/// - a level of 15, which is both libaom's flat sentinel and what every
858/// `using_qmatrix == 0` frame's levels are parked at;
859/// - a 1D/identity transform (`is_2d_transform` false: libaom's
860/// `av1_get_iqmatrix` reads the NULL slot for those);
861/// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the
862/// segment-adjusted quantizer index clamped to 0 with all five plane
863/// deltas zero -- the same `block_q_idx` every other dequant site reads).
864fn block_iqmatrix(
865 fctx: &crate::decode::FrameCtx,
866 plane_idx: usize,
867 w: usize,
868 h: usize,
869 tx_type: TxType,
870) -> Option<crate::qm::Iqm> {
871 let levels = fctx.qm_levels.with(|c| c.get());
872 let level = levels[plane_idx.min(2)];
873 if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 {
874 return None;
875 }
876 if !tx_type.is_2d_transform() {
877 return None;
878 }
879 let d = fctx.quant_deltas.with(|c| c.get());
880 if block_q_idx(fctx) == 0
881 && d.y_dc == 0
882 && d.u_dc == 0
883 && d.u_ac == 0
884 && d.v_dc == 0
885 && d.v_ac == 0
886 {
887 return None;
888 }
889 crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h)
890}
891
892/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
893/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
894/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
895/// A no-op when `delta_q_present` is unset, or when this block is not at the
896/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
897/// libaom, collapsed here to a position check since a partition tree's
898/// top-left leaf is the only block that can ever land there), or when that
899/// leaf both *is* the whole superblock and is `skip` (the one case libaom
900/// itself skips the read, state carrying over unchanged).
901fn maybe_read_delta_q(
902 dec: &mut SymbolDecoder,
903 cdfs: &mut Cdfs,
904 mi_r: usize,
905 mi_c: usize,
906 is_whole_sb: bool,
907 skip: bool,
908 fctx: &crate::decode::FrameCtx,
909) {
910 if !fctx.delta_q_present.with(|c| c.get()) {
911 return;
912 }
913 let sb_mi = sb_mi_cur(fctx) as usize;
914 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
915 return;
916 }
917 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
918 // computed against the sequence's own superblock size (lane-sb128b r1:
919 // it used to be hardcoded against 64 and disabled under `sb128`, which a
920 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
921 // wrong).
922 if is_whole_sb && skip {
923 return;
924 }
925 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
926 const DELTA_Q_SMALL: i32 = 3;
927 if abs >= DELTA_Q_SMALL {
928 let rem_bits = dec.literal(3) + 1;
929 let thr = (1i32 << rem_bits) + 1;
930 abs = dec.literal(rem_bits) as i32 + thr;
931 }
932 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
933 let reduced = if sign_negative { -abs } else { abs };
934 hit!(DELTA_Q_HITS);
935 let res = fctx.delta_q_res.with(|c| c.get());
936 fctx.current_q_idx
937 .with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
938}
939
940// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
941// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
942// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
943// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
944// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
945// updates index 0 and every reader treats that as the value for all 4
946// indices (spec `read_delta_lf_params`'s own single-cdf branch).
947// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
948// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
949thread_local! {
950 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
951}
952
953/// Current value of [`DELTA_LF_HITS`].
954#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
955pub(crate) fn delta_lf_hits() -> usize {
956 DELTA_LF_HITS.with(|c| c.get())
957}
958
959/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
960/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
961/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
962/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
963/// read once into index 0 otherwise.
964fn maybe_read_delta_lf(
965 dec: &mut SymbolDecoder,
966 cdfs: &mut Cdfs,
967 mi_r: usize,
968 mi_c: usize,
969 is_whole_sb: bool,
970 skip: bool,
971 fctx: &crate::decode::FrameCtx,
972) {
973 if !fctx.delta_lf_present.with(|c| c.get()) {
974 return;
975 }
976 let sb_mi = sb_mi_cur(fctx) as usize;
977 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
978 return;
979 }
980 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
981 // computed against the sequence's own superblock size (lane-sb128b r1:
982 // it used to be hardcoded against 64 and disabled under `sb128`, which a
983 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
984 // wrong).
985 if is_whole_sb && skip {
986 return;
987 }
988 let multi = fctx.delta_lf_multi.with(|c| c.get());
989 let res = fctx.delta_lf_res.with(|c| c.get());
990 let count = if multi { 4 } else { 1 };
991 let mut cur = fctx.current_delta_lf.with(|c| c.get());
992 for i in 0..count {
993 let mut abs = if multi {
994 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
995 } else {
996 dec.symbol(&mut cdfs.delta_lf) as i32
997 };
998 const DELTA_LF_SMALL: i32 = 3;
999 if abs >= DELTA_LF_SMALL {
1000 let rem_bits = dec.literal(3) + 1;
1001 let thr = (1i32 << rem_bits) + 1;
1002 abs = dec.literal(rem_bits) as i32 + thr;
1003 }
1004 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
1005 let reduced = if sign_negative { -abs } else { abs };
1006 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
1007 hit!(DELTA_LF_HITS);
1008 }
1009 fctx.current_delta_lf.with(|c| c.set(cur));
1010}
1011
1012/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
1013/// after `skip` is known at every block-decode call site. A no-op at
1014/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
1015/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
1016/// `allow_intrabc`, so neither needs a separate check here. Reads once per
1017/// superblock, at the first non-skip block.
1018fn maybe_read_cdef_idx(
1019 dec: &mut SymbolDecoder,
1020 mi_r: usize,
1021 mi_c: usize,
1022 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
1023 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
1024 // unit it covers, so its one literal drives all of them (lane-b128r).
1025 (w_mi, h_mi): (usize, usize),
1026 skip: bool,
1027 fctx: &crate::decode::FrameCtx,
1028) {
1029 let bits = fctx.cdef_bits.with(|c| c.get());
1030 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
1031 return;
1032 }
1033 let idx = dec.literal(u32::from(bits)) as u8;
1034 fctx.cdef_transmitted.with(|c| c.set(true));
1035 hit!(CDEF_IDX_HITS);
1036 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
1037 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
1038 if sb_cols > 0 {
1039 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
1040 // their strength off the MB_MODE_INFO of the first non-skip block in
1041 // their own unit -- and a block that COVERS several units (the 128
1042 // root's own 128x128 block, the only one there is) is that block for
1043 // every unit it covers, so one literal drives all four. This grid is
1044 // per 64x64 unit, so the read stamps every unit the block covers; one
1045 // that is smaller than a unit stamps exactly the cell it always did.
1046 let (rows, cols) = (
1047 (h_mi / SB_MI as usize).max(1),
1048 (w_mi / SB_MI as usize).max(1),
1049 );
1050 fctx.cdef_idx_grid.with(|g| {
1051 let mut g = g.borrow_mut();
1052 for dr in 0..rows {
1053 for dc in 0..cols {
1054 let i = (sb_r + dr) * sb_cols + sb_c + dc;
1055 if sb_c + dc < sb_cols && i < g.len() {
1056 g[i] = idx;
1057 }
1058 }
1059 }
1060 });
1061 }
1062}
1063
1064// ---------------------------------------------------------------------------
1065// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
1066// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
1067// the two consumers a real stream exercises: the per-segment quantizer index
1068// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
1069// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
1070// `read_intra_segment_id`/`read_inter_segment_id` and
1071// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
1072// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
1073// is what the oracle every gate here compares against actually does.
1074thread_local! {
1075 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
1076 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
1077 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
1078 /// this frame has no primary reference (spec `load_previous_segment_ids`).
1079 /// `(mi_rows, mi_cols)` for both maps above.
1080 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
1081 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
1082 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
1083 /// The block currently being decoded -- read back by [`block_q_idx`].
1084 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
1085 /// How many real `segment_id` symbols were read, and the set of segment
1086 /// ids any block ended up with -- the gate's proof the feature fired.
1087 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1088 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
1089 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
1090 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
1091 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
1092 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
1093 /// nothing about the segments carrying distinct quantizers.
1094 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
1095 /// How many `seg_id_predicted` symbols were read (temporal update).
1096 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1097}
1098
1099/// Installs this frame's segmentation parameters and allocates its map, with
1100/// `prev` the primary reference frame's saved map (spec
1101/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
1102/// slot). Called once per frame, whether or not segmentation is enabled.
1103pub(crate) fn set_segmentation(
1104 seg: SegmentationParams,
1105 mi_rows: usize,
1106 mi_cols: usize,
1107 prev: Option<&[u8]>,
1108 fctx: &crate::decode::FrameCtx,
1109) {
1110 if crate::envflags::env_flag!("EC_HDR") {
1111 eprintln!(
1112 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
1113 seg.enabled,
1114 seg.update_map,
1115 seg.temporal_update,
1116 seg.seg_id_pre_skip,
1117 seg.last_active_seg_id,
1118 seg.feature_data
1119 );
1120 }
1121 fctx.seg.with(|s| *s.borrow_mut() = seg);
1122 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
1123 fctx.seg_ids
1124 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
1125 fctx.prev_seg_ids.with(|m| {
1126 let mut m = m.borrow_mut();
1127 m.clear();
1128 if let Some(p) = prev {
1129 if p.len() == mi_rows * mi_cols {
1130 m.extend_from_slice(p);
1131 }
1132 }
1133 });
1134 fctx.above_seg_pred
1135 .with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
1136 fctx.left_seg_pred
1137 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
1138 fctx.cur_segment_id.with(|c| c.set(0));
1139}
1140
1141/// This frame's decoded segment map, to be stored into whichever reference
1142/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
1143pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
1144 fctx.seg_ids.with(|m| m.borrow().clone())
1145}
1146
1147/// How many `segment_id` symbols have been read (never reset per frame).
1148#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1149pub(crate) fn segment_id_hits() -> usize {
1150 SEG_ID_HITS.with(|c| c.get())
1151}
1152
1153/// How many distinct segment ids any decoded block has carried.
1154#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1155pub(crate) fn segment_ids_seen() -> usize {
1156 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
1157}
1158
1159/// The lowest and highest quantizer index any decoded block was dequantized
1160/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
1161#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1162pub(crate) fn block_q_span() -> (i32, i32) {
1163 BLOCK_Q_SPAN.with(|c| c.get())
1164}
1165
1166/// How many `seg_id_predicted` symbols have been read (temporal update).
1167#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1168pub(crate) fn segment_pred_hits() -> usize {
1169 SEG_PRED_HITS.with(|c| c.get())
1170}
1171
1172/// Resets the segmentation hit counters (gate setup).
1173#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1174pub(crate) fn reset_segment_hits() {
1175 SEG_ID_HITS.with(|c| c.set(0));
1176 SEG_IDS_SEEN.with(|c| c.set(0));
1177 SEG_PRED_HITS.with(|c| c.set(0));
1178 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
1179}
1180
1181/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
1182/// being decoded, with its `FeatureData` value.
1183fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
1184 fctx.seg.with(|s| {
1185 let s = s.borrow();
1186 s.feature_active(segment_id, feature)
1187 .then(|| i32::from(s.feature_data[segment_id][feature]))
1188 })
1189}
1190
1191/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
1192/// `av1_get_qindex`) for the block currently being decoded: the running
1193/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
1194/// Every dequant call site reads the block's quantizer through here.
1195fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
1196 let base = fctx.current_q_idx.with(|c| c.get());
1197 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
1198 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
1199 Some(data) => (base + data).clamp(0, 255),
1200 None => base,
1201 };
1202 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
1203 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
1204 // already proven equal is a segment-id defect, not a quantizer one.
1205 if crate::envflags::env_flag!("EC_DQCOEFF") {
1206 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
1207 }
1208 hit_do!(BLOCK_Q_SPAN.with(|c| {
1209 let (lo, hi) = c.get();
1210 c.set((lo.min(q), hi.max(q)));
1211 }););
1212 q
1213}
1214
1215/// The segment id recorded for one mi cell of the current frame's map.
1216fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1217 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1218 if mi_r >= mi_rows || mi_c >= mi_cols {
1219 return 0;
1220 }
1221 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1222}
1223
1224/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1225fn write_segment_id(
1226 mi_r: usize,
1227 mi_c: usize,
1228 w_mi: usize,
1229 h_mi: usize,
1230 id: u8,
1231 fctx: &crate::decode::FrameCtx,
1232) {
1233 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1234 let (x_mis, y_mis) = (
1235 w_mi.min(mi_cols.saturating_sub(mi_c)),
1236 h_mi.min(mi_rows.saturating_sub(mi_r)),
1237 );
1238 fctx.seg_ids.with(|m| {
1239 let mut m = m.borrow_mut();
1240 for y in 0..y_mis {
1241 for x in 0..x_mis {
1242 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1243 }
1244 }
1245 });
1246 fctx.cur_segment_id.with(|c| c.set(id));
1247 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1248}
1249
1250/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is
1251/// inherited VERBATIM over this block's own mi footprint -- per-cell copies,
1252/// not the minified id [`predicted_segment_id`] hands the block. Without a
1253/// previous map the footprint is zeroed, exactly as the C NULL branch does.
1254fn copy_segment_ids(
1255 mi_r: usize,
1256 mi_c: usize,
1257 w_mi: usize,
1258 h_mi: usize,
1259 fctx: &crate::decode::FrameCtx,
1260) {
1261 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1262 let (x_mis, y_mis) = (
1263 w_mi.min(mi_cols.saturating_sub(mi_c)),
1264 h_mi.min(mi_rows.saturating_sub(mi_r)),
1265 );
1266 fctx.seg_ids.with(|m| {
1267 let mut m = m.borrow_mut();
1268 fctx.prev_seg_ids.with(|p| {
1269 let p = p.borrow();
1270 for y in 0..y_mis {
1271 for x in 0..x_mis {
1272 let idx = (mi_r + y) * mi_cols + mi_c + x;
1273 m[idx] = p.get(idx).copied().unwrap_or(0);
1274 }
1275 }
1276 });
1277 });
1278}
1279
1280/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1281/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1282/// block's own mi footprint. `0` when there is no previous map.
1283fn predicted_segment_id(
1284 mi_r: usize,
1285 mi_c: usize,
1286 w_mi: usize,
1287 h_mi: usize,
1288 fctx: &crate::decode::FrameCtx,
1289) -> u8 {
1290 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1291 fctx.prev_seg_ids.with(|m| {
1292 let m = m.borrow();
1293 if m.is_empty() {
1294 return 0;
1295 }
1296 let (x_mis, y_mis) = (
1297 w_mi.min(mi_cols.saturating_sub(mi_c)),
1298 h_mi.min(mi_rows.saturating_sub(mi_r)),
1299 );
1300 let mut id = u8::MAX;
1301 for y in 0..y_mis {
1302 for x in 0..x_mis {
1303 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1304 }
1305 }
1306 if id == u8::MAX { 0 } else { id }
1307 })
1308}
1309
1310/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1311fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1312 if reference == 0 {
1313 return diff;
1314 }
1315 if reference >= max - 1 {
1316 return max - diff - 1;
1317 }
1318 let half = if 2 * reference < max {
1319 diff <= 2 * reference
1320 } else {
1321 diff <= 2 * (max - reference - 1)
1322 };
1323 if half {
1324 return if diff & 1 != 0 {
1325 reference + ((diff + 1) >> 1)
1326 } else {
1327 reference - (diff >> 1)
1328 };
1329 }
1330 if 2 * reference < max {
1331 diff
1332 } else {
1333 max - (diff + 1)
1334 }
1335}
1336
1337/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1338/// frame's already-decoded above/left/above-left neighbours.
1339fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1340 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1341 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1342 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1343 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1344 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1345 let ctx = match prev_ul {
1346 None => 0,
1347 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1348 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1349 Some(_) => 0,
1350 };
1351 let pred = match (prev_u, prev_l) {
1352 (None, l) => l.unwrap_or(0),
1353 (Some(u), None) => u,
1354 (Some(u), Some(l)) => {
1355 if prev_ul == Some(u) {
1356 u
1357 } else {
1358 l
1359 }
1360 }
1361 };
1362 (pred, ctx)
1363}
1364
1365/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1366/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1367/// that prediction. Does NOT write the map -- callers do.
1368fn read_segment_id(
1369 dec: &mut SymbolDecoder,
1370 cdfs: &mut Cdfs,
1371 mi_r: usize,
1372 mi_c: usize,
1373 skip: bool,
1374 fctx: &crate::decode::FrameCtx,
1375) -> u8 {
1376 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1377 if skip {
1378 return pred as u8;
1379 }
1380 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1381 hit!(SEG_ID_HITS);
1382 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1383 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1384 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1385 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1386 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1387 eprintln!(
1388 "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}",
1389 dec.debug_state().0
1390 );
1391 }
1392 id as u8
1393}
1394
1395/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1396/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1397/// caller decides which by passing `pre_skip`).
1398fn intra_segment_id(
1399 dec: &mut SymbolDecoder,
1400 cdfs: &mut Cdfs,
1401 mi_r: usize,
1402 mi_c: usize,
1403 w_mi: usize,
1404 h_mi: usize,
1405 skip: bool,
1406 fctx: &crate::decode::FrameCtx,
1407) {
1408 if !fctx.seg.with(|s| s.borrow().enabled) {
1409 return;
1410 }
1411 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1412 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1413}
1414
1415/// Whether this frame's intra blocks read their `segment_id` before `skip`
1416/// (`SegIdPreSkip`); `false` also when segmentation is off.
1417fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1418 fctx.seg.with(|s| {
1419 let s = s.borrow();
1420 s.enabled && s.seg_id_pre_skip
1421 })
1422}
1423
1424/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1425/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1426/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1427fn inter_segment_id(
1428 dec: &mut SymbolDecoder,
1429 cdfs: &mut Cdfs,
1430 mi_r: usize,
1431 mi_c: usize,
1432 w_mi: usize,
1433 h_mi: usize,
1434 skip: bool,
1435 pre_skip: bool,
1436 fctx: &crate::decode::FrameCtx,
1437) {
1438 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1439 let s = s.borrow();
1440 (
1441 s.enabled,
1442 s.update_map,
1443 s.temporal_update,
1444 s.seg_id_pre_skip,
1445 )
1446 });
1447 if !enabled {
1448 return;
1449 }
1450 if !update_map {
1451 // The map is inherited from the previous frame, and libaom's
1452 // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of
1453 // the previous map over the block's own footprint, mixed ids intact --
1454 // while the id the BLOCK itself carries is the min over that footprint
1455 // (`get_predicted_segment_id`). Stamping the min here flattened mixed
1456 // footprints into the saved map, and every later frame whose
1457 // `update_map == 0` copy or temporal prediction read that position
1458 // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class
1459 // `simplified-inheritance`).
1460 copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx);
1461 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1462 fctx.cur_segment_id.with(|c| c.set(id));
1463 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1464 return;
1465 }
1466 if pre_skip && !pre_skip_frame {
1467 return;
1468 }
1469 if !pre_skip && skip {
1470 // libaom: a skipped block never codes `seg_id_predicted`, and its
1471 // segment id is the spatial prediction.
1472 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1473 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1474 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1475 return;
1476 }
1477 let id = if temporal_update {
1478 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1479 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1480 hit!(SEG_PRED_HITS);
1481 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1482 if predicted {
1483 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1484 } else {
1485 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1486 }
1487 } else {
1488 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1489 };
1490 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1491}
1492
1493/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1494fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1495 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1496 // so contribute 0) outside the tile -- the availability check here is
1497 // what keeps a previous tile's stamps out of this tile's context.
1498 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1499 let above = if mi_r > row0 {
1500 fctx.above_seg_pred
1501 .with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1502 } else {
1503 0
1504 };
1505 let left = if mi_c > col0 {
1506 fctx.left_seg_pred
1507 .with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1508 } else {
1509 0
1510 };
1511 usize::from(above + left)
1512}
1513
1514/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1515fn stamp_seg_pred(
1516 mi_r: usize,
1517 mi_c: usize,
1518 w_mi: usize,
1519 h_mi: usize,
1520 value: u8,
1521 fctx: &crate::decode::FrameCtx,
1522) {
1523 fctx.above_seg_pred.with(|m| {
1524 let mut m = m.borrow_mut();
1525 for i in 0..w_mi {
1526 if let Some(cell) = m.get_mut(mi_c + i) {
1527 *cell = value;
1528 }
1529 }
1530 });
1531 fctx.left_seg_pred.with(|m| {
1532 let mut m = m.borrow_mut();
1533 for i in 0..h_mi {
1534 if let Some(cell) = m.get_mut(mi_r + i) {
1535 *cell = value;
1536 }
1537 }
1538 });
1539}
1540
1541// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1542// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1543// counter, proving a stream actually put a directional block next to a
1544// smooth-predicted neighbour rather than every block reading the (previously
1545// hardcoded `false`) edge-filter strength bucket unchanged.
1546thread_local! {
1547 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1548 const { std::cell::Cell::new(0) };
1549}
1550
1551/// Current value of [`SMOOTH_LUMA_HITS`].
1552#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1553pub(crate) fn smooth_luma_hits() -> usize {
1554 SMOOTH_LUMA_HITS.with(|c| c.get())
1555}
1556
1557thread_local! {
1558 /// lane-band46 r1: how many split-transform units answered their intra
1559 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1560 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1561 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1562 /// transform unit whose above-right / below-left reference samples would
1563 /// be wrong without that fix.
1564 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1565 const { std::cell::Cell::new(0) };
1566}
1567
1568/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1569#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1570pub(crate) fn split_tu_reach_fix_hits() -> usize {
1571 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1572}
1573
1574/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1575/// answer differs from the standalone-block answer the call sites used before
1576/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1577/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1578/// block's top-left `(px, py)`.
1579#[allow(clippy::too_many_arguments)]
1580fn tu_reach(
1581 bw: usize,
1582 bh: usize,
1583 col_off: usize,
1584 row_off: usize,
1585 tx: usize,
1586 block: Reach,
1587 px: usize,
1588 py: usize,
1589 width: usize,
1590 height: usize,
1591 fctx: &crate::decode::FrameCtx,
1592) -> Reach {
1593 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1594 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1595 if fixed != standalone {
1596 hit!(SPLIT_TU_REACH_FIX_HITS);
1597 }
1598 fixed
1599}
1600
1601/// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect
1602/// (lane-av1-422b: a 4:2:2 chroma unit is square in chroma pixels, but its
1603/// luma anchor is `(chroma_tx << ss_x, chroma_tx << ss_y)` -- at ss (1,0)
1604/// twice as wide as it is tall). Same predicate as [`tu_reach`]; the
1605/// square mismatch counter only means anything when the footprint actually
1606/// is square.
1607fn tu_reach_rect(
1608 bw: usize,
1609 bh: usize,
1610 col_off: usize,
1611 row_off: usize,
1612 tx_w: usize,
1613 tx_h: usize,
1614 block: Reach,
1615 px: usize,
1616 py: usize,
1617 width: usize,
1618 height: usize,
1619 fctx: &crate::decode::FrameCtx,
1620) -> Reach {
1621 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);
1622 if tx_w == tx_h {
1623 let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx);
1624 if fixed != standalone {
1625 hit!(SPLIT_TU_REACH_FIX_HITS);
1626 }
1627 }
1628 fixed
1629}
1630
1631// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1632// across every call on the current thread -- lane-chroma r3's own before/after
1633// counter, proving a stream actually exercised chroma's smooth/paeth
1634// predictor (the previously-refused round-2 gap) rather than every block
1635// landing on DC/CFL/directional.
1636thread_local! {
1637 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1638 const { std::cell::Cell::new(0) };
1639}
1640
1641/// Current value of [`SMOOTH_UV_HITS`].
1642#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1643pub(crate) fn smooth_uv_hits() -> usize {
1644 SMOOTH_UV_HITS.with(|c| c.get())
1645}
1646
1647// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1648// full superblock walk over, across every call on the current thread --
1649// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1650// multi-tile stream must prove more than one tile actually fired, not just
1651// that the stream carried tile_info.cols > 1.
1652thread_local! {
1653 static TILE_HITS: std::cell::Cell<usize> =
1654 const { std::cell::Cell::new(0) };
1655}
1656/// Current value of [`TILE_HITS`].
1657#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1658pub(crate) fn tile_hits() -> usize {
1659 TILE_HITS.with(|c| c.get())
1660}
1661
1662// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1663// selected for filtering, across every call on the current thread -- the same
1664// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1665// exercised `apply_deblock` rather than every edge landing on level 0.
1666thread_local! {
1667 static DEBLOCK_HITS: std::cell::Cell<usize> =
1668 const { std::cell::Cell::new(0) };
1669}
1670/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1671/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1672/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1673static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1674
1675/// Current value of [`DEBLOCK_HITS`].
1676#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1677pub(crate) fn deblock_hits() -> usize {
1678 DEBLOCK_HITS.with(|c| c.get())
1679}
1680
1681// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1682// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1683// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1684// stream built with `--enable-onesided-comp=1` really exercised the
1685// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1686thread_local! {
1687 static UNI_COMP_HITS: std::cell::Cell<usize> =
1688 const { std::cell::Cell::new(0) };
1689}
1690
1691/// Current value of [`UNI_COMP_HITS`].
1692#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1693pub(crate) fn uni_comp_hits() -> usize {
1694 UNI_COMP_HITS.with(|c| c.get())
1695}
1696
1697// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1698// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1699// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1700// blend and not only the wedge arm.
1701thread_local! {
1702 static DIFFWTD_HITS: std::cell::Cell<usize> =
1703 const { std::cell::Cell::new(0) };
1704}
1705
1706/// Current value of [`DIFFWTD_HITS`].
1707#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1708pub(crate) fn diffwtd_hits() -> usize {
1709 DIFFWTD_HITS.with(|c| c.get())
1710}
1711
1712// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1713// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1714// this decoder's square inter path reaches), so no `compound_type` symbol is
1715// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1716// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1717thread_local! {
1718 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1719 const { std::cell::Cell::new(0) };
1720}
1721
1722/// Current value of [`DIFFWTD_INFERRED_HITS`].
1723#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1724pub(crate) fn diffwtd_inferred_hits() -> usize {
1725 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1726}
1727
1728// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1729// with `show_frame == 0`, output later by a `show_existing_frame` header
1730// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1731// `stream::decode_stream`, which is where the frame header is consumed; the
1732// gate's proof that the on-value really reached the bitstream rather than
1733// being dropped by the rate control.
1734thread_local! {
1735 static FWD_KF_HITS: std::cell::Cell<usize> =
1736 const { std::cell::Cell::new(0) };
1737}
1738
1739/// Current value of [`FWD_KF_HITS`].
1740#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1741pub(crate) fn fwd_kf_hits() -> usize {
1742 FWD_KF_HITS.with(|c| c.get())
1743}
1744
1745/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1746pub(crate) fn note_fwd_kf() {
1747 hit!(FWD_KF_HITS);
1748}
1749
1750// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1751// the block's own side, across every call on the current thread -- the same
1752// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1753// actually exercised a *split* transform under `TxMode::Select` rather than
1754// every block coincidentally resolving `depth=0` (indistinguishable from
1755// `TxMode::Largest` pixel-wise).
1756thread_local! {
1757 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1758 const { std::cell::Cell::new(0) };
1759}
1760
1761// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1762// transform smaller than their own side (`tx_depth != 0`) while coding a
1763// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1764// only exercises with aomenc's tx-size search left ON (its default), which
1765// every older recipe in this file pins off. Counted at the block, so a stream
1766// where RD happened to give every split-transform block a DC chroma mode
1767// reads as zero rather than silently passing for free.
1768thread_local! {
1769 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1770 const { std::cell::Cell::new(0) };
1771}
1772
1773/// Current value of [`SQ_CHROMA_TX_HITS`].
1774#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1775pub(crate) fn sq_chroma_tx_hits() -> usize {
1776 SQ_CHROMA_TX_HITS.with(|c| c.get())
1777}
1778
1779/// Current value of [`TX_DEPTH_HITS`].
1780#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1781pub(crate) fn tx_depth_hits() -> usize {
1782 TX_DEPTH_HITS.with(|c| c.get())
1783}
1784
1785// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1786// read, and how many of those actually took the split, on the current thread
1787// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1788// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1789// coincidentally coding one whole-block transform.
1790thread_local! {
1791 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1792 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1793 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1794 // strips coded one whole-block rect transform unit, and how many split
1795 // their rect max transform into square sub-transforms.
1796 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1797 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1798 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1799 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1800 // truncated low-32 corner.
1801 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1802 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1803 // inter strip, `[32x8, 8x32]`.
1804 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1805 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1806 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1807 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1808 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1809 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1810 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1811 // frame -- 16x8 and 8x16 inter leaves.
1812 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1813 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1814 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1815 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1816 // `decode_inter_block` already carries forty parameters and both are
1817 // frame-constant.
1818 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1819 // frame-constant like the two above and stashed the same way -- an intra
1820 // block inside an inter frame reads `use_filter_intra` under it.
1821}
1822
1823/// Current value of [`TXFM_SPLIT_READS`].
1824#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1825pub(crate) fn txfm_split_reads() -> usize {
1826 TXFM_SPLIT_READS.with(|c| c.get())
1827}
1828
1829/// Current value of [`TXFM_SPLIT_HITS`].
1830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1831pub(crate) fn txfm_split_hits() -> usize {
1832 TXFM_SPLIT_HITS.with(|c| c.get())
1833}
1834
1835/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1836#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1837pub(crate) fn inter_leaf16_horz_hits() -> usize {
1838 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1839}
1840
1841/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1842#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1843pub(crate) fn inter_leaf16_vert_hits() -> usize {
1844 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1845}
1846
1847/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1848pub(crate) fn rect_inter_tu_hits() -> usize {
1849 RECT_INTER_TU_HITS.with(|c| c.get())
1850}
1851
1852/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1853pub(crate) fn rect_inter_txsplit_hits() -> usize {
1854 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1855}
1856
1857/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1858pub(crate) fn rect64_inter_tu_hits() -> usize {
1859 RECT64_INTER_TU_HITS.with(|c| c.get())
1860}
1861
1862/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1863/// whole-block luma units of a 32x32-level 1:4 inter strip.
1864pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1865 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1866}
1867
1868/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1869/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1870pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1871 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1872}
1873
1874/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1875/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1876pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1877 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1878}
1879
1880/// Records one rectangular var-tx leaf.
1881fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1882 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1883 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1884 }
1885 let cell = if tw.min(th) == 4 {
1886 &VARTX_RECT_LEAF4_HITS
1887 } else {
1888 &VARTX_RECT_LEAF_HITS
1889 };
1890 cell.with(|c| {
1891 let mut h = c.get();
1892 h[usize::from(th > tw)] += 1;
1893 c.set(h);
1894 });
1895}
1896
1897/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1898/// [`ENABLE_FILTER_INTRA_INTER`].
1899pub(crate) fn set_inter_tx_mode(
1900 tx_select: bool,
1901 reduced_tx_set: bool,
1902 enable_filter_intra: bool,
1903 fctx: &crate::decode::FrameCtx,
1904) {
1905 fctx.tx_select_inter.with(|c| c.set(tx_select));
1906 fctx.intra_only.with(|c| c.set(false));
1907 fctx.tx_select_frame.with(|c| c.set(tx_select));
1908 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1909 fctx.enable_filter_intra_inter
1910 .with(|c| c.set(enable_filter_intra));
1911}
1912
1913// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1914// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1915// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1916// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1917// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1918// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1919// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1920// path above).
1921thread_local! {
1922 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1923 const { std::cell::Cell::new(0) };
1924}
1925
1926/// Current value of [`VERT_B_INTRA_HITS`].
1927#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1928pub(crate) fn vert_b_intra_hits() -> usize {
1929 VERT_B_INTRA_HITS.with(|c| c.get())
1930}
1931
1932// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1933// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1934// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1935// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1936// every arm separately so a run where aomenc's RD only picked one cannot
1937// pass as proof of four.
1938thread_local! {
1939 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1940}
1941
1942// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1943thread_local! {
1944 /// 4x4 transform units decoded inside an 8x8 square of a
1945 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1946 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1947 /// a real `--enable-tx-size-search=1` stream reaches it.
1948 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1949}
1950
1951#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1952pub(crate) fn vert_ab_tx4_hits() -> usize {
1953 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1954}
1955
1956#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1957pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1958 AB16_HITS.with(std::cell::Cell::get)
1959}
1960
1961fn bump_ab16(arm: usize) {
1962 hit_do! {
1963 AB16_HITS.with(|c| {
1964 let mut v = c.get();
1965 v[arm] += 1;
1966 c.set(v);
1967 });
1968 }
1969}
1970
1971// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1972// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1973// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1974// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1975// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1976// superblock's z-order recursion, not raster mi position).
1977thread_local! {
1978 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1979 const { std::cell::Cell::new(0) };
1980}
1981
1982/// Current value of [`HORZ_VERT_INTRA_HITS`].
1983#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1984pub(crate) fn horz_vert_intra_hits() -> usize {
1985 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1986}
1987
1988// How many blocks were decoded as a frame-edge rect strip -- the single
1989// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1990// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1991// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1992// paths share the counter.
1993thread_local! {
1994 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1995 const { std::cell::Cell::new(0) };
1996}
1997
1998/// Current value of [`EDGE_RECT_STRIP_HITS`].
1999#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
2000pub(crate) fn edge_rect_strip_hits() -> usize {
2001 EDGE_RECT_STRIP_HITS.with(|c| c.get())
2002}
2003
2004// lane-interedge r1: frame-edge half strips on the INTER path, per partition
2005// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
2006// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
2007// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
2008// are height mod 16 == 8, so every inter frame crosses these nodes.
2009thread_local! {
2010 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
2011 const { std::cell::Cell::new([0; 6]) };
2012}
2013
2014/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
2015pub(crate) fn bump_inter_edge_strip(idx: usize) {
2016 hit_do! {
2017 INTER_EDGE_STRIP_HITS.with(|c| {
2018 let mut v = c.get();
2019 v[idx] += 1;
2020 c.set(v);
2021 });
2022 }
2023}
2024
2025// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
2026// forced split -- libaom `decode_partition` (decodeframe.c):
2027// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
2028// straddle case that reads NO symbol at all. Indexed by level:
2029// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
2030thread_local! {
2031 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
2032 const { std::cell::Cell::new([0; 4]) };
2033}
2034
2035fn bump_edge_both_cut(level: usize) {
2036 hit_do! {
2037 EDGE_BOTH_CUT_HITS.with(|c| {
2038 let mut v = c.get();
2039 v[level] += 1;
2040 c.set(v);
2041 });
2042 }
2043}
2044
2045/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
2046pub fn inter_edge_strip_hits() -> [usize; 6] {
2047 INTER_EDGE_STRIP_HITS.with(|c| c.get())
2048}
2049
2050/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
2051/// into the next one (class `counter-from-refused-stream`).
2052pub fn reset_inter_edge_strip_hits() {
2053 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
2054}
2055
2056/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
2057#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2058pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
2059 EDGE_BOTH_CUT_HITS.with(|c| c.get())
2060}
2061
2062/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
2063#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2064pub(crate) fn reset_edge_both_cut_hits() {
2065 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
2066}
2067
2068// How many HORZ/VERT intra strips resolved a SPLIT luma transform
2069// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
2070// the case every rect path here refused by name before, and the first
2071// refusal the user's ReelB extract (600s in) stops at.
2072thread_local! {
2073 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
2074 const { std::cell::Cell::new(0) };
2075}
2076
2077/// Current value of [`RECT_SPLIT_TX_HITS`].
2078#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2079pub(crate) fn rect_split_tx_hits() -> usize {
2080 RECT_SPLIT_TX_HITS.with(|c| c.get())
2081}
2082
2083// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
2084// side 64) AND split past the first depth, i.e. tiled more than one unit in
2085// each axis -- the only shape with a transform unit that has neighbours on
2086// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
2087// no gate fired before lane-rectsplit r2 (the shared counter above also
2088// counts 32x32-level and depth-1 strips, so it cannot prove this case).
2089thread_local! {
2090 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
2091 const { std::cell::Cell::new(0) };
2092}
2093
2094/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
2095#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2096pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
2097 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
2098}
2099
2100// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
2101// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
2102// chroma half takes that had no coefficient tables before (index order:
2103// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
2104// proves the pair it happens to hit cannot catch a transposed scan/context
2105// table (class scan-weights-cross-axis).
2106thread_local! {
2107 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
2108 const { std::cell::Cell::new([0; 4]) };
2109}
2110
2111/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
2112#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2113pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
2114 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
2115}
2116
2117// lane-av1-422: how many SQUARE chroma coefficient units the strip path read
2118// on a 4:2:2 frame (ss 1,0) -- the half-width, unhalved-height shape whose
2119// tables only exist because of the square rows in the chroma_tiled arm. A
2120// 4:2:0 or 4:4:4 frame can never increment it (their rect strips' chroma is
2121// itself rect), and a restored `/2 chroma height` diverts 4:2:2 squares onto
2122// the rect rows, so the witness gate reads 0 there and fails.
2123thread_local! {
2124 static CHROMA422_SQUARE_HITS: std::cell::Cell<usize> =
2125 const { std::cell::Cell::new(0) };
2126}
2127
2128/// Current value of [`CHROMA422_SQUARE_HITS`].
2129// lane-av1-422b: `pub` so `examples/decode_probe.rs` can census it the way
2130// it does every other capability counter.
2131pub fn chroma422_square_hits() -> usize {
2132 CHROMA422_SQUARE_HITS.with(|c| c.get())
2133}
2134
2135// lane-av1-422f: how many RECT chroma coefficient units the square-block
2136// path read on a 4:2:2 frame (ss 1,0) -- TX_4X8 / TX_8X16 / TX_16X32, the
2137// plane block's own half-width, unhalved-height shape. A 4:2:0 or 4:4:4
2138// frame never takes the rect branch (their units are square
2139// `chroma_tx == chroma_tx_h`), so a witness gate reading 0 here proves the
2140// model reverted to squares.
2141thread_local! {
2142 static CHROMA422_RECT_HITS: std::cell::Cell<usize> =
2143 const { std::cell::Cell::new(0) };
2144}
2145
2146/// Current value of [`CHROMA422_RECT_HITS`].
2147pub fn chroma422_rect_hits() -> usize {
2148 CHROMA422_RECT_HITS.with(|c| c.get())
2149}
2150
2151// lane-av1-422g: how many PER-LEAF TX_4X4 chroma coefficient units the
2152// sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per even-column
2153// leaf per plane (`is_chroma_reference`'s `!(mi_col & ss_x)`). A 4:2:0 frame
2154// codes no sub-8 chroma at all and 4:4:4 goes through `sub8_leaf_chroma444`,
2155// so a witness gate reading 0 here proves the per-leaf 4:2:2 arm never ran.
2156thread_local! {
2157 static CHROMA422_SUB8_HITS: std::cell::Cell<usize> =
2158 const { std::cell::Cell::new(0) };
2159}
2160
2161/// Current value of [`CHROMA422_SUB8_HITS`].
2162pub fn chroma422_sub8_hits() -> usize {
2163 CHROMA422_SUB8_HITS.with(|c| c.get())
2164}
2165
2166// lane-av1422llintra: how many 4:2:2 LOSSLESS chroma plane blocks
2167// (`decode_leaf8`) were walked as 4x4 units rather than as the one
2168// `av1_get_max_uv_txsize` rect that rule only reaches OUTSIDE a lossless
2169// frame. A 4:2:0 or 4:4:4 frame never takes the arm (its own lossless walk
2170// was already there), so a witness gate reading 0 here proves the model
2171// reverted to the rect unit.
2172thread_local! {
2173 static CHROMA422_LOSSLESS_4X4_HITS: std::cell::Cell<usize> =
2174 const { std::cell::Cell::new(0) };
2175}
2176
2177/// Current value of [`CHROMA422_LOSSLESS_4X4_HITS`].
2178pub fn chroma422_lossless_4x4_hits() -> usize {
2179 CHROMA422_LOSSLESS_4X4_HITS.with(|c| c.get())
2180}
2181
2182// lane-av1-422sub8rect: how many PER-PIECE TX_4X4 chroma coefficient units
2183// the INTER sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per
2184// non-skipped odd-column piece per plane (`is_chroma_reference`'s
2185// `mi_col & 0x01` at ss_x 1). 4:2:0 goes through the shared group unit and
2186// 4:4:4 through [`sub8_leaf_chroma444`]'s own per-piece twin, so a witness
2187// gate reading 0 here proves the inter 4:2:2 per-piece arm never ran.
2188thread_local! {
2189 static CHROMA422_INTER_SUB8_HITS: std::cell::Cell<usize> =
2190 const { std::cell::Cell::new(0) };
2191}
2192
2193/// Current value of [`CHROMA422_INTER_SUB8_HITS`].
2194pub fn chroma422_inter_sub8_hits() -> usize {
2195 CHROMA422_INTER_SUB8_HITS.with(|c| c.get())
2196}
2197
2198// lane-av1-422m: how many TX_4X4 chunk units the invalid-ss-size chroma arm
2199// read (the 8x32 luma block whose 4:2:2 plane has no `ss_size_lookup` block).
2200// A 4:2:0 or 4:4:4 frame cannot increment it, so a non-zero read proves the
2201// chunked 4:2:2 chroma really decoded.
2202thread_local! {
2203 static CHROMA422_CHUNK_HITS: std::cell::Cell<usize> =
2204 const { std::cell::Cell::new(0) };
2205}
2206
2207/// Current value of [`CHROMA422_CHUNK_HITS`].
2208pub fn chroma422_chunk_hits() -> usize {
2209 CHROMA422_CHUNK_HITS.with(|c| c.get())
2210}
2211
2212// lane-av1-422stripanchor: how many 4-wide-strip PAIR chroma units
2213// ([`decode_rect_split`]'s ported floored-pair anchor) decoded. A 4:2:0 or
2214// 4:4:4 frame cannot increment it (the arm is keyed to a 2-px-wide chroma
2215// block, which only a 1-mi-wide strip at ss (1, 0) produces), so a non-zero
2216// read proves a stream routed a 4-wide strip through the split path.
2217thread_local! {
2218 static CHROMA422_PAIR_WIDE_HITS: std::cell::Cell<usize> =
2219 const { std::cell::Cell::new(0) };
2220}
2221
2222/// Current value of [`CHROMA422_PAIR_WIDE_HITS`].
2223pub fn chroma422_pair_wide_hits() -> usize {
2224 CHROMA422_PAIR_WIDE_HITS.with(|c| c.get())
2225}
2226
2227// How many HORZ/VERT intra strips actually predicted with filter intra
2228// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
2229// ("this decoder predicts square-only") until `predict_filter_intra` took
2230// `bw`x`bh`.
2231thread_local! {
2232 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
2233 const { std::cell::Cell::new(0) };
2234}
2235
2236/// Current value of [`FILTER_INTRA_RECT_HITS`].
2237#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2238pub(crate) fn filter_intra_rect_hits() -> usize {
2239 FILTER_INTRA_RECT_HITS.with(|c| c.get())
2240}
2241
2242// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
2243// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
2244// was never read at all before that round, so a gate needs to prove the flag
2245// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
2246// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
2247// carry different probabilities (18101 vs 20229), so a transposed pair is
2248// only caught by a gate that sees the flag fire on BOTH shapes (class
2249// scan-weights-cross-axis).
2250thread_local! {
2251 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
2252 const { std::cell::Cell::new(0) };
2253 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
2254 const { std::cell::Cell::new(0) };
2255}
2256
2257/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
2258#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2259pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
2260 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
2261}
2262
2263/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
2264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2265pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
2266 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
2267}
2268
2269// How many rectangular transform units actually coded coefficients through
2270// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
2271// exercised the rect coefficient reader at all rather than passing on
2272// all-skip blocks.
2273thread_local! {
2274 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2275 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2276}
2277
2278/// Current value of [`RECT_COEFF_TU_HITS`].
2279#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2280pub(crate) fn rect_coeff_tu_hits() -> usize {
2281 RECT_COEFF_TU_HITS.with(|c| c.get())
2282}
2283
2284/// Rectangular transform units whose resolved `tx_type` is a 1D class
2285/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
2286/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
2287/// for the square reader's own 1D types.
2288#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2289pub(crate) fn rect_class1_hits() -> usize {
2290 RECT_CLASS1_HITS.with(|c| c.get())
2291}
2292
2293// lane-av1readcensus: the PER-UNIT coefficient census -- one unit counted
2294// per `read_coeffs`/`read_coeffs_rect` call, i.e. per object this decoder
2295// actually walks, which is the unit the round-4 `av1444rect` count measured
2296// (636 square chroma reads against the oracle's 1086). The counters are
2297// 4:4:4-ONLY (`CENSUS_444`, set per frame beside `set_subsampling`), so a
2298// 4:2:0 control reads `(0, 0, 0)` -- a walk-shape change at 4:2:0 is another
2299// lane's business, and this census must not fire there.
2300thread_local! {
2301 /// Per-plane unit counts, `[luma, u, v]`, at 4:4:4 only.
2302 static CENSUS_444_UNITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2303 /// Of [`CENSUS_444_UNITS`], the units that coded at least one coefficient
2304 /// (`txb_skip == 0`) -- the per-plane split is only comparable against
2305 /// the oracle's when both sides count all-zero units the same way.
2306 static CENSUS_444_CODED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2307 /// Sequential unit index, so a trace line names its own position in the
2308 /// frame's walk rather than relying on line order alone.
2309 static CENSUS_UNIT_N: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2310 /// The plane the units read from here on belong to. A thread-local rather
2311 /// than a `read_coeffs` parameter because the three luma call sites
2312 /// (`decode_rect_split`, `decode_block_rect64`, `read_inter_plane_rect`)
2313 /// are not this lane's to edit and would each grow an argument; the
2314 /// plane-owning readers stamp it once on entry instead.
2315 static CENSUS_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2316 /// 4:4:4 (`subsampling_x == 0 && subsampling_y == 0`) for the frame being
2317 /// decoded, set per frame from [`crate::stream`].
2318 static CENSUS_444: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2319}
2320
2321/// Current `[luma, u, v]` 4:4:4 coefficient-unit counts.
2322#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2323pub(crate) fn census_444_units() -> [usize; 3] {
2324 CENSUS_444_UNITS.with(|c| c.get())
2325}
2326
2327/// Current `[luma, u, v]` 4:4:4 counts of units that coded coefficients.
2328#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2329pub(crate) fn census_444_coded() -> [usize; 3] {
2330 CENSUS_444_CODED.with(|c| c.get())
2331}
2332
2333/// lane-av1readcensus: arms the 4:4:4 census for the frame about to decode,
2334/// called once per frame from [`crate::stream`]'s decode loop beside
2335/// [`set_subsampling`]. At 4:2:0 (or 4:2:2) every census counter stays zero --
2336/// the walk-shape question this census answers is a 4:4:4 one.
2337pub(crate) fn set_census_444(ss_x: u8, ss_y: u8) {
2338 CENSUS_444.with(|c| c.set(ss_x == 0 && ss_y == 0));
2339}
2340
2341/// lane-av1readcensus: the plane the units read from here on belong to,
2342/// stamped by the plane-owning readers ([`read_plane`], [`read_inter_plane`],
2343/// [`read_inter_plane_rect`]) on entry.
2344pub(crate) fn set_census_plane(plane: usize) {
2345 CENSUS_PLANE.with(|c| c.set(plane));
2346}
2347
2348/// lane-av1readcensus: is the per-unit census trace on? Shares
2349/// [`coeff_trace_on`]'s per-frame narrowing so one frame's walk can be
2350/// dumped without the rest of the stream.
2351fn census_trace_on() -> bool {
2352 if !crate::envflags::env_flag!("EC_CENSUS_UNIT") {
2353 return false;
2354 }
2355 match COEFF_TRACE_FRAME.with(|c| c.get()) {
2356 None => true,
2357 Some(w) if w >= usize::MAX - 1 => true,
2358 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
2359 }
2360}
2361
2362/// lane-av1readcensus: one line per coefficient unit this decoder walks, the
2363/// twin of the oracle's `EC_COEFF` / `EC_COEFF_VAL` bracket around each
2364/// `av1_read_coeffs_txb` call. Pair the two sides by `post_rng` (or by `n`),
2365/// never by plane label or by walk position -- the walk order is exactly what
2366/// the census is measuring.
2367fn census_unit(
2368 w: usize,
2369 h: usize,
2370 tx_type: TxType,
2371 eob: usize,
2372 all_zero: bool,
2373 entry_rng: u32,
2374 dec: &SymbolDecoder,
2375) {
2376 let plane = CENSUS_PLANE.with(|c| c.get()).min(2);
2377 let coded = usize::from(!all_zero);
2378 CENSUS_UNIT_N.with(|c| c.set(c.get() + 1));
2379 hit_do! {
2380 CENSUS_444_UNITS.with(|c| {
2381 if CENSUS_444.with(|on| on.get()) {
2382 let mut v = c.get();
2383 v[plane] += 1;
2384 c.set(v);
2385 }
2386 });
2387 CENSUS_444_CODED.with(|c| {
2388 if CENSUS_444.with(|on| on.get()) {
2389 let mut v = c.get();
2390 v[plane] += coded;
2391 c.set(v);
2392 }
2393 });
2394 }
2395 if !census_trace_on() {
2396 return;
2397 }
2398 let n = CENSUS_UNIT_N.with(|c| c.get()) - 1;
2399 let post_rng = dec.debug_state().0;
2400 eprintln!(
2401 "EC_CENSUS_UNIT side=ours n={n} plane={plane} w={w} h={h} tx={tx_type:?} eob={eob} \
2402 all_zero={all_zero} entry_rng={entry_rng} post_rng={post_rng}"
2403 );
2404}
2405
2406/// How many transform units this thread has read since the last
2407/// [`reset_census_unit_n`] (lane-av1offtile). The per-unit oracle twin is
2408/// `EC_ECDUMP_IN`, one line per `read_coeffs_txb` call, so this count IS
2409/// directly comparable with an oracle `EC_ECDUMP_IN` census -- which is what
2410/// makes "we walk N units where libaom walks M" a gated claim rather than an
2411/// inference from the desync's position.
2412pub fn census_unit_n() -> usize {
2413 CENSUS_UNIT_N.with(|c| c.get())
2414}
2415
2416/// Reset [`census_unit_n`] to zero (lane-av1offtile).
2417pub fn reset_census_unit_n() {
2418 CENSUS_UNIT_N.with(|c| c.set(0));
2419}
2420
2421/// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the
2422/// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` /
2423/// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one
2424/// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in
2425/// the single caller `av1_read_coeffs_txb` after the whole unit).
2426///
2427/// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The
2428/// two sides can walk a different NUMBER of units and still be paired, because
2429/// the interval is what a unit CONSUMED. Entry position alone drifts the moment
2430/// one side consumes a different number of bits, and list index is invalid the
2431/// moment one side misses a unit -- both were measured here and both
2432/// mis-attribute. `post_bit` after the `txb_skip` read is the same
2433/// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole
2434/// unit including the optional luma `tx_type`, the eob, the base/BR passes and
2435/// the sign/Golomb loop, so a unit that reads the right symbols in the wrong
2436/// ORDER is caught too.
2437///
2438/// `bit` counts the bits this decoder has pulled out of its window, so it sits
2439/// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts
2440/// before `aom_reader_init`). The offset is measured per fixture, never
2441/// assumed: +14 on `444_intrabc_rect4_witness.obu`.
2442#[inline]
2443fn unit_iv_on() -> bool {
2444 crate::envflags::env_flag!("EC_UNITIV")
2445}
2446
2447/// The unit's ENTRY position. Returns it so the caller can pass the same value
2448/// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again.
2449#[inline]
2450#[track_caller]
2451fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize {
2452 if !unit_iv_on() {
2453 return 0;
2454 }
2455 let bit = dec.debug_bitpos();
2456 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2457 eprintln!(
2458 "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}",
2459 std::panic::Location::caller()
2460 );
2461 bit
2462}
2463
2464/// The position immediately after this unit's `txb_skip` read. `bit_in ==
2465/// post_bit` means the read consumed ZERO bits (a CDF row already at a
2466/// boundary), so this is also the real-read filter: the reader logs a step
2467/// either way, and counting raw lines overstates the symbol count ~2x (measured
2468/// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the
2469/// oracle's 513 -- not the "~1069 fewer" an earlier round reported).
2470#[inline]
2471fn unit_iv_skip(
2472 dec: &SymbolDecoder,
2473 bit_in: usize,
2474 plane: usize,
2475 w: usize,
2476 h: usize,
2477 ctx: usize,
2478 all_zero: bool,
2479) {
2480 if !unit_iv_on() {
2481 return;
2482 }
2483 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2484 eprintln!(
2485 "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}",
2486 all_zero as i32,
2487 dec.debug_bitpos()
2488 );
2489}
2490
2491/// The position after the WHOLE unit. One call per successful read, on both
2492/// the all-zero early return and the full coefficient walk.
2493#[inline]
2494fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) {
2495 if !unit_iv_on() {
2496 return;
2497 }
2498 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2499 eprintln!(
2500 "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}",
2501 dec.debug_bitpos()
2502 );
2503}
2504
2505// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
2506// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
2507// shapes whose `use_filter_intra` symbol had no CDF class before this round.
2508// A gate asserting the wider counter would be satisfied by a 32x16 strip and
2509// prove nothing about the new shapes.
2510thread_local! {
2511 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
2512 const { std::cell::Cell::new(0) };
2513}
2514
2515/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
2516#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2517pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
2518 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
2519}
2520
2521// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
2522// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
2523// counter would be satisfied by a 16x8 strip and prove nothing here.
2524thread_local! {
2525 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
2526 const { std::cell::Cell::new(0) };
2527}
2528
2529/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
2530#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2531pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
2532 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
2533}
2534
2535// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
2536// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
2537// call on the current thread -- the same before/after counter pattern as
2538// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
2539// `eob_pt`/1D-neighbour context path rather than every block coincidentally
2540// landing on `DCT_DCT`.
2541thread_local! {
2542 static TX_CLASS1_HITS: std::cell::Cell<usize> =
2543 const { std::cell::Cell::new(0) };
2544}
2545
2546// How many `uv_mode` reads resolved to a directional chroma mode (neither
2547// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
2548// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
2549// actually exercised chroma's own directional predictor.
2550thread_local! {
2551 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
2552 const { std::cell::Cell::new(0) };
2553}
2554
2555/// Current value of [`DIRECTIONAL_UV_HITS`].
2556#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2557pub(crate) fn directional_uv_hits() -> usize {
2558 DIRECTIONAL_UV_HITS.with(|c| c.get())
2559}
2560
2561// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
2562// something other than [`ANGLE_DELTA_ZERO`], across every call in the
2563// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
2564// proving a stream actually exercised a nonzero angle delta.
2565thread_local! {
2566 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
2567 const { std::cell::Cell::new(0) };
2568}
2569
2570// How many [`read_single_ref`] reads resolved to a reference other than
2571// `LAST_FRAME`, across every call on the current thread -- the same before/after
2572// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2573// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
2574// only other supported one so far) rather than every block coincidentally
2575// resolving `LAST_FRAME`.
2576thread_local! {
2577 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
2578 const { std::cell::Cell::new(0) };
2579}
2580
2581/// Current value of [`NON_LAST_REF_HITS`].
2582#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2583pub(crate) fn non_last_ref_hits() -> usize {
2584 NON_LAST_REF_HITS.with(|c| c.get())
2585}
2586
2587// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2588// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2589// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2590// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2591// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2592// `GOLDEN_FRAME` draw it did not ask for.
2593thread_local! {
2594 static LAST2_HITS: std::cell::Cell<usize> =
2595 const { std::cell::Cell::new(0) };
2596}
2597thread_local! {
2598 static LAST3_HITS: std::cell::Cell<usize> =
2599 const { std::cell::Cell::new(0) };
2600}
2601thread_local! {
2602 static GOLDEN_HITS: std::cell::Cell<usize> =
2603 const { std::cell::Cell::new(0) };
2604}
2605thread_local! {
2606 static BWDREF_HITS: std::cell::Cell<usize> =
2607 const { std::cell::Cell::new(0) };
2608}
2609thread_local! {
2610 static ALTREF2_HITS: std::cell::Cell<usize> =
2611 const { std::cell::Cell::new(0) };
2612}
2613thread_local! {
2614 static ALTREF_HITS: std::cell::Cell<usize> =
2615 const { std::cell::Cell::new(0) };
2616}
2617
2618// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2619// -- proves a `reference_select` stream actually reached a block that picked
2620// compound, not just that the header bit was set. Every such block is
2621// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2622// so this only ever counts attempted reads, never a completed decode.
2623thread_local! {
2624 static COMP_MODE_HITS: std::cell::Cell<usize> =
2625 const { std::cell::Cell::new(0) };
2626}
2627
2628/// Current value of [`COMP_MODE_HITS`].
2629#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2630pub(crate) fn comp_mode_hits() -> usize {
2631 COMP_MODE_HITS.with(|c| c.get())
2632}
2633
2634// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2635// use for, across every call on the current thread -- the same before/after
2636// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2637// exercised palette reconstruction rather than only reading and refusing the
2638// `palette_y_mode` symbol.
2639thread_local! {
2640 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2641}
2642
2643/// Current value of [`PALETTE_HITS`].
2644#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2645pub(crate) fn palette_hits() -> usize {
2646 PALETTE_HITS.with(|c| c.get())
2647}
2648
2649// lane-tiles r12: of those, how many sat at their own TILE's left column --
2650// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2651// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2652// palette gate that never hits one proves nothing about the tile guard.
2653thread_local! {
2654 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2655}
2656
2657/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2658#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2659pub(crate) fn palette_tile_left_hits() -> usize {
2660 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2661}
2662
2663// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2664// palette use -- proves a stream actually reconstructed UV palette pixels,
2665// not just read and refused the `palette_uv_mode` symbol.
2666thread_local! {
2667 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2668}
2669
2670/// Current value of [`PALETTE_UV_HITS`].
2671#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2672pub(crate) fn palette_uv_hits() -> usize {
2673 PALETTE_UV_HITS.with(|c| c.get())
2674}
2675
2676// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2677// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2678// (not just the square path's) actually fired.
2679thread_local! {
2680 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2681}
2682
2683/// Current value of [`PALETTE_RECT_HITS`].
2684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2685pub(crate) fn palette_rect_hits() -> usize {
2686 PALETTE_RECT_HITS.with(|c| c.get())
2687}
2688
2689// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2690// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2691// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2692// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2693// RD, almost always refused-on-use because the block doesn't end up USING a
2694// palette -- see r5's report). This is the site the removed refusal
2695// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2696// fired here whether or not the block picked a palette, so this is the
2697// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2698// never observes.
2699thread_local! {
2700 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2701}
2702
2703/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2704#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2705pub(crate) fn rect_screen_content_hits() -> usize {
2706 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2707}
2708
2709// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2710// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2711// windowing actually ran, not just that the whole-block path stayed exact.
2712// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2713// first actually incremented in r7, when the refusal it guarded was lifted.
2714thread_local! {
2715 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2716}
2717
2718thread_local! {
2719 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2720 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2721 /// (16x8/8x16), the two shapes the lifted refusals named.
2722 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2723}
2724
2725/// Current value of [`RECT4_PALETTE_HITS`].
2726#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2727pub(crate) fn rect4_palette_hits() -> usize {
2728 RECT4_PALETTE_HITS.with(|c| c.get())
2729}
2730
2731/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2732#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2733pub(crate) fn palette_split_tx_hits() -> usize {
2734 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2735}
2736
2737thread_local! {
2738 /// lane-av1444d10: chroma PREDICTION units on the 32-capped tiled chroma
2739 /// walk (`decode_block_rect`'s `uw/uh = min(chroma, 32)` units) that were
2740 /// handed a STRICT sub-slice of their block's palette buffer -- i.e. the
2741 /// units of a block the 32-cap actually TILED (`nw * nh > 1`).
2742 ///
2743 /// CORRECTED 2026-09-30 after the refutation pass `lanes/refute-av1444d10`
2744 /// read the numbers back: the previous comment claimed it counted "the
2745 /// units that are NOT the block's top-left corner", which is not what the
2746 /// code did -- the hit was unconditional, so a block's corner unit fired it
2747 /// too AND a single-unit block (whose window is a pure re-stride copy of
2748 /// the whole buffer) fired it as well. That made a hit prove only that some
2749 /// palette chroma block existed, not that the tiled arm ran. The `bigger`
2750 /// guard now makes the counter discriminate. On the pinned fixture the
2751 /// measured value is unchanged at 4 (one block with nw = 1, nh = 2 x two
2752 /// planes x two unit rows); a stream whose palette chroma blocks are all
2753 /// single-unit now leaves it at zero.
2754 ///
2755 /// FURTHER CORRECTED the same day by the palette lane's refutation
2756 /// (`lanes/av1444palw.report.md` + the arm-isolated mutation): the guard is
2757 /// about TILING, not about `nw > 1` specifically. Isolating the two window
2758 /// sites shows the RECT-unit arm alone reds the 10-bit cell, and the
2759 /// SQUARE-unit arm alone reds the 12-bit cell *and* the 10-bit one -- so
2760 /// windowing is load-bearing for every tiled block, and `nw > 1` is merely
2761 /// the case the corpus could not reach. Do not read this counter as
2762 /// evidence that only the horizontal term matters.
2763 static CHROMA_PALETTE_WINDOW_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2764}
2765
2766/// Current value of [`CHROMA_PALETTE_WINDOW_HITS`].
2767#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2768pub(crate) fn chroma_palette_window_hits() -> usize {
2769 CHROMA_PALETTE_WINDOW_HITS.with(|c| c.get())
2770}
2771
2772/// Zeroes [`CHROMA_PALETTE_WINDOW_HITS`] so a gate can read it as a DELTA
2773/// (it is process-wide, like every counter here).
2774#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2775pub(crate) fn reset_chroma_palette_window_hits() {
2776 CHROMA_PALETTE_WINDOW_HITS.with(|c| c.set(0));
2777}
2778
2779thread_local! {
2780 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2781 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2782 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2783 /// `--min-partition-size=8` puts them on this leaf path.
2784 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2785}
2786
2787/// Current value of [`PALETTE_LEAF8_HITS`].
2788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2789pub(crate) fn palette_leaf8_hits() -> usize {
2790 PALETTE_LEAF8_HITS.with(|c| c.get())
2791}
2792
2793/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2795pub(crate) fn reset_palette_leaf8_hits() {
2796 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2797}
2798
2799thread_local! {
2800 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2801 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2802 /// block that also carries a real, corner-cropped luma transform.
2803 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2804}
2805
2806/// Current value of [`PALETTE_SB_STRIP_HITS`].
2807#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2808pub(crate) fn palette_sb_strip_hits() -> usize {
2809 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2810}
2811
2812/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2813#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2814pub(crate) fn reset_palette_sb_strip_hits() {
2815 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2816}
2817
2818thread_local! {
2819 /// lane-av1rectreach: units of `decode_rect_split`'s `chroma_tiled` walk
2820 /// whose PER-UNIT reach ([`tu_reach_rect`], libaom's per-unit
2821 /// `has_top_right` / `has_bottom_left`) DIFFERS from the block-level
2822 /// `reach` this walk used to hand every unit -- i.e. units for which the
2823 /// two answers are not interchangeable. This is what a gate needs before
2824 /// it compares the walk byte-exactly: if the two agreed everywhere, the
2825 /// substitution could not change a single predicted sample and the
2826 /// exactness assert would be measuring a witness the fix cannot touch.
2827 ///
2828 /// What it does NOT prove is that the argument handed to the unit reader
2829 /// is the per-unit one -- the count is taken from the same expression
2830 /// either way, so deleting the substitution reds the exactness assert
2831 /// rather than this counter. That is the right way round: the assert is
2832 /// the claim, this is only the floor under it.
2833 static RECT_TILED_CHROMA_UNIT_REACH_HITS: std::cell::Cell<usize> =
2834 const { std::cell::Cell::new(0) };
2835 /// Chroma units of the same walk whose grid is exactly 2x1 (a 4:4:4
2836 /// 64x32 chroma plane block as two 32x32 units).
2837 static RECT_TILED_CHROMA_2X1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2838 /// Chroma units of the same walk whose grid is exactly 1x2 (4:4:4 32x64,
2839 /// or 16x64 as two 16x32s).
2840 static RECT_TILED_CHROMA_1X2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2841 /// Chroma units of the same walk in any other multi-unit grid (2x2 and up
2842 /// -- only reachable at 4:2:2, which is refused, so this stays 0 on
2843 /// every admitted stream; kept so the match above is exhaustive).
2844 static RECT_TILED_CHROMA_NXN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2845}
2846
2847/// Current values of the four `RECT_TILED_CHROMA_*` counters, in the order
2848/// `(unit_reach_differs, 2x1, 1x2, other multi-unit)`.
2849#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2850pub(crate) fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) {
2851 (
2852 RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.get()),
2853 RECT_TILED_CHROMA_2X1_HITS.with(|c| c.get()),
2854 RECT_TILED_CHROMA_1X2_HITS.with(|c| c.get()),
2855 RECT_TILED_CHROMA_NXN_HITS.with(|c| c.get()),
2856 )
2857}
2858
2859/// Zeroes the four `RECT_TILED_CHROMA_*` counters (gate tests call this
2860/// before their own decode).
2861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2862pub(crate) fn reset_rect_tiled_chroma_grid_hits() {
2863 RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.set(0));
2864 RECT_TILED_CHROMA_2X1_HITS.with(|c| c.set(0));
2865 RECT_TILED_CHROMA_1X2_HITS.with(|c| c.set(0));
2866 RECT_TILED_CHROMA_NXN_HITS.with(|c| c.set(0));
2867}
2868
2869// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2870// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2871// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2872// capability rather than the key frame's, which every screen stream also
2873// carries.
2874thread_local! {
2875 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2876 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2877}
2878
2879// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2880// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2881// shared counter too, so only this one proves a gate really reached the leaf
2882// where the refusal used to sit.
2883thread_local! {
2884 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2885 const { std::cell::Cell::new((0, 0)) };
2886}
2887
2888/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2889pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2890 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2891}
2892
2893/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2894pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2895 (
2896 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2897 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2898 )
2899}
2900
2901// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2902// and which are therefore predicted one transform unit at a time (a skipped
2903// block codes no coefficients, so nothing else in the stream witnesses this
2904// path -- only the pixels do).
2905thread_local! {
2906 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2907}
2908
2909/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2910pub fn skip_split_tx_hits() -> usize {
2911 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2912}
2913
2914// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2915// `tx_depth` split the luma transform -- the arm that predicted DC off the
2916// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2917// witness this path, so a gate that wants it needs the counter.
2918thread_local! {
2919 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2920 /// lane-av1chromadc: chroma units of a skipped block whose intra-BC /
2921 /// UV-palette override had to be WINDOWED to the unit's own extent --
2922 /// i.e. `cn_cols * cn_rows > 1`, which at 4:2:0 never happens (the chroma
2923 /// plane block is one 32x32 unit) and at 4:4:4 is every block of 64 and
2924 /// above. Counts UNITS, not blocks. EXCLUSIVE to this walk: the other two
2925 /// override sites (the luma slot and `decode_intrabc_owned_rect`) have
2926 /// their own windows.
2927 static SKIP_CHROMA_OVERRIDE_WINDOW_HITS: std::cell::Cell<usize> =
2928 const { std::cell::Cell::new(0) };
2929}
2930
2931/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2932pub fn skip_split_tx_override_hits() -> usize {
2933 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2934}
2935
2936/// lane-av1chromadc: [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`].
2937#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2938pub fn skip_chroma_override_window_hits() -> usize {
2939 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.get())
2940}
2941
2942/// Zeroes [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`] before a gate's own decode.
2943#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2944pub fn reset_skip_chroma_override_window_hits() {
2945 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.set(0));
2946}
2947
2948/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2949pub fn reset_skip_split_tx_override_hits() {
2950 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2951}
2952
2953// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2954// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2955// really are smaller than the block and FEWER symbols are read than the
2956// block has cells (class map-read-past-frame-edge).
2957thread_local! {
2958 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2959}
2960
2961/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2962pub fn palette_onscreen_cut_hits() -> usize {
2963 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2964}
2965
2966/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2967pub fn reset_palette_onscreen_cut_hits() {
2968 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2969}
2970
2971/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2972pub fn reset_skip_split_tx_hits() {
2973 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2974}
2975
2976// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2977// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2978// the gate's proof that the lifted path actually ran, per size.
2979thread_local! {
2980 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2981 const { std::cell::Cell::new([0; 4]) };
2982}
2983
2984/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2985#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2986pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2987 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2988}
2989
2990/// A just-decoded palette-Y block's own predicted pixels
2991/// (`side*side`, row-major, `colors[map[i]]`), consumed by
2992/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2993/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2994/// per-block override through `read_plane`'s two dozen call sites is the
2995/// alternative this avoids). Always empty again once that call consumes
2996/// it (`.take()`), so a non-palette block's own `reconstruct` call never
2997/// sees stale state.
2998
2999/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
3000/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
3001/// site whose reconstruct never runs would be picked up by the NEXT block's
3002/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
3003/// lane-lossless2: one transform unit's window on a block-sized palette
3004/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
3005/// handing it the whole-block buffer makes every unit reconstruct the block's
3006/// top-left corner (the luma split-transform paths already window; the chroma
3007/// ones did not, which is invisible until a lossless frame codes a palette
3008/// block as 4x4 chroma units).
3009fn palette_window(
3010 buf: &[u16],
3011 stride: usize,
3012 ox: usize,
3013 oy: usize,
3014 w: usize,
3015 h: usize,
3016) -> Vec<u16> {
3017 // `stride` is the BLOCK's own chroma width, so a caller that handed over a
3018 // mismatched stride could read in-bounds GARBAGE instead of panicking --
3019 // a silent misread, which is the one failure mode this walk must not have.
3020 // The refutation pass (`lanes/refute-av1444d10.report.md`, risk (e)) named
3021 // that as the only thing keeping the tiled walk safe, so the invariant is
3022 // closed loudly here instead of resting on an `unsupported` return
3023 // elsewhere that a future shape could remove.
3024 assert!(
3025 w <= stride && ox + w <= stride && (oy + h) * stride <= buf.len(),
3026 "palette window {w}x{h} at ({ox},{oy}) does not fit a {}-entry buffer at stride {stride}",
3027 buf.len()
3028 );
3029 (0..h)
3030 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
3031 .collect()
3032}
3033
3034/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
3035#[track_caller]
3036fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
3037 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
3038 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
3039 eprintln!(
3040 "PALSET len={} stale={stale} at {}",
3041 buf.len(),
3042 std::panic::Location::caller()
3043 );
3044 }
3045 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
3046}
3047
3048#[track_caller]
3049fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
3050 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
3051 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
3052 eprintln!(
3053 "PALTAKE len={:?} at {}",
3054 got.as_ref().map(Vec::len),
3055 std::panic::Location::caller()
3056 );
3057 }
3058 got
3059}
3060
3061/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
3062/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
3063/// pixels, because at parse time this block's own luma is still queued.
3064#[derive(Clone, Copy, Debug)]
3065pub(crate) struct CflSrc {
3066 px: usize,
3067 py: usize,
3068 bw: usize,
3069 bh: usize,
3070}
3071
3072fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
3073 CflSrc {
3074 px,
3075 py,
3076 bw: side,
3077 bh: side,
3078 }
3079}
3080
3081fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
3082 CflSrc { px, py, bw, bh }
3083}
3084
3085/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
3086/// instead of executed. Each variant is the resolved argument tuple of the
3087/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
3088/// order performs exactly the same writes in exactly the same order --
3089/// entropy parsing no longer touches the frame's own planes (except the two
3090/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
3091/// the replay on a superblock-row wavefront worker.
3092/// The dequantization + inverse transform of one transform unit, kept as its
3093/// INPUTS so that a recorded write carries the work instead of its result
3094/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
3095/// recon worker, not on the parsing thread. `stride == 0` means the dense
3096/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
3097/// `reconstruct_mc_rect` reads both of its buffers at.
3098#[derive(Clone, Copy)]
3099pub(crate) struct TxParams {
3100 /// The plane this unit belongs to (0 luma, 1 U, 2 V), carried from the
3101 /// reader that OWNS the unit. `dequant_and_inverse_wht4x4`'s `EC_DQCOEFF`
3102 /// twin prints it so its ladder pairs with the oracle's: the per-unit
3103 /// census plane could not, because the callers that route a lossless 4x4
3104 /// unit into the WHT are not all the ones that stamp the census plane
3105 /// (measured on `ll444-lossless-key.obu`: 1663 of 1663 chroma units paired
3106 /// by count, 1660 of them against an empty grid).
3107 pub(crate) plane: usize,
3108 pub(crate) w: usize,
3109 pub(crate) h: usize,
3110 pub(crate) bit_depth: u8,
3111 pub(crate) q_idx: i32,
3112 pub(crate) dc_delta: i32,
3113 pub(crate) ac_delta: i32,
3114 pub(crate) tx_type: TxType,
3115 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
3116 /// on the parse thread by [`block_iqmatrix`] and captured here so the
3117 /// recon worker scales identically without touching frame state.
3118 pub(crate) qm: Option<crate::qm::Iqm>,
3119 pub(crate) stride: usize,
3120 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
3121 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
3122 /// the 4x4 Walsh-Hadamard
3123 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
3124 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
3125 pub(crate) lossless: bool,
3126}
3127
3128/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
3129/// The mixed-lossless witness's proof the per-segment lossless path really
3130/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
3131/// workers run this on their own threads.
3132static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3133
3134/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
3135/// delta around one decode.
3136#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3137pub(crate) fn lossless_wht_units() -> usize {
3138 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
3139}
3140
3141/// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
3142/// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
3143/// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
3144/// `coded_lossless` frame before it looks at the `tx_mode` symbol,
3145/// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree,
3146/// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for
3147/// EVERY plane of a lossless block, and of `av1/common/idct.c`'s
3148/// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a
3149/// `lossless` branch -- every other size falls through to the IDCT, because
3150/// there is no non-4x4 lossless inverse transform to dispatch to. So one of
3151/// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape;
3152/// read as a before/after delta around one decode it names the caller. Must
3153/// read 0 on a stream whose lossless unit geometry is right. Atomic: the
3154/// wavefront workers run the transform on their own threads.
3155static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
3156 std::sync::atomic::AtomicUsize::new(0);
3157
3158/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
3159/// before/after delta around one decode.
3160#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3161pub(crate) fn lossless_wht_split_units() -> usize {
3162 LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
3163}
3164
3165impl TxParams {
3166 /// The one copy of the produce-the-residual code: the inline path calls it
3167 /// on the parse thread, the wavefront worker calls it on its own, so both
3168 /// are the same function on the same inputs and byte-identical.
3169 fn run(self, grid: &[i32]) -> Vec<i32> {
3170 let residual = if self.lossless {
3171 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3172 // lane-whtshape: a non-4x4 unit here is this decoder's own
3173 // transform-unit geometry being wrong (see
3174 // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used
3175 // to be stopped by a `debug_assert_eq!` that RELEASE never ran:
3176 // the 4x4 WHT returned 16 values for a `w * h` block and the
3177 // release build died one frame later in the strided copy with an
3178 // opaque `range end index 8 out of range for slice of length 0`
3179 // that never named lossless or the transform. Counted, and
3180 // reconstructed as the raster of 4x4 WHT units
3181 // ([`crate::transform::dequant_and_inverse_wht`]) instead: total,
3182 // the same in both profiles, and the 4x4 fast path is the same
3183 // single call it always was. The old
3184 // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with
3185 // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does
3186 // not either), and `av1_get_tx_type` already answers `DCT_DCT` on
3187 // every plane of a lossless block, so asserting an argument
3188 // nothing reads was a debug-only panic on a value release
3189 // ignores.
3190 if self.w != 4 || self.h != 4 {
3191 LOSSLESS_WHT_SPLIT_UNITS.fetch_add(
3192 self.w.div_ceil(4) * self.h.div_ceil(4),
3193 std::sync::atomic::Ordering::Relaxed,
3194 );
3195 }
3196 crate::transform::dequant_and_inverse_wht(
3197 grid,
3198 self.plane,
3199 self.w,
3200 self.h,
3201 self.bit_depth,
3202 self.q_idx,
3203 self.dc_delta,
3204 self.ac_delta,
3205 )
3206 } else {
3207 dequant_and_inverse_typed_wh(
3208 grid,
3209 self.w,
3210 self.h,
3211 self.bit_depth,
3212 self.q_idx,
3213 self.dc_delta,
3214 self.ac_delta,
3215 self.tx_type,
3216 self.qm,
3217 )
3218 };
3219 // An all-zero grid transforms to the empty marker, and a strided copy
3220 // of zeros is still zeros: the marker passes straight through.
3221 if residual.is_empty() {
3222 return residual;
3223 }
3224 if self.stride == 0 {
3225 return residual;
3226 }
3227 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
3228 // height exceeds its (narrow) prediction stride needs the full
3229 // stride * h; every square caller has h == stride and is unchanged.
3230 let mut strided = vec![0i32; self.stride * self.h];
3231 for row in 0..self.h {
3232 strided[row * self.stride..][..self.w]
3233 .copy_from_slice(&residual[row * self.w..][..self.w]);
3234 }
3235 strided
3236 }
3237}
3238
3239/// A recorded write's residual: already transformed, or the coefficients and
3240/// [`TxParams`] the worker transforms itself.
3241pub(crate) enum Residual {
3242 /// An already-transformed residual in the arena, `(offset, len)`; a zero
3243 /// `len` is the all-zero marker [`dense_residual`] expands.
3244 Done(u32, u32),
3245 /// The coefficients live in the pushing tile's arena
3246 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
3247 /// len)` in it.
3248 Coeffs(TxParams, u32, u32),
3249}
3250
3251impl Residual {
3252 /// The record for a transform unit whose coefficient grid is all zero:
3253 /// the empty marker, so neither the grid nor the residual is cloned and
3254 /// the worker never runs the transform (60% of the 4K segment's units).
3255 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3256 if is_zero_grid(grid) {
3257 return Self::Done(0, 0);
3258 }
3259 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
3260 }
3261
3262 /// A residual the parse thread already transformed, kept in the arena
3263 /// instead of its own `Vec`.
3264 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3265 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
3266 // which is exactly the all-zero marker -- one pointer compare instead
3267 // of copying up to 64 KB of zeros into the arena per block.
3268 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
3269 return Self::Done(0, 0);
3270 }
3271 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
3272 }
3273
3274 /// The residual to reconstruct with; `scratch` is where a transform run
3275 /// on this thread lands, so the caller owns that buffer.
3276 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
3277 match self {
3278 Self::Done(off, len) => &arena[off as usize..][..len as usize],
3279 Self::Coeffs(p, off, len) => {
3280 *scratch = p.run(&arena[off as usize..][..len as usize]);
3281 scratch
3282 }
3283 }
3284 }
3285}
3286
3287/// Appends to the tile's coefficient arena, returning the offset the record
3288/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
3289fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
3290 fctx.coeff_arena.with(|a| {
3291 let mut a = a.borrow_mut();
3292 let off = a.len();
3293 a.extend_from_slice(v);
3294 off as u32
3295 })
3296}
3297
3298/// [`push_coeffs`] for a recorded prediction.
3299fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
3300 fctx.pred_arena.with(|a| {
3301 let mut a = a.borrow_mut();
3302 let off = a.len();
3303 a.extend_from_slice(v);
3304 off as u32
3305 })
3306}
3307
3308/// An all-zero residual, for the transform units that code no coefficient:
3309/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
3310/// and the reconstruction loops below read this instead of a per-unit
3311/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
3312/// (a 128-wide inter block's prediction stride).
3313pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
3314
3315/// lane-blockscratch: one plane's coefficient levels as the block-tail
3316/// neighbour writes want them. A plane that coded nothing (a skipped block, a
3317/// strip with no chroma, luma under a var-tx split whose units already wrote
3318/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
3319/// zeroing up to 64 KB of its own per block.
3320#[derive(Clone)]
3321enum Grid {
3322 Zero(usize),
3323 Own(Vec<i32>),
3324}
3325
3326/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
3327/// unit that writes into it. Only a block wider or taller than 64 px codes its
3328/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
3329/// collectors per block and then drop them untouched.
3330fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
3331 if v.is_empty() {
3332 *v = vec![0i32; n];
3333 }
3334 v
3335}
3336
3337impl std::ops::Deref for Grid {
3338 type Target = [i32];
3339 fn deref(&self) -> &[i32] {
3340 match self {
3341 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
3342 Grid::Own(v) => v,
3343 }
3344 }
3345}
3346
3347/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
3348/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
3349/// transform units that code no coefficient without the scan (lane-coefgrid).
3350pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
3351 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
3352}
3353
3354/// `residual`, or `n` zeros when it is the empty all-zero marker.
3355fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
3356 if residual.is_empty() {
3357 &ZERO_RESIDUAL[..n]
3358 } else {
3359 residual
3360 }
3361}
3362
3363/// Where a recorded motion-compensated write reads its prediction from.
3364///
3365/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
3366/// the parse thread's single biggest reconstruction cost, so at
3367/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
3368/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
3369/// runs it into its own three-plane slot, and every transform unit of that
3370/// block then reads its window out of that slot ([`Pred::Cur`]).
3371#[derive(Clone, Copy)]
3372pub(crate) enum Pred<'a> {
3373 /// A prediction the parse thread already built, at its own stride
3374 /// (`stride == 0` means "the reader's own `stride` argument").
3375 Inline(&'a [u16], usize),
3376 /// The current block's deferred prediction: plane, its stride, and this
3377 /// unit's offset into it.
3378 Cur {
3379 plane: usize,
3380 stride: usize,
3381 off: usize,
3382 },
3383}
3384
3385impl<'a> Pred<'a> {
3386 /// The same prediction read at an explicit stride.
3387 fn view(self, stride: usize) -> Self {
3388 match self {
3389 Self::Inline(b, _) => Self::Inline(b, stride),
3390 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
3391 }
3392 }
3393 /// The materialised buffer and the stride to read it at (`stride` is the
3394 /// reader's own when this prediction was built dense); `None` for a
3395 /// deferred prediction, which only a recorded op can carry.
3396 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
3397 match self {
3398 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
3399 Self::Cur { .. } => None,
3400 }
3401 }
3402 /// This prediction's window starting `n` samples in.
3403 fn offset(self, n: usize) -> Self {
3404 match self {
3405 Self::Inline(b, s) => Self::Inline(&b[n..], s),
3406 Self::Cur { plane, stride, off } => Self::Cur {
3407 plane,
3408 stride,
3409 off: off + n,
3410 },
3411 }
3412 }
3413}
3414
3415/// [`Pred`], resolved into what a recorded op carries.
3416pub(crate) enum PredSrc {
3417 /// A prediction window in the tile's prediction arena, `(offset, len)`.
3418 Owned(u32, u32),
3419 /// A window of the block prediction: its plane, its offset, and the
3420 /// stride it is read at -- which is the block's, not necessarily the
3421 /// op's (a transform unit's residual stays dense, so the worker takes
3422 /// its window out of the block prediction itself).
3423 Cur {
3424 plane: usize,
3425 off: usize,
3426 src: usize,
3427 },
3428}
3429
3430/// One block's whole-block prediction build, deferred to a recon worker.
3431///
3432/// The closure borrows the tile's reference pictures and its own frame-level
3433/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
3434/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
3435/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
3436pub(crate) struct PredBuild(
3437 Box<
3438 dyn FnOnce(
3439 &mut PlaneBuf<'static>,
3440 &mut PlaneBuf<'static>,
3441 &mut PlaneBuf<'static>,
3442 &crate::decode::FrameCtx,
3443 // lane-blockmem: the previous block's three prediction buffers,
3444 // refilled in place -- the build used to return three fresh
3445 // `Vec`s per block and drop these.
3446 &mut [Vec<u16>; 3],
3447 ),
3448 >,
3449);
3450
3451// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
3452// pictures and frame tables, and the closure runs on exactly one worker.
3453#[allow(unsafe_code)]
3454unsafe impl Send for PredBuild {}
3455
3456/// `true` when this tile's writes are recorded for the wavefront instead of
3457/// performed at the push site, i.e. when a prediction may be deferred.
3458fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
3459 fctx.recon_planes.with(std::cell::Cell::get).is_none()
3460}
3461
3462/// The previous block's prediction buffer, cleared and zero-filled to `n`
3463/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
3464/// without the per-block allocation and free.
3465fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
3466 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
3467 // than resized element by element -- which is every block on the inline
3468 // path, where there is no previous buffer to reuse.
3469 if v.capacity() < n {
3470 return vec![0u16; n];
3471 }
3472 v.clear();
3473 v.resize(n, 0);
3474 v
3475}
3476
3477/// Records one block's prediction build for the worker that reconstructs it.
3478#[allow(unsafe_code)]
3479fn push_pred<'a>(
3480 fctx: &crate::decode::FrameCtx,
3481 f: impl FnOnce(
3482 &mut PlaneBuf<'static>,
3483 &mut PlaneBuf<'static>,
3484 &mut PlaneBuf<'static>,
3485 &crate::decode::FrameCtx,
3486 &mut [Vec<u16>; 3],
3487 ) + 'a,
3488) {
3489 type Dyn<'x> = dyn FnOnce(
3490 &mut PlaneBuf<'static>,
3491 &mut PlaneBuf<'static>,
3492 &mut PlaneBuf<'static>,
3493 &crate::decode::FrameCtx,
3494 &mut [Vec<u16>; 3],
3495 ) + 'x;
3496 let boxed: Box<Dyn<'a>> = Box::new(f);
3497 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
3498 // before the borrows the closure holds go out of scope.
3499 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
3500 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
3501}
3502
3503/// One superblock's recorded writes plus the two arenas they index -- the
3504/// unit a wavefront worker takes off the queue (lane-recoparse).
3505pub(crate) struct ReconJob {
3506 ops: Vec<ReconOp>,
3507 coeffs: Vec<i32>,
3508 preds: Vec<u16>,
3509}
3510
3511pub(crate) enum ReconOp {
3512 /// lane-wave4: build this block's prediction into the worker's slot.
3513 Pred(PredBuild),
3514 Intra {
3515 plane: usize,
3516 x: usize,
3517 y: usize,
3518 bw: usize,
3519 bh: usize,
3520 /// `true` when the parse site called `reconstruct_rect` (whose
3521 /// `edges_rect` differs from `edges` even at `bw == bh`).
3522 rect: bool,
3523 mode: usize,
3524 angle_delta: i32,
3525 reach: Reach,
3526 residual: Residual,
3527 cfl: Option<(i32, CflSrc)>,
3528 filter_intra: Option<usize>,
3529 smooth_neighbor: bool,
3530 /// The palette/intrabc prediction override, taken off
3531 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
3532 /// from that slot by the replay.
3533 pred: Option<Vec<u16>>,
3534 },
3535 Mc {
3536 plane: usize,
3537 x: usize,
3538 y: usize,
3539 stride: usize,
3540 w: usize,
3541 h: usize,
3542 prediction: PredSrc,
3543 residual: Residual,
3544 },
3545}
3546
3547/// The three planes of the tile currently being decoded, as raw pointers.
3548///
3549/// corner-cut: at one reconstruction thread a recorded write must cost
3550/// nothing -- deferring it to the end of the superblock is +1.2%
3551/// instructions and +4.5% wall on 4K, because the residual is written at
3552/// parse and read back cache-cold at replay. So the recorded op is performed
3553/// at the push site instead, through the pointers the tile decoder registers
3554/// once ([`ReconInline`]), which is the same thread, the same order and the
3555/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
3556/// stack still holds aliases them, exactly the [`crate::par::Shared`]
3557/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
3558/// threading the three planes down every `read_plane`/`read_inter_plane`
3559/// call site (~40) so the push site owns the borrow it writes through.
3560#[derive(Clone, Copy)]
3561pub(crate) struct ReconPlanes(
3562 *mut PlaneBuf<'static>,
3563 *mut PlaneBuf<'static>,
3564 *mut PlaneBuf<'static>,
3565);
3566
3567// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
3568// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
3569// value travelling is `None`; the pointers never leave the tile decoder's
3570// own thread.
3571#[allow(unsafe_code)]
3572unsafe impl Send for ReconPlanes {}
3573// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
3574// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
3575// contract, one superblock per band instead of one row band.
3576#[allow(unsafe_code)]
3577unsafe impl Sync for ReconPlanes {}
3578
3579/// Registers the tile's planes for inline reconstruction and unregisters them
3580/// on every exit from the tile decoder, including the `?` ones -- a stale
3581/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
3582/// tile.
3583pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
3584
3585#[allow(unsafe_code)]
3586impl<'a> ReconInline<'a> {
3587 /// Installs the guard for this tile when reconstruction is inline
3588 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
3589 /// to the queue instead, for the wavefront workers to replay.
3590 fn install(
3591 fctx: &'a crate::decode::FrameCtx,
3592 y: &mut PlaneBuf<'static>,
3593 u: &mut PlaneBuf<'static>,
3594 v: &mut PlaneBuf<'static>,
3595 ) -> Option<Self> {
3596 if crate::par::recon_threads() != 1 {
3597 return None;
3598 }
3599 // SAFETY: the planes are locals of the tile decoder and outlive the
3600 // guard, which is dropped on every exit from it (including `?`); see
3601 // [`ReconPlanes`] for the aliasing trade-off.
3602 let planes = ReconPlanes(
3603 std::ptr::from_mut(y),
3604 std::ptr::from_mut(u),
3605 std::ptr::from_mut(v),
3606 );
3607 fctx.recon_planes.with(|c| c.set(Some(planes)));
3608 Some(Self(fctx))
3609 }
3610}
3611
3612impl Drop for ReconInline<'_> {
3613 fn drop(&mut self) {
3614 self.0.recon_planes.with(|c| c.set(None));
3615 }
3616}
3617
3618#[allow(unsafe_code)]
3619fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
3620 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
3621 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
3622 // the parse site would have performed itself before lane-wave1.
3623 // The inline path never records coefficients (the transform runs at
3624 // the push site), so the arena is not read here.
3625 unsafe {
3626 exec_op(
3627 op,
3628 &mut *y,
3629 &mut *u,
3630 &mut *v,
3631 &mut Default::default(),
3632 &[],
3633 &[],
3634 fctx,
3635 )
3636 };
3637 return;
3638 }
3639 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
3640}
3641
3642/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
3643/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
3644///
3645/// The parser keeps parsing and never touches the planes; each superblock's
3646/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
3647/// `(row, column)` inside the tile (128x128 superblocks are one job for all
3648/// four of their 64x64 visits, since a 128 block writes across quadrants).
3649/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
3650/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
3651/// every pixel an intra predictor can read (its edges reach one block right
3652/// along the row above and one block down the column to the left, both
3653/// inside those two neighbours) and every CfL AC read (this block's own
3654/// luma, written by this same job). Jobs are handed out in raster order, so
3655/// the oldest outstanding one always has its dependencies met: no deadlock.
3656///
3657/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
3658/// `thread_local!` and miss every worker, which is why the default is 1.
3659pub(crate) struct WaveState {
3660 q: std::sync::Mutex<WaveQueue>,
3661 cv: std::sync::Condvar,
3662 planes: ReconPlanes,
3663 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
3664 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
3665 bit_depth: u8,
3666 enable_edge_filter: bool,
3667 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
3668 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3669 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3670 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3671 /// default halved every worker's chroma reference position and lost the
3672 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3673 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3674 subsampling: (u8, u8),
3675 last_col: usize,
3676}
3677
3678struct WaveQueue {
3679 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3680 /// row's front job can ever be runnable -- a job waits on its own left
3681 /// neighbour -- so a worker takes the lowest row whose front job's
3682 /// dependencies are met. Popping the raster-oldest job instead (what
3683 /// this replaced) put every worker on the SAME row, where the wavefront
3684 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3685 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3686 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3687 /// walking it.
3688 queued: usize,
3689 /// Per superblock row, the last column reconstructed (-1 = none yet).
3690 done: Vec<isize>,
3691 /// Per superblock row, the last column PARSED (submitted, whether or not
3692 /// it recorded any write) and the last column actually pushed as a job
3693 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3694 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3695 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3696 last_sub: Vec<isize>,
3697 last_push: Vec<isize>,
3698 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3699 active: usize,
3700 closed: bool,
3701 /// lane-sballoc: the three per-superblock buffers a finished job hands
3702 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3703 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3704 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3705 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3706 /// inside the queue's own mutex, which both sides already take.
3707 free: Vec<JobBufs>,
3708 free_cap: usize,
3709}
3710
3711/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3712type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3713
3714impl WaveQueue {
3715 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3716 /// or `None` (with the blocking condition counted when instrumented).
3717 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, ReconJob)> {
3718 let mut blocked: Option<bool> = None;
3719 for r in 0..self.rows.len() {
3720 let Some(front) = self.rows[r].front() else {
3721 continue;
3722 };
3723 let c = front.0;
3724 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3725 let left = c == 0 || self.done[r] >= c as isize - 1;
3726 if above && left {
3727 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3728 self.queued -= 1;
3729 return Some((r, c, job));
3730 }
3731 if blocked.is_none() {
3732 blocked = Some(above);
3733 }
3734 }
3735 if stats {
3736 match blocked {
3737 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3738 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3739 None => 0,
3740 };
3741 }
3742 None
3743 }
3744}
3745
3746/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3747/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3748/// empty queue), how far ahead the parse thread is, and how often the two
3749/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3750/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3751/// whole run.
3752const WS_SLOTS: usize = 16;
3753use std::sync::atomic::AtomicU64;
3754use std::sync::atomic::Ordering::Relaxed;
3755static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3756static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3757static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3758static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3759static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3760static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3761/// Parse-thread time between two submits, i.e. everything parse still does
3762/// itself (symbol decode plus the predictions not deferred).
3763static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3764/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3765/// (the intrabc/interintra reads) and at the tile's end.
3766static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3767static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3768static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3769static WS_TILES: AtomicU64 = AtomicU64::new(0);
3770
3771fn wave_stats() -> bool {
3772 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3773 match ON.load(Relaxed) {
3774 0 => {
3775 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3776 .map(|v| v.trim() == "1")
3777 .unwrap_or(false);
3778 ON.store(1 + u8::from(on), Relaxed);
3779 on
3780 }
3781 n => n == 2,
3782 }
3783}
3784
3785fn wave_stats_dump() {
3786 let ms = |n: u64| n as f64 / 1e6;
3787 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3788 for i in 0..WS_SLOTS {
3789 let jobs = WS_JOBS[i].load(Relaxed);
3790 if jobs == 0 {
3791 continue;
3792 }
3793 s += &format!(
3794 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3795 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3796 ms(WS_BUSY[i].load(Relaxed)),
3797 ms(WS_WAIT[i].load(Relaxed)),
3798 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3799 );
3800 }
3801 s += &format!(
3802 " | pipe={}/{}",
3803 PIPE_FRAMES.load(Relaxed),
3804 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3805 );
3806 s += &format!(
3807 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3808 ms(WS_PARSE.load(Relaxed)),
3809 ms(WS_BARRIER.load(Relaxed)),
3810 WS_BARRIERS.load(Relaxed),
3811 ms(WS_DRAIN.load(Relaxed)),
3812 WS_BLOCK_ABOVE.load(Relaxed),
3813 WS_BLOCK_LEFT.load(Relaxed),
3814 );
3815 eprintln!("{s}");
3816}
3817
3818#[allow(unsafe_code)]
3819fn wave_worker(st: &WaveState, idx: usize) {
3820 let fctx = FrameCtx::new();
3821 fctx.bit_depth.set(st.bit_depth);
3822 fctx.enable_edge_filter.set(st.enable_edge_filter);
3823 let (sx, sy) = st.subsampling;
3824 fctx.subsampling_x.set(sx);
3825 fctx.subsampling_y.set(sy);
3826 let stats = wave_stats();
3827 let slot = idx.min(WS_SLOTS - 1);
3828 loop {
3829 let t0 = std::time::Instant::now();
3830 let mut q = st.q.lock().unwrap();
3831 let (r, c, job) = loop {
3832 if let Some(job) = q.take_runnable(st.last_col, stats) {
3833 break job;
3834 }
3835 if q.closed && q.queued == 0 {
3836 return;
3837 }
3838 q = st.cv.wait(q).unwrap();
3839 };
3840 q.active += 1;
3841 drop(q);
3842 if stats {
3843 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3844 WS_JOBS[slot].fetch_add(1, Relaxed);
3845 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3846 }
3847 let t1 = std::time::Instant::now();
3848 let ReconPlanes(y, u, v) = st.planes;
3849 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3850 // every superblock that could have written or be reading them is
3851 // complete by the wavefront rule above.
3852 let mut cur: [Vec<u16>; 3] = Default::default();
3853 let ReconJob {
3854 mut ops,
3855 mut coeffs,
3856 mut preds,
3857 } = job;
3858 unsafe {
3859 for op in ops.drain(..) {
3860 exec_op(
3861 op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx,
3862 );
3863 }
3864 }
3865 if stats {
3866 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3867 }
3868 coeffs.clear();
3869 preds.clear();
3870 let mut q = st.q.lock().unwrap();
3871 // lane-sballoc: hand the three buffers back for the next submit.
3872 if q.free.len() < q.free_cap {
3873 q.free.push((ops, coeffs, preds));
3874 }
3875 q.done[r] = c as isize;
3876 q.active -= 1;
3877 st.cv.notify_all();
3878 }
3879}
3880
3881/// Installs the wavefront for one tile and joins its workers on every exit
3882/// from the tile decoder, including the `?` ones -- the jobs hold raw
3883/// pointers into the tile's planes, so no worker may outlive them.
3884/// (lane-pool1: the workers come from this thread's persistent pool, so a
3885/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3886/// with fresh scratch.)
3887pub(crate) struct WaveGuard<'a>(
3888 &'a crate::decode::FrameCtx,
3889 Option<crate::par::Batch<'static>>,
3890);
3891
3892#[allow(unsafe_code)]
3893impl<'a> WaveGuard<'a> {
3894 fn install(
3895 fctx: &'a crate::decode::FrameCtx,
3896 y: &mut PlaneBuf<'static>,
3897 u: &mut PlaneBuf<'static>,
3898 v: &mut PlaneBuf<'static>,
3899 rows: usize,
3900 cols: usize,
3901 ) -> Option<Self> {
3902 let threads = crate::par::recon_threads();
3903 if threads == 1 || rows == 0 || cols == 0 {
3904 return None;
3905 }
3906 let st = std::sync::Arc::new(WaveState {
3907 q: std::sync::Mutex::new(WaveQueue {
3908 rows: (0..rows)
3909 .map(|_| std::collections::VecDeque::new())
3910 .collect(),
3911 queued: 0,
3912 done: vec![-1; rows],
3913 last_sub: vec![-1; rows],
3914 last_push: vec![-1; rows],
3915 active: 0,
3916 closed: false,
3917 free: Vec::new(),
3918 free_cap: threads + 2,
3919 }),
3920 cv: std::sync::Condvar::new(),
3921 // SAFETY: the planes are locals of the tile decoder and outlive
3922 // this guard, which joins every worker in `drop`.
3923 planes: ReconPlanes(
3924 std::ptr::from_mut(y),
3925 std::ptr::from_mut(u),
3926 std::ptr::from_mut(v),
3927 ),
3928 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3929 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3930 subsampling: (
3931 fctx.subsampling_x.with(std::cell::Cell::get),
3932 fctx.subsampling_y.with(std::cell::Cell::get),
3933 ),
3934 last_col: cols - 1,
3935 });
3936 let batch = crate::par::Batch::new("ec-av1-recon");
3937 for idx in 0..threads {
3938 let st = std::sync::Arc::clone(&st);
3939 batch.submit(move || wave_worker(&st, idx));
3940 }
3941 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3942 fctx.wave_mark
3943 .with(|c| c.set(Some(std::time::Instant::now())));
3944 Some(Self(fctx, Some(batch)))
3945 }
3946}
3947
3948impl Drop for WaveGuard<'_> {
3949 fn drop(&mut self) {
3950 let st = self.0.wave.with(|w| w.borrow_mut().take());
3951 if let Some(st) = st {
3952 st.q.lock().unwrap().closed = true;
3953 st.cv.notify_all();
3954 }
3955 let t0 = std::time::Instant::now();
3956 // Dropping the batch waits every worker out, as the joins did.
3957 drop(self.1.take());
3958 if wave_stats() {
3959 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3960 WS_TILES.fetch_add(1, Relaxed);
3961 wave_stats_dump();
3962 }
3963 }
3964}
3965
3966/// An empty buffer for the next superblock: the recycled one when it is at
3967/// least as big as the superblock just parsed, else a fresh sized one
3968/// (lane-sballoc; `v` is always empty).
3969fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3970 if v.capacity() < cap {
3971 v.reserve_exact(cap - v.len());
3972 }
3973 v
3974}
3975
3976/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3977/// when there is no wavefront (one reconstruction thread), in which case the
3978/// caller replays them itself.
3979fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3980 let st = fctx.wave.with(|w| w.borrow().clone());
3981 let Some(st) = st else { return false };
3982 // lane-blockmem: the op list is replaced sized for the next superblock,
3983 // exactly as the two arenas below are -- taking it left a zero-capacity
3984 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3985 // every superblock.
3986 // lane-sballoc: the replacement comes from the finished jobs' free list
3987 // when there is one (warm capacity, already faulted in); only the first
3988 // superblocks of a tile allocate.
3989 let mut q = st.q.lock().unwrap();
3990 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3991 let ops = fctx.recon_ops.with(|c| {
3992 let mut c = c.borrow_mut();
3993 let cap = c.len();
3994 std::mem::replace(&mut *c, reuse(sops, cap))
3995 });
3996 // The job owns its coefficients: the arena is replaced by an empty one
3997 // sized for the next superblock, so parse never regrows from nothing and
3998 // the worker frees this buffer once, instead of once per unit.
3999 let coeffs = fctx.coeff_arena.with(|c| {
4000 let mut c = c.borrow_mut();
4001 let cap = c.len();
4002 std::mem::replace(&mut *c, reuse(scoeffs, cap))
4003 });
4004 let preds = fctx.pred_arena.with(|c| {
4005 let mut c = c.borrow_mut();
4006 let cap = c.len();
4007 std::mem::replace(&mut *c, reuse(spreds, cap))
4008 });
4009 {
4010 if (c as isize) > q.last_sub[r] {
4011 q.last_sub[r] = c as isize;
4012 }
4013 if !ops.is_empty() {
4014 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
4015 q.queued += 1;
4016 q.last_push[r] = c as isize;
4017 }
4018 drop(q);
4019 st.cv.notify_all();
4020 }
4021 if wave_stats() {
4022 let now = std::time::Instant::now();
4023 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
4024 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
4025 }
4026 }
4027 true
4028}
4029
4030/// Waits until every submitted job is reconstructed, so the parser may read
4031/// the planes itself (the intrabc source fetch and the interintra intra
4032/// predictor -- see [`flush_recon`]).
4033fn wave_barrier(fctx: &crate::decode::FrameCtx) {
4034 let st = fctx.wave.with(|w| w.borrow().clone());
4035 let Some(st) = st else { return };
4036 let stats = wave_stats();
4037 let t0 = std::time::Instant::now();
4038 let mut q = st.q.lock().unwrap();
4039 while q.queued > 0 || q.active > 0 {
4040 q = st.cv.wait(q).unwrap();
4041 }
4042 drop(q);
4043 if stats {
4044 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
4045 WS_BARRIERS.fetch_add(1, Relaxed);
4046 }
4047}
4048
4049/// Performs an intra write at its push site when the tile registered its
4050/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
4051#[allow(unsafe_code)]
4052#[allow(clippy::too_many_arguments)]
4053fn inline_intra(
4054 plane: usize,
4055 x: usize,
4056 oy: usize,
4057 bw: usize,
4058 bh: usize,
4059 rect: bool,
4060 mode: usize,
4061 angle_delta: i32,
4062 reach: Reach,
4063 residual: &[i32],
4064 cfl: Option<(i32, CflSrc)>,
4065 filter_intra: Option<usize>,
4066 smooth_neighbor: bool,
4067 fctx: &crate::decode::FrameCtx,
4068) -> bool {
4069 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
4070 return false;
4071 };
4072 let pred = take_palette_pred(fctx);
4073 // SAFETY: see [`ReconPlanes`].
4074 unsafe {
4075 exec_intra(
4076 &mut *y,
4077 &mut *u,
4078 &mut *v,
4079 plane,
4080 x,
4081 oy,
4082 bw,
4083 bh,
4084 rect,
4085 mode,
4086 angle_delta,
4087 reach,
4088 residual,
4089 cfl,
4090 filter_intra,
4091 smooth_neighbor,
4092 pred,
4093 fctx,
4094 );
4095 }
4096 true
4097}
4098
4099/// [`inline_intra`] for a motion-compensated write.
4100#[allow(unsafe_code)]
4101#[allow(clippy::too_many_arguments)]
4102fn inline_mc(
4103 plane: usize,
4104 x: usize,
4105 oy: usize,
4106 stride: usize,
4107 w: usize,
4108 h: usize,
4109 prediction: &[u16],
4110 residual: &[i32],
4111 fctx: &crate::decode::FrameCtx,
4112) -> bool {
4113 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
4114 return false;
4115 };
4116 // SAFETY: see [`ReconPlanes`].
4117 unsafe {
4118 exec_mc(
4119 &mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx,
4120 );
4121 }
4122 true
4123}
4124
4125/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
4126#[allow(clippy::too_many_arguments)]
4127fn push_intra(
4128 plane: usize,
4129 x: usize,
4130 y: usize,
4131 side: usize,
4132 mode: usize,
4133 angle_delta: i32,
4134 reach: Reach,
4135 residual: &[i32],
4136 cfl: Option<(i32, CflSrc)>,
4137 filter_intra: Option<usize>,
4138 smooth_neighbor: bool,
4139 fctx: &crate::decode::FrameCtx,
4140) {
4141 if inline_intra(
4142 plane,
4143 x,
4144 y,
4145 side,
4146 side,
4147 false,
4148 mode,
4149 angle_delta,
4150 reach,
4151 residual,
4152 cfl,
4153 filter_intra,
4154 smooth_neighbor,
4155 fctx,
4156 ) {
4157 return;
4158 }
4159 let pred = take_palette_pred(fctx);
4160 push_op(
4161 fctx,
4162 ReconOp::Intra {
4163 plane,
4164 x,
4165 y,
4166 bw: side,
4167 bh: side,
4168 rect: false,
4169 mode,
4170 angle_delta,
4171 reach,
4172 residual: Residual::done(residual, fctx),
4173 cfl,
4174 filter_intra,
4175 smooth_neighbor,
4176 pred,
4177 },
4178 );
4179}
4180
4181/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
4182#[allow(clippy::too_many_arguments)]
4183fn push_intra_rect(
4184 plane: usize,
4185 x: usize,
4186 y: usize,
4187 bw: usize,
4188 bh: usize,
4189 mode: usize,
4190 angle_delta: i32,
4191 reach: Reach,
4192 residual: &[i32],
4193 cfl: Option<(i32, CflSrc)>,
4194 filter_intra: Option<usize>,
4195 smooth_neighbor: bool,
4196 fctx: &crate::decode::FrameCtx,
4197) {
4198 if inline_intra(
4199 plane,
4200 x,
4201 y,
4202 bw,
4203 bh,
4204 true,
4205 mode,
4206 angle_delta,
4207 reach,
4208 residual,
4209 cfl,
4210 filter_intra,
4211 smooth_neighbor,
4212 fctx,
4213 ) {
4214 return;
4215 }
4216 let pred = take_palette_pred(fctx);
4217 push_op(
4218 fctx,
4219 ReconOp::Intra {
4220 plane,
4221 x,
4222 y,
4223 bw,
4224 bh,
4225 rect: true,
4226 mode,
4227 angle_delta,
4228 reach,
4229 residual: Residual::done(residual, fctx),
4230 cfl,
4231 filter_intra,
4232 smooth_neighbor,
4233 pred,
4234 },
4235 );
4236}
4237
4238/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
4239fn push_mc(
4240 plane: usize,
4241 x: usize,
4242 y: usize,
4243 side: usize,
4244 prediction: Pred<'_>,
4245 residual: &[i32],
4246 fctx: &crate::decode::FrameCtx,
4247) {
4248 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
4249}
4250
4251/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
4252#[allow(clippy::too_many_arguments)]
4253#[track_caller]
4254fn push_mc_rect(
4255 plane: usize,
4256 x: usize,
4257 y: usize,
4258 stride: usize,
4259 w: usize,
4260 h: usize,
4261 prediction: Pred<'_>,
4262 residual: &[i32],
4263 fctx: &crate::decode::FrameCtx,
4264) {
4265 // lane-av1ibcfork: the PUSH site of an MC/inter write. The executed rung
4266 // (`EC_MCWR`, in `reconstruct_mc_rect`) can only name the dispatch, so
4267 // this is what names the block decoder that asked for the write -- the
4268 // only thing that distinguishes two writes of the same shape. It is what
4269 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block
4270 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring
4271 // block's reconstruction (lanes/av1ibcfork.report.md).
4272 if crate::envflags::env_flag!("EC_MCPUSH") {
4273 eprintln!(
4274 "EC_MCPUSH plane={plane} x={x} y={y} stride={stride} w={w} h={h} \
4275 res_len={} at {}",
4276 residual.len(),
4277 std::panic::Location::caller()
4278 );
4279 }
4280 let (src, stride) = match prediction.inline(stride) {
4281 Some(v) => v,
4282 None => {
4283 let Pred::Cur {
4284 plane: sp,
4285 stride: ss,
4286 off,
4287 } = prediction
4288 else {
4289 unreachable!()
4290 };
4291 push_op(
4292 fctx,
4293 ReconOp::Mc {
4294 plane,
4295 x,
4296 y,
4297 stride: ss,
4298 w,
4299 h,
4300 prediction: PredSrc::Cur {
4301 plane: sp,
4302 off,
4303 src: ss,
4304 },
4305 residual: Residual::done(residual, fctx),
4306 },
4307 );
4308 return;
4309 }
4310 };
4311 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
4312 return;
4313 }
4314 push_op(
4315 fctx,
4316 ReconOp::Mc {
4317 plane,
4318 x,
4319 y,
4320 stride,
4321 w,
4322 h,
4323 // The whole window `reconstruct_mc_rect` reads at `stride`, not
4324 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
4325 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
4326 residual: Residual::done(residual, fctx),
4327 },
4328 );
4329}
4330
4331/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
4332/// thread the transform runs here, exactly as before; on the wavefront it
4333/// travels with the op and runs on the worker (lane-wave3).
4334#[allow(clippy::too_many_arguments)]
4335fn push_intra_tx(
4336 plane: usize,
4337 x: usize,
4338 y: usize,
4339 bw: usize,
4340 bh: usize,
4341 rect: bool,
4342 mode: usize,
4343 angle_delta: i32,
4344 reach: Reach,
4345 tx: TxParams,
4346 grid: &[i32],
4347 cfl: Option<(i32, CflSrc)>,
4348 filter_intra: Option<usize>,
4349 smooth_neighbor: bool,
4350 fctx: &crate::decode::FrameCtx,
4351) {
4352 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4353 inline_intra(
4354 plane,
4355 x,
4356 y,
4357 bw,
4358 bh,
4359 rect,
4360 mode,
4361 angle_delta,
4362 reach,
4363 &tx.run(grid),
4364 cfl,
4365 filter_intra,
4366 smooth_neighbor,
4367 fctx,
4368 );
4369 return;
4370 }
4371 let pred = take_palette_pred(fctx);
4372 push_op(
4373 fctx,
4374 ReconOp::Intra {
4375 plane,
4376 x,
4377 y,
4378 bw,
4379 bh,
4380 rect,
4381 mode,
4382 angle_delta,
4383 reach,
4384 residual: Residual::coeffs(tx, grid, fctx),
4385 cfl,
4386 filter_intra,
4387 smooth_neighbor,
4388 pred,
4389 },
4390 );
4391}
4392
4393/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
4394#[allow(clippy::too_many_arguments)]
4395fn push_mc_rect_tx(
4396 plane: usize,
4397 x: usize,
4398 y: usize,
4399 stride: usize,
4400 w: usize,
4401 h: usize,
4402 prediction: Pred<'_>,
4403 tx: TxParams,
4404 grid: &[i32],
4405 fctx: &crate::decode::FrameCtx,
4406) {
4407 // lane-wave4: a deferred prediction is not there to be windowed -- the
4408 // op carries its offset into the block's prediction instead, and the
4409 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
4410 // both buffers at one stride).
4411 let (prediction, stride) = match prediction.inline(stride) {
4412 Some(v) => v,
4413 None => {
4414 let Pred::Cur {
4415 plane: sp,
4416 stride: ss,
4417 off,
4418 } = prediction
4419 else {
4420 unreachable!()
4421 };
4422 let mut tx = tx;
4423 tx.stride = 0;
4424 push_op(
4425 fctx,
4426 ReconOp::Mc {
4427 plane,
4428 x,
4429 y,
4430 stride: w,
4431 w,
4432 h,
4433 prediction: PredSrc::Cur {
4434 plane: sp,
4435 off,
4436 src: ss,
4437 },
4438 residual: Residual::coeffs(tx, grid, fctx),
4439 },
4440 );
4441 return;
4442 }
4443 };
4444 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4445 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
4446 // stride, so a prediction handed over at the block's stride (a var-tx
4447 // unit's window, lane-wave4) has to be densified for a dense residual
4448 // -- which is exactly what the recorded path below does.
4449 let residual = tx.run(grid);
4450 let res_stride = if tx.stride == 0 { w } else { tx.stride };
4451 let window;
4452 let prediction = if stride == res_stride {
4453 prediction
4454 } else {
4455 debug_assert_eq!(res_stride, w);
4456 let mut win = Vec::with_capacity(w * h);
4457 for row in 0..h {
4458 win.extend_from_slice(&prediction[row * stride..][..w]);
4459 }
4460 window = win;
4461 &window[..]
4462 };
4463 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
4464 return;
4465 }
4466 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
4467 // two buffers at `stride`, so the record carries that window densely
4468 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
4469 // copied 64*64 samples on the PARSING thread before. The residual is then
4470 // produced dense too (`TxParams::stride = 0`), which is the same numbers
4471 // in the same places at stride `w`.
4472 let off = fctx.pred_arena.with(|a| {
4473 let mut a = a.borrow_mut();
4474 let off = a.len();
4475 for row in 0..h {
4476 a.extend_from_slice(&prediction[row * stride..][..w]);
4477 }
4478 off as u32
4479 });
4480 let mut tx = tx;
4481 tx.stride = 0;
4482 push_op(
4483 fctx,
4484 ReconOp::Mc {
4485 plane,
4486 x,
4487 y,
4488 stride: w,
4489 w,
4490 h,
4491 prediction: PredSrc::Owned(off, (w * h) as u32),
4492 residual: Residual::coeffs(tx, grid, fctx),
4493 },
4494 );
4495}
4496
4497/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
4498/// and empties the queue (lane-wave1 step (i)).
4499///
4500/// Called at the top of each superblock visit and at the end of each tile, so
4501/// a whole superblock's parsing runs with no plane access at all; the two
4502/// parse-time pixel READS that survive -- the intrabc source fetch and the
4503/// interintra intra predictor -- flush ahead of themselves instead, which
4504/// keeps them byte-exact and names exactly what step (ii) still has to move.
4505fn flush_recon(
4506 fctx: &crate::decode::FrameCtx,
4507 y: &mut PlaneBuf<'static>,
4508 u: &mut PlaneBuf<'static>,
4509 v: &mut PlaneBuf<'static>,
4510) {
4511 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
4512 // writes in place, not just this superblock's queue.
4513 wave_barrier(fctx);
4514 let mut ops = fctx
4515 .recon_spare
4516 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4517 fctx.recon_ops
4518 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
4519 let mut coeffs = fctx
4520 .coeff_spare
4521 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4522 fctx.coeff_arena
4523 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
4524 let mut preds = fctx
4525 .pred_spare
4526 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4527 fctx.pred_arena
4528 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
4529 let mut cur: [Vec<u16>; 3] = Default::default();
4530 for op in ops.drain(..) {
4531 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
4532 }
4533 coeffs.clear();
4534 preds.clear();
4535 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
4536 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
4537 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
4538}
4539
4540/// Performs one recorded write: the body [`flush_recon`] replays, and the
4541/// body [`push_op`] runs immediately when reconstruction is inline.
4542fn exec_op(
4543 op: ReconOp,
4544 y: &mut PlaneBuf<'static>,
4545 u: &mut PlaneBuf<'static>,
4546 v: &mut PlaneBuf<'static>,
4547 cur: &mut [Vec<u16>; 3],
4548 coeffs: &[i32],
4549 preds: &[u16],
4550 fctx: &crate::decode::FrameCtx,
4551) {
4552 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
4553 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
4554 // alone. It makes the encoder's own streams garbage, so it is a
4555 // MEASUREMENT rung only -- what it measures is how much of the encoder's
4556 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
4557 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
4558 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
4559 // stage and the parse plus the neighbour grids are the other 94%. That
4560 // is why handing the decoder the encoder's own reconstruction cannot
4561 // shrink the stage: only publishing the per-mi neighbour state the
4562 // filters read (and so never parsing at all) can.
4563 if crate::envflags::env_flag!("EC_AV1_NORECON") {
4564 return;
4565 }
4566 let mut scratch = Vec::new();
4567 match op {
4568 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
4569 ReconOp::Intra {
4570 plane,
4571 x,
4572 y: oy,
4573 bw,
4574 bh,
4575 rect,
4576 mode,
4577 angle_delta,
4578 reach,
4579 residual,
4580 cfl,
4581 filter_intra,
4582 smooth_neighbor,
4583 pred,
4584 } => exec_intra(
4585 y,
4586 u,
4587 v,
4588 plane,
4589 x,
4590 oy,
4591 bw,
4592 bh,
4593 rect,
4594 mode,
4595 angle_delta,
4596 reach,
4597 residual.resolve(coeffs, &mut scratch),
4598 cfl,
4599 filter_intra,
4600 smooth_neighbor,
4601 pred,
4602 fctx,
4603 ),
4604 ReconOp::Mc {
4605 plane,
4606 x,
4607 y: oy,
4608 stride,
4609 w,
4610 h,
4611 prediction,
4612 residual,
4613 } => {
4614 let residual = residual.resolve(coeffs, &mut scratch);
4615 match prediction {
4616 PredSrc::Owned(off, len) => {
4617 let p = &preds[off as usize..][..len as usize];
4618 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
4619 }
4620 PredSrc::Cur {
4621 plane: sp,
4622 off,
4623 src,
4624 } => {
4625 let block = std::mem::take(&mut cur[sp]);
4626 if src == stride {
4627 exec_mc(
4628 y,
4629 u,
4630 v,
4631 plane,
4632 x,
4633 oy,
4634 stride,
4635 w,
4636 h,
4637 &block[off..],
4638 residual,
4639 fctx,
4640 );
4641 } else {
4642 // A transform unit's residual is dense, so its window
4643 // of the block prediction is taken out dense too --
4644 // the copy the parsing thread used to make, made here.
4645 let mut window = Vec::with_capacity(w * h);
4646 for row in 0..h {
4647 window.extend_from_slice(&block[off + row * src..][..w]);
4648 }
4649 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
4650 }
4651 cur[sp] = block;
4652 }
4653 }
4654 }
4655 }
4656}
4657
4658/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
4659/// path ([`push_op`]'s registered planes) reaches it without ever building
4660/// the record -- which is what keeps one reconstruction thread at the cost of
4661/// the pre-lane-wave1 decoder.
4662#[allow(clippy::too_many_arguments)]
4663fn exec_intra(
4664 y: &mut PlaneBuf<'static>,
4665 u: &mut PlaneBuf<'static>,
4666 v: &mut PlaneBuf<'static>,
4667 plane: usize,
4668 x: usize,
4669 oy: usize,
4670 bw: usize,
4671 bh: usize,
4672 rect: bool,
4673 mode: usize,
4674 angle_delta: i32,
4675 reach: Reach,
4676 residual: &[i32],
4677 cfl: Option<(i32, CflSrc)>,
4678 filter_intra: Option<usize>,
4679 smooth_neighbor: bool,
4680 pred: Option<Vec<u16>>,
4681 fctx: &crate::decode::FrameCtx,
4682) {
4683 // The CfL AC signal is read HERE, off the luma that has already been
4684 // written for this block -- at parse time it would have been the previous
4685 // frame's samples.
4686 let ac = cfl.map(|(alpha, src)| {
4687 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
4688 (alpha, sig)
4689 });
4690 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
4691 let target: &mut PlaneBuf<'static> = match plane {
4692 0 => &mut *y,
4693 1 => &mut *u,
4694 _ => &mut *v,
4695 };
4696 // lane-av1cmpaudit: label the in-flight reconstruction's plane for the
4697 // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`).
4698 // Saved and restored so the rung reports THIS call's plane even under
4699 // nesting, and so both of exec_intra's return paths need no cleanup.
4700 let prev_plane = RECON_PLANE.with(|c| c.replace(plane));
4701 let _plane_guard = PlaneGuard(prev_plane);
4702 if rect {
4703 target.reconstruct_rect(
4704 x,
4705 oy,
4706 bw,
4707 bh,
4708 mode,
4709 angle_delta,
4710 reach,
4711 residual,
4712 cfl,
4713 filter_intra,
4714 smooth_neighbor,
4715 pred,
4716 fctx,
4717 );
4718 } else {
4719 target.reconstruct(
4720 x,
4721 oy,
4722 bw,
4723 mode,
4724 angle_delta,
4725 reach,
4726 residual,
4727 cfl,
4728 filter_intra,
4729 smooth_neighbor,
4730 pred,
4731 fctx,
4732 );
4733 }
4734}
4735
4736/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4737#[allow(clippy::too_many_arguments)]
4738fn exec_mc(
4739 y: &mut PlaneBuf<'static>,
4740 u: &mut PlaneBuf<'static>,
4741 v: &mut PlaneBuf<'static>,
4742 plane: usize,
4743 x: usize,
4744 oy: usize,
4745 stride: usize,
4746 w: usize,
4747 h: usize,
4748 prediction: &[u16],
4749 residual: &[i32],
4750 fctx: &crate::decode::FrameCtx,
4751) {
4752 let target: &mut PlaneBuf<'static> = match plane {
4753 0 => &mut *y,
4754 1 => &mut *u,
4755 _ => &mut *v,
4756 };
4757 target.reconstruct_mc_rect(x, oy, plane, stride, w, h, prediction, residual, fctx);
4758}
4759
4760thread_local! {
4761 /// The current frame's `mi` grid, kept only while a frame header set
4762 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4763 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4764 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4765 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4766 /// does not allow intrabc (so nothing is paid for it).
4767 ///
4768 /// corner-cut: only [`decode_block`] (the square path) records into it,
4769 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4770 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4771 /// be wrong there; upgrade = record from the rect/leaf paths too.
4772 /// The block vector [`read_intra_mode`] just decoded, handed to
4773 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4774 /// which the alternative -- a tenth tuple member through every caller --
4775 /// already avoids). Always `.take()`n by the block that reads it.
4776 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4777 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4778 /// returns too, so it counts reads, not reconstructions (a refused block
4779 /// is never reconstructed).
4780 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4781}
4782// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4783// an intrabc block's chroma reads can inherit it (see
4784// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4785// through that one arming site.
4786// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4787// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4788// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4789// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4790// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4791// intrabc block's two chroma [`read_plane`] calls; the type decides the
4792// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4793// -- getting it wrong desyncs the chroma coefficients, it is not a
4794// reconstruction-only detail.
4795
4796/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4797/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4798/// needs no separate plumbing to reach the rect-strip mode reader.
4799fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4800 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4801}
4802
4803thread_local! {
4804 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4805 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4806 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4807 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4808}
4809
4810/// Current value of [`RECT_INTRABC_READS`].
4811pub(crate) fn rect_intrabc_reads() -> usize {
4812 RECT_INTRABC_READS.with(|c| c.get())
4813}
4814
4815/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4816#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4817pub(crate) fn reset_rect_intrabc_reads() {
4818 RECT_INTRABC_READS.with(|c| c.set(0));
4819}
4820
4821thread_local! {
4822 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4823 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4824 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4825}
4826
4827thread_local! {
4828 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4829 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4830 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4831 /// counter: zero means the gate's fixture no longer reaches the route).
4832 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4833 const { std::cell::Cell::new(0) };
4834}
4835
4836/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4838pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4839 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4840}
4841
4842/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4844pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4845 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4846}
4847
4848/// Current value of [`LEAF8_INTRABC_HITS`].
4849pub(crate) fn leaf8_intrabc_hits() -> usize {
4850 LEAF8_INTRABC_HITS.with(|c| c.get())
4851}
4852
4853/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4854#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4855pub(crate) fn reset_leaf8_intrabc_hits() {
4856 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4857}
4858
4859/// Current value of [`INTRABC_HITS`].
4860#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4861pub(crate) fn intrabc_hits() -> usize {
4862 INTRABC_HITS.with(|c| c.get())
4863}
4864
4865thread_local! {
4866 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4867 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4868 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4869 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4870 /// here. A non-zero value is what makes the disarm below load-bearing.
4871 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4872 const { std::cell::Cell::new(0) };
4873}
4874
4875/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4876#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4877pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4878 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4879}
4880
4881/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4882/// decode).
4883#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4884pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4885 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4886}
4887
4888thread_local! {
4889 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4890 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4891 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4892 /// Before the fix this route predicted intra-DC and every one of this
4893 /// fixture's 150 such cells differed from the oracle on both chroma
4894 /// planes.
4895 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4896 const { std::cell::Cell::new(0) };
4897}
4898
4899/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4900#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4901pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4902 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4903}
4904
4905/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4906/// decode).
4907#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4908pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4909 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4910}
4911
4912/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4913#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4914pub(crate) fn reset_intrabc_hits() {
4915 INTRABC_HITS.with(|c| c.set(0));
4916}
4917
4918thread_local! {
4919 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4920 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4921 /// that replaced the refusal "an intrabc block under TxMode::Select".
4922 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4923 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4924 /// sizes (not one square size across every leaf) -- the engagement
4925 /// counter proving a witness actually exercises the per-leaf reconstruct.
4926 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4927 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4928 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4929 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4930 /// symbol here desynced `warped.obu` at the very next block.
4931 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4932 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4933 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4934 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4935 /// this one).
4936 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4937 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4938 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4939 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4940 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4941 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4942 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4943 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4944 /// counts neither orientation nor the skip flag, so an arm that flipped
4945 /// to an all-skip stream (no residual reader at all) would stay green.
4946 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4947 const { std::cell::Cell::new([0, 0]) };
4948 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4949 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4950 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4951 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4952 /// invisible to every gate because they only counted CODED strips.
4953 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4954 const { std::cell::Cell::new([0, 0]) };
4955 /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized
4956 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4957 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no
4958 /// halving of its own. At 4:2:0 this is the same arithmetic as the halving,
4959 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4960 /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's
4961 /// chroma plane block.
4962 static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4963 const { std::cell::Cell::new(0) };
4964 /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block
4965 /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR
4966 /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes
4967 /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block,
4968 /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's
4969 /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a
4970 /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm:
4971 /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot
4972 /// be satisfied by any older route.
4973 static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell<usize> =
4974 const { std::cell::Cell::new(0) };
4975 /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips
4976 /// ([`decode_intrabc_owned_rect`]) whose chroma plane block was sized
4977 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4978 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies
4979 /// no halving of its own. At 4:2:0 the two forms are the same arithmetic,
4980 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4981 /// EXCLUSIVE to this arm: no other caller sizes a 128-root intra-BC
4982 /// strip's chroma plane block.
4983 static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4984 const { std::cell::Cell::new(0) };
4985}
4986
4987/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4988/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4989#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4990pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4991 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4992}
4993
4994/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4995/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4996#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4997pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4998 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4999}
5000
5001/// Current value of [`INTRABC_RECT_HITS`].
5002#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5003pub fn intrabc_rect_hits() -> usize {
5004 INTRABC_RECT_HITS.with(|c| c.get())
5005}
5006
5007/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
5008#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5009pub(crate) fn reset_intrabc_rect_hits() {
5010 INTRABC_RECT_HITS.with(|c| c.set(0));
5011 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
5012 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
5013 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
5014}
5015
5016/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
5017#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5018pub fn ibc_rect_chroma_footprint_444_hits() -> usize {
5019 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
5020}
5021
5022/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
5023#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5024pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() {
5025 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
5026}
5027
5028/// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
5029#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5030pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
5031 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
5032}
5033
5034/// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
5035#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5036pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
5037 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
5038}
5039
5040/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
5041#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5042pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
5043 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
5044}
5045
5046/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
5047#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5048pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
5049 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
5050}
5051
5052/// Current value of [`INTRABC_RECT_VARTX_HITS`].
5053#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5054pub fn intrabc_rect_vartx_hits() -> usize {
5055 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
5056}
5057
5058thread_local! {
5059 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
5060 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
5061 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
5062 /// guard (`decode_block_128rect`). A refused block bumps
5063 /// [`INTRABC_HITS`] but never this one.
5064 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5065 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
5066 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
5067 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
5068 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
5069 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
5070 /// side` model walked the 4:2:0 count on every axis, so this counter is
5071 /// the reach/arm witness for the per-axis walk.
5072 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
5073 const { std::cell::Cell::new(0) };
5074 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
5075 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
5076 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
5077 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
5078 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
5079 const { std::cell::Cell::new(0) };
5080}
5081
5082/// Current value of [`INTRABC_128RECT_HITS`].
5083#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5084pub fn intrabc_128rect_hits() -> usize {
5085 INTRABC_128RECT_HITS.with(|c| c.get())
5086}
5087
5088/// Zeroes [`INTRABC_128RECT_HITS`].
5089#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5090pub(crate) fn reset_intrabc_128rect_hits() {
5091 INTRABC_128RECT_HITS.with(|c| c.set(0));
5092}
5093
5094/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
5095#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5096pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
5097 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
5098}
5099
5100/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
5101#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5102pub fn intrabc_128rect_chunk_shape() -> usize {
5103 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
5104}
5105
5106/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
5107/// [`INTRABC_128RECT_CHUNK_SHAPE`].
5108#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5109pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
5110 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
5111 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
5112}
5113
5114/// Current value of [`INTRABC_VARTX_HITS`].
5115pub fn intrabc_vartx_hits() -> usize {
5116 INTRABC_VARTX_HITS.with(|c| c.get())
5117}
5118
5119/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
5120pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
5121 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
5122}
5123
5124/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
5125#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5126pub(crate) fn reset_intrabc_vartx_hits() {
5127 INTRABC_VARTX_HITS.with(|c| c.set(0));
5128}
5129
5130/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
5131/// decode).
5132#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5133pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
5134 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
5135}
5136
5137/// Current value of [`RECT_INTRABC_VARTX_HITS`].
5138#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5139pub fn rect_intrabc_vartx_hits() -> usize {
5140 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
5141}
5142
5143/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
5144/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
5145/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
5146/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
5147fn record_intrabc_mi(
5148 mi_r: usize,
5149 mi_c: usize,
5150 n4: usize,
5151 dv: Option<(i32, i32)>,
5152 n: &mut Neighbours,
5153 fctx: &crate::decode::FrameCtx,
5154) {
5155 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
5156}
5157
5158/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
5159/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
5160/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
5161///
5162/// Also stamps libaom's `is_inter_block` verdict for this block into the
5163/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
5164/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
5165/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
5166/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
5167/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
5168/// every block runs; this runs after it (class leaked-band otherwise).
5169fn record_intrabc_mi_rect(
5170 mi_r: usize,
5171 mi_c: usize,
5172 n4_w: usize,
5173 n4_h: usize,
5174 dv: Option<(i32, i32)>,
5175 n: &mut Neighbours,
5176 fctx: &crate::decode::FrameCtx,
5177) {
5178 if dv.is_some() {
5179 for i in 0..n4_w {
5180 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
5181 *cell = true;
5182 }
5183 }
5184 for i in 0..n4_h {
5185 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
5186 *cell = true;
5187 }
5188 }
5189 // lane-av1txctxband: the per-CELL `is_inter_block` an INTRABC block
5190 // publishes (`blockd.h:372-374` counts it), at the granularity
5191 // `get_tx_size_context` reads it. The band above is one slot per
5192 // column and so survives every later block in that column.
5193 n.mark_inter_grid_rect((mi_r, mi_c), n4_w, n4_h, true);
5194 }
5195 fctx.intrabc_mi_grid.with(|g| {
5196 let mut g = g.borrow_mut();
5197 let Some((grid, _, _)) = g.as_mut() else {
5198 return;
5199 };
5200 let info = crate::mvstack::MiInfo {
5201 is_inter: dv.is_some(),
5202 ref_frame: 0,
5203 ref_frame1: NO_REF1,
5204 mv: mv16(dv.unwrap_or((0, 0))),
5205 mv1: (0, 0),
5206 is_new_mv: dv.is_some(),
5207 is_global_mv0: false,
5208 is_global_mv1: false,
5209 size: n4_w as u8,
5210 size_h: n4_h as u8,
5211 };
5212 for r in mi_r..mi_r + n4_h {
5213 for c in mi_c..mi_c + n4_w {
5214 grid.set(r, c, info);
5215 }
5216 }
5217 });
5218}
5219
5220// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
5221// proves a real `skip_mode_present` stream actually reached a block that
5222// picked it, not just that the frame header bit was set.
5223thread_local! {
5224 static SKIP_MODE_HITS: std::cell::Cell<usize> =
5225 const { std::cell::Cell::new(0) };
5226}
5227
5228/// Current value of [`SKIP_MODE_HITS`].
5229#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5230pub(crate) fn skip_mode_hits() -> usize {
5231 SKIP_MODE_HITS.with(|c| c.get())
5232}
5233
5234// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
5235// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
5236// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
5237// reached [`obmc_blend`], not just the header bit.
5238thread_local! {
5239 static OBMC_HITS: std::cell::Cell<usize> =
5240 const { std::cell::Cell::new(0) };
5241}
5242
5243// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
5244// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
5245// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
5246// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
5247// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
5248// decoder used to read with the wrong alphabet, so a gate that asserts this
5249// counter advanced proves the fixed path fired (class
5250// `gate-blind-to-feature`).
5251thread_local! {
5252 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5253}
5254
5255/// Current value of [`FIMV_ALPHABET_HITS`].
5256pub fn fimv_alphabet_hits() -> usize {
5257 FIMV_ALPHABET_HITS.with(|c| c.get())
5258}
5259
5260// lane-fimv r1: how many frame headers this decoder has decoded with
5261// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
5262// prove the encoder really produced the header state under test rather than
5263// assume it.
5264thread_local! {
5265 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5266}
5267
5268/// Current value of [`FIMV_FRAME_HITS`].
5269pub fn fimv_frame_hits() -> usize {
5270 FIMV_FRAME_HITS.with(|c| c.get())
5271}
5272
5273/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
5274/// `force_integer_mv` bit is set.
5275pub fn note_force_integer_mv_frame() {
5276 hit!(FIMV_FRAME_HITS);
5277}
5278
5279/// Current value of [`OBMC_HITS`].
5280#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5281pub(crate) fn obmc_hits() -> usize {
5282 OBMC_HITS.with(|c| c.get())
5283}
5284
5285// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
5286// off the neighbour band -- the positive half of the proof for "an OBMC
5287// neighbour whose switchable interp filter was never recorded". A
5288// fixed-filter frame returns before this point (its neighbours legitimately
5289// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
5290// `interp_filter` symbols were published by `record_inter_rect_mi`.
5291thread_local! {
5292 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5293}
5294
5295/// Current value of [`OBMC_FILTER_BAND_READS`].
5296#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5297pub(crate) fn obmc_filter_band_reads() -> usize {
5298 OBMC_FILTER_BAND_READS.with(|c| c.get())
5299}
5300
5301// lane-scaledref r1: per-case firing counts for the scaled-reference gate
5302// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
5303// reference would pass just as well and prove nothing, so the gate
5304// hard-asserts each combination this round lifts actually occurred:
5305// a compound block with a scaled tap, a warp block whose warp libaom
5306// suppresses because the reference is scaled, an OBMC block, an interintra
5307// block, and an 8x8 leaf.
5308thread_local! {
5309 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5310 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5311 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5312 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5313 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5314 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5315 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5316}
5317
5318/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5319/// scaled and one unscaled tap.
5320#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5321pub(crate) fn mixed_scale_compound_hits() -> usize {
5322 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5323}
5324
5325/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5326/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5327/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5328/// `blockd.h:1484`).
5329#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5330pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5331 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5332}
5333
5334/// Current value of [`SCALED_COMPOUND_HITS`].
5335#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5336pub(crate) fn scaled_compound_hits() -> usize {
5337 SCALED_COMPOUND_HITS.with(|c| c.get())
5338}
5339
5340/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5341pub fn scaled_warp_fallback_hits() -> usize {
5342 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5343}
5344
5345/// Current value of [`SCALED_OBMC_HITS`].
5346#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5347pub(crate) fn scaled_obmc_hits() -> usize {
5348 SCALED_OBMC_HITS.with(|c| c.get())
5349}
5350
5351/// Current value of [`SCALED_INTERINTRA_HITS`].
5352#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5353pub(crate) fn scaled_interintra_hits() -> usize {
5354 SCALED_INTERINTRA_HITS.with(|c| c.get())
5355}
5356
5357/// Current value of [`SCALED_BLOCK8_HITS`].
5358#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5359pub(crate) fn scaled_block8_hits() -> usize {
5360 SCALED_BLOCK8_HITS.with(|c| c.get())
5361}
5362
5363// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5364// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5365// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5366// 8x8-leaf OBMC block apart from a 16x16+ one.
5367thread_local! {
5368 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5369}
5370
5371// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5372// pair whose two directions differ (`enable_dual_filter` only -- with dual
5373// filter off both directions take the single symbol, so this can never fire).
5374// A gate asserting it proves the stream really carries dual-filter blocks.
5375thread_local! {
5376 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5377}
5378
5379// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5380// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5381// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5382// no-filter sentinel that made a neighbouring OBMC block panic).
5383thread_local! {
5384 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5385}
5386
5387/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5388#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5389pub(crate) fn dual_filter_diff_hits() -> usize {
5390 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5391}
5392
5393/// Current value of [`COMPOUND8_FILTER_HITS`].
5394#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5395pub(crate) fn compound8_filter_hits() -> usize {
5396 COMPOUND8_FILTER_HITS.with(|c| c.get())
5397}
5398
5399// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5400// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5401// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5402// -- the gate's proof that a fixture really exercises the alphabet this
5403// round changed, even though the block itself still refuses (warp
5404// estimation/filter not ported).
5405thread_local! {
5406 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5407 const { std::cell::Cell::new(0) };
5408}
5409
5410/// Current value of [`WARP_SELECTED_HITS`].
5411#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5412pub(crate) fn warp_selected_hits() -> usize {
5413 WARP_SELECTED_HITS.with(|c| c.get())
5414}
5415
5416// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5417// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5418// into the compound intermediate) rather than translationally -- the
5419// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5420// really reached [`crate::warp::warp_affine_compound`].
5421// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5422// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5423// counter is frame-global. These two are the same arms restricted to blocks
5424// whose top mode-info row is in the frame's upper half, which is the half
5425// this lane's evidence covers.
5426thread_local! {
5427 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5428 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5429}
5430
5431/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5432/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5433///
5434/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5435/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5436/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5437/// The figure quoted for that fixture comes from a patch-run-restore build
5438/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5439/// is the same discipline every 4:2:2 lane in this family uses.
5440#[allow(dead_code)]
5441pub(crate) fn top_half_compound_hits() -> usize {
5442 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5443}
5444
5445/// How many inter blocks in the frame's upper half satisfy libaom's
5446/// `is_global_mv_block` on at least one reference slot -- mode
5447/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5448/// model > `TRANSLATION`. This is the block set whose prediction goes
5449/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5450/// as computed at the increment site; it is NOT merely "some slot has a
5451/// non-TRANSLATION model", which also counts blocks that are not global-mv
5452/// blocks.
5453///
5454/// Like [`top_half_compound_hits`], no committed test reads it: with the
5455/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5456/// these numbers describe.
5457#[allow(dead_code)]
5458pub(crate) fn top_half_warp_hits() -> usize {
5459 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5460}
5461
5462thread_local! {
5463 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5464 const { std::cell::Cell::new(0) };
5465}
5466
5467/// Current value of [`COMPOUND_WARP_HITS`].
5468#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5469pub(crate) fn compound_warp_hits() -> usize {
5470 COMPOUND_WARP_HITS.with(|c| c.get())
5471}
5472
5473// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5474// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5475// translationally until r3, so a gate needs to tell a warped 8x8 compound
5476// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5477thread_local! {
5478 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5479 const { std::cell::Cell::new(0) };
5480}
5481
5482/// Current value of [`COMPOUND_WARP_HITS_8`].
5483#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5484pub(crate) fn compound_warp_hits_8() -> usize {
5485 COMPOUND_WARP_HITS_8.with(|c| c.get())
5486}
5487
5488// lane-gmaffine r1: how many blocks built their prediction from a
5489// SIX-parameter (`AFFINE`) global-motion model through
5490// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5491// carried an AFFINE `global_motion_params` AND that a block was predicted
5492// with it, not merely that the header parsed one.
5493thread_local! {
5494 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5495 const { std::cell::Cell::new(0) };
5496}
5497
5498/// Current value of [`AFFINE_GM_HITS`].
5499#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5500pub(crate) fn affine_gm_hits() -> usize {
5501 AFFINE_GM_HITS.with(|c| c.get())
5502}
5503
5504// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5505// combine rather than the simple average -- `compound_idx == 0` under
5506// `enable_jnt_comp`, whose weights come from
5507// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5508// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5509// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5510// stream that carries `enable_jnt_comp = true` in its sequence header but
5511// codes every compound block with `compound_idx == 1` leaves this at 0 and
5512// decoded identically without the whole distance-weight path.
5513thread_local! {
5514 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5515 const { std::cell::Cell::new(0) };
5516}
5517
5518/// Current value of [`DIST_WTD_COMP_HITS`].
5519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5520pub(crate) fn dist_wtd_comp_hits() -> usize {
5521 DIST_WTD_COMP_HITS.with(|c| c.get())
5522}
5523
5524/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5525#[allow(dead_code)] // test-only
5526pub(crate) fn reset_dist_wtd_comp_hits() {
5527 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5528}
5529
5530// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5531// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5532// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5533// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5534// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5535// side build and its own counter, [`AFFINE_GM_HITS`]).
5536thread_local! {
5537 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5538 const { std::cell::Cell::new(0) };
5539}
5540
5541/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5542#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5543pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5544 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5545}
5546
5547// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5548// differently at the block's WIDTH than at libaom's
5549// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5550// pick the wrong motion_mode alphabet.
5551thread_local! {
5552 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5553}
5554
5555/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5556pub fn tr_reach_longer_side_hits() -> usize {
5557 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5558}
5559
5560// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5561// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5562// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5563// reads its interp-filter symbol. Counts the blocks where that guard flips
5564// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5565// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5566// entropy desync one symbol wide).
5567thread_local! {
5568 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5569}
5570
5571/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5572pub fn gm_nontrans_small_side_hits() -> usize {
5573 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5574}
5575
5576// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5577// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5578// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5579// only once `find_projection` returned a usable model, unlike
5580// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5581// proof that the leaf path itself fired, not the 16x16+ one.
5582thread_local! {
5583 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5584 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5585}
5586
5587/// Current value of [`GLOBALMV_HITS_8`].
5588#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5589pub(crate) fn globalmv_hits_8() -> usize {
5590 GLOBALMV_HITS_8.with(|c| c.get())
5591}
5592
5593/// Current value of [`WARP_HITS_8`].
5594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5595pub(crate) fn warp_hits_8() -> usize {
5596 WARP_HITS_8.with(|c| c.get())
5597}
5598
5599// How many blocks decoded `interintra == 1` with the non-wedge blended
5600// prediction applied (lane-interintra r1) -- the gate's proof that a
5601// stream actually exercised interintra.
5602thread_local! {
5603 static INTERINTRA_HITS: std::cell::Cell<usize> =
5604 const { std::cell::Cell::new(0) };
5605}
5606
5607/// Current value of [`INTERINTRA_HITS`].
5608#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5609pub(crate) fn interintra_hits() -> usize {
5610 INTERINTRA_HITS.with(|c| c.get())
5611}
5612
5613// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5614// -- the shape `interintra_blend` used to build a square `side x side` intra
5615// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5616// pre-existing interintra gate passed with that bug, so the rect arm needs
5617// its own counter to stop being vacuous.
5618thread_local! {
5619 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5620}
5621
5622/// Current value of [`INTERINTRA_RECT_HITS`].
5623pub fn interintra_rect_hits() -> usize {
5624 INTERINTRA_RECT_HITS.with(|c| c.get())
5625}
5626
5627// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5628// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5629// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5630// gate fixture actually exercises this alphabet, even though the block
5631// still refuses (the mask blend itself is unported).
5632thread_local! {
5633 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5634 const { std::cell::Cell::new(0) };
5635}
5636
5637/// Current value of [`MASKED_COMPOUND_HITS`].
5638#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5639pub(crate) fn masked_compound_hits() -> usize {
5640 MASKED_COMPOUND_HITS.with(|c| c.get())
5641}
5642
5643// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5644// masked-compound block whose true footprint is rectangular, i.e. the case
5645// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5646// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5647// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5648thread_local! {
5649 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5650 const { std::cell::Cell::new(0) };
5651}
5652
5653/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5654#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5655pub(crate) fn rect_masked_compound_hits() -> usize {
5656 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5657}
5658
5659// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5660// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5661// actually exercised the wedge blend, not just the DIFFWTD half of
5662// `MASKED_COMPOUND_HITS`.
5663thread_local! {
5664 static WEDGE_HITS: std::cell::Cell<usize> =
5665 const { std::cell::Cell::new(0) };
5666}
5667
5668/// Current value of [`WEDGE_HITS`].
5669#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5670pub(crate) fn wedge_hits() -> usize {
5671 WEDGE_HITS.with(|c| c.get())
5672}
5673
5674// How many blocks decoded a real wedge-INTERINTRA block
5675// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5676// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5677// smooth arm counted by `INTERINTRA_HITS`.
5678thread_local! {
5679 static WII_HITS: std::cell::Cell<usize> =
5680 const { std::cell::Cell::new(0) };
5681}
5682
5683/// Current value of [`WII_HITS`].
5684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5685pub(crate) fn wii_hits() -> usize {
5686 WII_HITS.with(|c| c.get())
5687}
5688
5689// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5690// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5691// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5692// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5693// frame carrying one.
5694thread_local! {
5695 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5696}
5697
5698/// Current value of [`NOCFL_UV_MODE_HITS`].
5699#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5700pub(crate) fn nocfl_uv_mode_hits() -> usize {
5701 NOCFL_UV_MODE_HITS.with(|c| c.get())
5702}
5703
5704/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5705/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5706pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5707 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5708
5709fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5710 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5711}
5712
5713// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5714// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5715// the rect wedge masks lifted this round actually fired, not just the square
5716// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5717thread_local! {
5718 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5719 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5720}
5721
5722/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5723pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5724 RECT_WEDGE_HITS.with(|c| c.get())
5725}
5726
5727/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5728pub(crate) fn rect_wii_hits() -> [usize; 6] {
5729 RECT_WII_HITS.with(|c| c.get())
5730}
5731
5732// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5733// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5734// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5735// aomdec, neighbour list included).
5736thread_local! {
5737 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5738}
5739
5740/// Current value of [`OBMC_RECT_LEAF_HITS`].
5741pub(crate) fn obmc_rect_leaf_hits() -> usize {
5742 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5743}
5744
5745// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5746// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5747// to be read from the pair's FIRST mi, which is a different block and, when
5748// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5749// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5750thread_local! {
5751 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5752}
5753
5754/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5755pub(crate) fn obmc_pair_filter_hits() -> usize {
5756 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5757}
5758
5759// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5760// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5761// own side, so a block overhanging the bottom/right still predicts the full
5762// neighbour strip (the destination write is what clips). We used to shrink the
5763// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5764// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5765thread_local! {
5766 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5767}
5768
5769/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5770#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5771pub(crate) fn obmc_edge_span_hits() -> usize {
5772 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5773}
5774
5775/// Current value of [`OBMC_HITS_8`].
5776#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5777pub(crate) fn obmc_hits_8() -> usize {
5778 OBMC_HITS_8.with(|c| c.get())
5779}
5780
5781// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5782// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5783// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5784// `VERT_B` all still fall into the generic "a partition type this encoder
5785// never writes" refusal below) -- the gate's proof that a free-partition
5786// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5787// coincidentally never selecting one.
5788thread_local! {
5789 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5790 const { std::cell::Cell::new(0) };
5791}
5792
5793/// Current value of [`EXTENDED_PARTITION_HITS`].
5794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5795pub(crate) fn extended_partition_hits() -> usize {
5796 EXTENDED_PARTITION_HITS.with(|c| c.get())
5797}
5798
5799// lane-partitions r1: how many 32x32 quadrants decoded a real
5800// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5801// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5802// gate's proof this round's arms actually fired.
5803thread_local! {
5804 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5805 const { std::cell::Cell::new(0) };
5806}
5807
5808/// Current value of [`RECT_PARTITION_HITS`].
5809#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5810pub(crate) fn rect_partition_hits() -> usize {
5811 RECT_PARTITION_HITS.with(|c| c.get())
5812}
5813
5814// lane-inter8 r1: how many superblocks an inter tile coded as a single
5815// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5816// static content, previously a named refusal).
5817thread_local! {
5818 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5819 /// path decoded as one whole block (its gate's own witness).
5820 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5821 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5822 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5823 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5824}
5825
5826/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5827pub(crate) fn inter_sb128_horz_hits() -> usize {
5828 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5829}
5830
5831/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5832pub(crate) fn inter_sb128_vert_hits() -> usize {
5833 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5834}
5835
5836/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5837pub fn inter_sb128_none_hits() -> usize {
5838 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5839}
5840
5841thread_local! {
5842 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5843 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5844 /// units) -- the gate's witness that the lifted refusal's case fired.
5845 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5846}
5847
5848/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5849pub fn intra_128_in_inter_hits() -> usize {
5850 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5851}
5852
5853thread_local! {
5854 /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the
5855 /// intra-in-inter 128x128 root read (`decode_inter_block`'s
5856 /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every
5857 /// unit is one `read_plane` on U and one on V, so the counter is the
5858 /// gate's proof the arm ran at all -- no committed 4:4:4 fixture
5859 /// reached it before this lane.
5860 pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell<usize> =
5861 const { std::cell::Cell::new(0) };
5862}
5863
5864/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's
5865/// before/after delta.
5866pub fn intra_128_in_inter_mu_chroma_hits() -> usize {
5867 INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get)
5868}
5869
5870thread_local! {
5871 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5872 const { std::cell::Cell::new(0) };
5873}
5874
5875/// Current value of [`INTER_SB_NONE_HITS`].
5876#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5877pub(crate) fn inter_sb_none_hits() -> usize {
5878 INTER_SB_NONE_HITS.with(|c| c.get())
5879}
5880
5881// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5882// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5883// path has always run that loop, so only this counter proves the newly-lifted
5884// alphabet value fired.
5885thread_local! {
5886 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5887 const { std::cell::Cell::new(0) };
5888}
5889
5890/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5891#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5892pub(crate) fn inter_sub16_split_hits() -> usize {
5893 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5894}
5895
5896// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5897// while at least one reference picture was SCALED (superres) -- the counter
5898// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5899thread_local! {
5900 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5901 const { std::cell::Cell::new(0) };
5902}
5903
5904/// Current value of [`SCALED_LEAF8_HITS`].
5905pub fn scaled_leaf8_hits() -> usize {
5906 SCALED_LEAF8_HITS.with(|c| c.get())
5907}
5908
5909// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5910// rect pair) were predicted from a SCALED reference -- the counter behind the
5911// lifted "sub-8x8 inter block under a scaled reference" refusal.
5912thread_local! {
5913 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5914 const { std::cell::Cell::new(0) };
5915}
5916
5917/// Current value of [`SCALED_SUB8_HITS`].
5918pub fn scaled_sub8_hits() -> usize {
5919 SCALED_SUB8_HITS.with(|c| c.get())
5920}
5921
5922// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5923// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5924// rect coefficient reader itself fired, not just the strip-level partition
5925// symbol [`RECT_PARTITION_HITS`] already counts.
5926thread_local! {
5927 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5928 const { std::cell::Cell::new(0) };
5929}
5930
5931/// Current value of [`RECT_COEFF_HITS`].
5932#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5933pub(crate) fn rect_coeff_hits() -> usize {
5934 RECT_COEFF_HITS.with(|c| c.get())
5935}
5936
5937// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5938// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5939// charter's real-aomenc gate hard-asserts.
5940thread_local! {
5941 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5942 const { std::cell::Cell::new(0) };
5943}
5944
5945/// Current value of [`RECT_LEAF_COEFF_HITS`].
5946#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5947pub(crate) fn rect_leaf_coeff_hits() -> usize {
5948 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5949}
5950
5951// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5952// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5953// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5954// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5955// needs rectangular intra prediction" before this round.
5956thread_local! {
5957 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5958 const { std::cell::Cell::new([0; 3]) };
5959}
5960
5961/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5962/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5963#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5964pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5965 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5966}
5967
5968// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5969// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5970// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5971// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5972// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5973// a single counter cannot tell an axis swap from a working arm
5974// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5975thread_local! {
5976 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5977 const { std::cell::Cell::new([0; 2]) };
5978}
5979
5980/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5981/// (0 = 64x32, 1 = 32x64).
5982pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5983 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5984}
5985
5986// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5987// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5988// is never incremented) -- the gate's proof that the lifted path ran per depth.
5989thread_local! {
5990 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5991 const { std::cell::Cell::new([0; 3]) };
5992}
5993
5994// lane-t900 r21: rect intra strips inside an inter frame that read the
5995// screen-content palette syntax (`allow_screen_content_tools` set and the
5996// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5997// refusal used to guard, so this counter is what keeps its witness gate
5998// non-vacuous.
5999thread_local! {
6000 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6001}
6002
6003/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
6004#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6005pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
6006 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
6007}
6008
6009/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
6010#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6011pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
6012 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
6013}
6014
6015/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
6016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6017pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
6018 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
6019}
6020
6021// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
6022// approximation would have resolved off a DIFFERENT CDF row than the real
6023// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
6024// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
6025// tally is green on the old code too (class gate-blind-to-feature).
6026thread_local! {
6027 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
6028 const { std::cell::Cell::new(0) };
6029}
6030
6031/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
6032#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
6033pub(crate) fn txctx_deblock_divergence_hits() -> usize {
6034 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
6035}
6036// lane-av1txctxband: how many `get_tx_size_context` reads the per-CELL
6037// `is_inter_block` cover and the per-COLUMN `above_inter`/`left_inter` bands
6038// DISAGREE about -- i.e. exactly the reads whose CDF row the old code chose
6039// wrongly. Green on the old code too (a plain "some block was inter" tally
6040// would be), so this is the non-vacuity arm of the witness gate: it is 0 on
6041// every stream where the bands happened to be right and non-zero on the
6042// 4:4:4 lossy `--sb-size=128` cq-62 stream whose entropy forked at read 32813
6043// on the 8x4 intra leaf at mi(57,52).
6044thread_local! {
6045 static TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS: std::cell::Cell<usize> =
6046 const { std::cell::Cell::new(0) };
6047}
6048
6049/// Current value of [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`].
6050#[allow(dead_code)] // read only from the `#[cfg(test)]` gate
6051pub(crate) fn txctx_inter_cell_band_divergence_hits() -> usize {
6052 TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(std::cell::Cell::get)
6053}
6054
6055/// Zeroes [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`].
6056#[allow(dead_code)] // read only from the `#[cfg(test)]` gate
6057pub(crate) fn reset_txctx_inter_cell_band_divergence_hits() {
6058 TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(|c| c.set(0));
6059}
6060
6061// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
6062// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
6063// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
6064// rect strip on the inter block path" before this round.
6065thread_local! {
6066 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
6067 const { std::cell::Cell::new([0; 4]) };
6068}
6069
6070/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
6071/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
6072pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
6073 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
6074}
6075
6076// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
6077// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
6078// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
6079// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
6080// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
6081// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
6082// REACH only, never that the fix bites -- that is the gate's byte compare and
6083// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
6084thread_local! {
6085 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6086}
6087
6088/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
6089#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6090pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
6091 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
6092}
6093
6094/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
6095#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6096pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
6097 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
6098}
6099
6100// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
6101// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
6102// stream of the same recipe leaves it at 0, which is what makes it the
6103// 4:4:4-only route.
6104//
6105// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
6106// never was. A route counter fires identically before and after a change that
6107// changes nothing downstream, so a non-zero count proves REACH and nothing
6108// more. On this lane it is also armed deliberately OUTSIDE the `own444`
6109// expression, so that the mutation (`own444 = false`) still increments it and
6110// the red comes from the pixel/entropy arm instead. The evidence that the ss
6111// gate bites is the measured fork move -- first entropy fork read 11750 ->
6112// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
6113// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
6114// a DIFFERS-style assertion to carry a claim.
6115thread_local! {
6116 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6117}
6118
6119// lane-av1422luma: the ss (1,0) twin of `INTRABC_RECT4_OWN_CHROMA444_HITS`
6120// -- how many intra-BC 1:4 strips at 4:2:2 took the own-chroma (no pair)
6121// route. Same caveat as the 4:4:4 counter: it proves REACH and nothing else,
6122// and 4:2:2 is refused at the sequence header, so no committed test can read
6123// it (the count in `lanes/av1422luma.report.md` is from a bypassed probe build).
6124thread_local! {
6125 static INTRABC_RECT4_OWN_CHROMA422_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6126}
6127
6128/// Current value of [`INTRABC_RECT4_OWN_CHROMA422_HITS`].
6129#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6130pub(crate) fn intrabc_rect4_own_chroma422_hits() -> usize {
6131 INTRABC_RECT4_OWN_CHROMA422_HITS.with(std::cell::Cell::get)
6132}
6133
6134/// Resets [`INTRABC_RECT4_OWN_CHROMA422_HITS`] before a decode.
6135#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6136pub(crate) fn reset_intrabc_rect4_own_chroma422_hits() {
6137 INTRABC_RECT4_OWN_CHROMA422_HITS.with(|c| c.set(0));
6138}
6139
6140/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
6141#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6142pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
6143 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
6144}
6145
6146/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
6147#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6148pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
6149 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
6150}
6151
6152// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
6153// through one of the key-frame rect readers ([`decode_block_rect4`],
6154// [`decode_block_rect64`]). `Some((size_group, skip))` tells
6155// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
6156// already read by [`decode_inter_block`] and (b) the luma mode comes off
6157// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
6158// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
6159
6160// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
6161// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
6162// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
6163// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
6164thread_local! {
6165 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
6166 const { std::cell::Cell::new(0) };
6167}
6168
6169/// Current value of [`MODE_MI_OVERRIDE_HITS`].
6170#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6171pub(crate) fn mode_mi_override_hits() -> usize {
6172 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
6173}
6174
6175// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
6176// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
6177// mode from the previous tile, where libaom's `up_available`/`left_available`
6178// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
6179// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
6180// per superblock row in `start_row`, so the luma fallback cannot leak the way
6181// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
6182// the invariant that makes the coarse fallback safe.
6183thread_local! {
6184 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
6185 const { std::cell::Cell::new(0) };
6186}
6187
6188/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
6189#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6190pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
6191 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
6192}
6193
6194// lane-cfl r1: how many times a chroma intra-edge filter-type read
6195// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
6196// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
6197// r1 defect would have filtered a chroma edge with the wrong strength.
6198thread_local! {
6199 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
6200 const { std::cell::Cell::new(0) };
6201}
6202
6203/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
6204#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6205pub(crate) fn uv_mode_mi_override_hits() -> usize {
6206 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
6207}
6208
6209// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
6210// `uv_mode` from the mi GRID where the one-slot-per-column map would have
6211// answered differently -- the sub-8x8 pair case where the pair's own first
6212// half had already overwritten the column slot the chroma-ref half reads.
6213thread_local! {
6214 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
6215 const { std::cell::Cell::new(0) };
6216}
6217
6218/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
6219pub fn uv_mode_grid_override_hits() -> usize {
6220 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
6221}
6222
6223// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
6224// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
6225// from an earlier block in that pixel row/column while the mi-exact map --
6226// which an inter block only started writing this round -- correctly says the
6227// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
6228// an INTER mode, and its `uv_mode` "is not set for inter blocks").
6229thread_local! {
6230 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
6231 const { std::cell::Cell::new(0) };
6232}
6233
6234/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
6235#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6236pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
6237 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
6238}
6239
6240// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
6241// suppressed at a TILE edge that is not a frame edge -- the above/left
6242// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
6243// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
6244// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
6245// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
6246// above would decide this tile's chroma edge filter strength.
6247thread_local! {
6248 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
6249 const { std::cell::Cell::new(0) };
6250}
6251
6252/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
6253#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6254pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
6255 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
6256}
6257
6258// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
6259// left neighbour whose `uv_mode` at libaom's real read cell
6260// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
6261// cell this decoder used to read (its own mi row). Two buckets: the raw mode
6262// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
6263// flipped. The second is the one that can move pixels.
6264thread_local! {
6265 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
6266 const { std::cell::Cell::new(0) };
6267 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
6268 const { std::cell::Cell::new(0) };
6269}
6270thread_local! {
6271 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6272}
6273
6274/// Current value of [`UV_LEFT_SS_Y_READS`].
6275pub fn uv_left_ss_y_reads() -> usize {
6276 UV_LEFT_SS_Y_READS.with(|c| c.get())
6277}
6278
6279/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
6280pub fn uv_left_ss_y_mode_diff_hits() -> usize {
6281 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
6282}
6283
6284/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
6285pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
6286 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
6287}
6288
6289// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
6290// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
6291// decoder reads (its own mi row) and the cell libaom reads (one row down)
6292// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
6293// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
6294// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
6295thread_local! {
6296 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6297}
6298
6299/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
6300pub fn uv_left_1mi_split_hits() -> usize {
6301 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
6302}
6303
6304// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
6305// Bumped in `Neighbours::start_tile`; never read by decode logic.
6306thread_local! {
6307 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
6308}
6309
6310// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
6311// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
6312// shapes the r1 chroma defect showed up on.
6313thread_local! {
6314 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6315 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6316}
6317// lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4
6318// arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample)
6319// and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two
6320// reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability
6321// evidence for that function's format-blind extent.
6322thread_local! {
6323 static CFL_AC_444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6324 static CFL_AC_422_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6325 static CFL_AC_420_SQ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6326 static CFL_AC_420_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6327 static CFL_AC_Q3_AT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6328}
6329
6330/// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits.
6331pub fn cfl_ac_arm_hits() -> [usize; 4] {
6332 [
6333 CFL_AC_444_HITS.with(|c| c.get()),
6334 CFL_AC_422_HITS.with(|c| c.get()),
6335 CFL_AC_420_SQ_HITS.with(|c| c.get()),
6336 CFL_AC_420_RECT_HITS.with(|c| c.get()),
6337 ]
6338}
6339
6340/// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is
6341/// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate
6342/// proves it is reached ONLY at 4:2:0.
6343pub fn cfl_ac_q3_at_hits() -> usize {
6344 CFL_AC_Q3_AT_HITS.with(|c| c.get())
6345}
6346
6347/// Current value of [`CFL_BLOCK_HITS`].
6348#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6349pub(crate) fn cfl_block_hits() -> usize {
6350 CFL_BLOCK_HITS.with(|c| c.get())
6351}
6352
6353/// Current value of [`UV_ANGLE_DELTA_HITS`].
6354#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6355pub(crate) fn uv_angle_delta_hits() -> usize {
6356 UV_ANGLE_DELTA_HITS.with(|c| c.get())
6357}
6358
6359// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
6360// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
6361// gate's proof this round's arms actually reached a real block, not just
6362// that `partition_w64` read one of those two symbol values.
6363thread_local! {
6364 static SB_RECT_HITS: std::cell::Cell<usize> =
6365 const { std::cell::Cell::new(0) };
6366}
6367
6368// Current value of [`SB_RECT_HITS`].
6369// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
6370// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
6371// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
6372// non-SPLIT edge arm actually decoded (before this round the bit was read and
6373// thrown away, so that arm was unreachable).
6374thread_local! {
6375 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6376}
6377
6378/// Current value of [`EDGE_PART_HITS`].
6379#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6380pub(crate) fn edge_part_hits() -> [usize; 4] {
6381 EDGE_PART_HITS.with(|c| c.get())
6382}
6383
6384/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
6385#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6386pub(crate) fn reset_edge_part_hits() {
6387 EDGE_PART_HITS.with(|c| c.set([0; 4]));
6388}
6389
6390fn bump_edge_part(slot: usize) {
6391 hit_do! {
6392 EDGE_PART_HITS.with(|c| {
6393 let mut h = c.get();
6394 h[slot] += 1;
6395 c.set(h);
6396 });
6397 }
6398}
6399
6400#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6401pub(crate) fn sb_rect_hits() -> usize {
6402 SB_RECT_HITS.with(|c| c.get())
6403}
6404
6405// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
6406// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
6407// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
6408// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6409// paths (intra and inter) feed the same counter.
6410//
6411// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6412// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6413// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6414// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6415// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6416// every SB of the last row), so the 32-level slots stay 0 on that content and
6417// only these prove the arm fired.
6418thread_local! {
6419 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6420 const { std::cell::Cell::new([0; 8]) };
6421}
6422
6423/// Current value of [`EDGE32_HITS`].
6424#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6425pub(crate) fn edge32_hits() -> [usize; 8] {
6426 EDGE32_HITS.with(|c| c.get())
6427}
6428
6429/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6430/// reads are `if`-conditions, so the counter has to ride the expression.
6431fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6432 bump_edge32(base + bit.min(1));
6433 bit
6434}
6435
6436fn bump_edge32(slot: usize) {
6437 hit_do! {
6438 EDGE32_HITS.with(|c| {
6439 let mut h = c.get();
6440 h[slot] += 1;
6441 c.set(h)
6442 });
6443 }
6444}
6445
6446// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6447// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6448// strip) fired. Real aomenc picks these at 64 even with
6449// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6450// the counter the gate hard-asserts.
6451thread_local! {
6452 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6453 const { std::cell::Cell::new([0; 4]) };
6454}
6455
6456/// Current value of [`SB_AB_HITS`], summed over the four arms.
6457#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6458pub(crate) fn sb_ab_hits() -> usize {
6459 SB_AB_HITS.with(|c| c.get().iter().sum())
6460}
6461
6462/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6463/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6464/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6465/// proof of all four.
6466#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6467pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6468 SB_AB_HITS.with(std::cell::Cell::get)
6469}
6470
6471// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6472// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6473// strips). Two counters, not one, because a gate that only proved "some 1:4
6474// strip fired" would pass on a stream that never coded the other axis, and
6475// every scan/context table this round added comes in a transposed pair.
6476thread_local! {
6477 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6478 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6479}
6480
6481/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6482#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6483pub(crate) fn sb_rect4_horz_hits() -> usize {
6484 SB_RECT4_HORZ_HITS.with(|c| c.get())
6485}
6486
6487/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6488#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6489pub(crate) fn sb_rect4_vert_hits() -> usize {
6490 SB_RECT4_VERT_HITS.with(|c| c.get())
6491}
6492
6493// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6494// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6495// strips), the arms the ReelB mid-film extract stops at.
6496thread_local! {
6497 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6498 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6499 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6500 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6501 /// `PARTITION_VERT_4`.
6502 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6503 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6504 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6505 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6506 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6507 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6508 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6509 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6510}
6511
6512// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6513// a gate that only counted strips would pass on an all-skip stream, which
6514// exercises none of the new scan/context tables.
6515thread_local! {
6516 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6517}
6518
6519// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6520// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6521// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6522// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6523// counts the same for a 16x8/8x16 strip below 16x16.
6524thread_local! {
6525 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6526 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6527 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6528}
6529
6530/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6531#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6532pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6533 (
6534 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6535 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6536 )
6537}
6538
6539/// Current value of `SUB16_SPLIT_HITS`.
6540#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6541pub(crate) fn sub16_split_hits() -> usize {
6542 SUB16_SPLIT_HITS.with(|c| c.get())
6543}
6544
6545// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6546// luma transform is SPLIT and which therefore leave through that fn's early
6547// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6548thread_local! {
6549 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6550}
6551
6552/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6553#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6554pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6555 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6556}
6557
6558/// Current value of `RECT4_COEFF_HITS`.
6559pub(crate) fn rect4_coeff_hits() -> usize {
6560 RECT4_COEFF_HITS.with(|c| c.get())
6561}
6562
6563// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6564// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6565// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6566// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6567// asserts the arms it proves separately so a run whose RD only picked one
6568// cannot pass as proof of the others.
6569thread_local! {
6570 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6571}
6572
6573/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6574/// inter frame).
6575pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6576 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6577}
6578
6579// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6580// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6581// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6582// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6583// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6584// arm separately so a run whose RD only picked one cannot pass as proof of
6585// four.
6586thread_local! {
6587 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6588}
6589
6590/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6591/// inter frame).
6592pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6593 AB16_INTER_HITS.with(std::cell::Cell::get)
6594}
6595
6596// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6597// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6598// counts the odd strips that close a 4:2:0 chroma pair
6599// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6600// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6601// the PREVIOUS strip's own mv/ref/filters -- libaom
6602// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6603// through `is_sub8x8_inter` (same file, :54).
6604thread_local! {
6605 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6606 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6607 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6608 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6609}
6610
6611// lane-arfchroma: chroma transform-unit publications whose block started
6612// MID-CELL -- the condition `record_mi_chroma`'s origin alignment exists for.
6613// A 4x4 chroma unit is `1 << ss` luma mi per axis, so a block whose mi origin
6614// is not step-aligned (a 16x4 / 4x16 1:4 strip at 4:2:0 has an ODD mi row or
6615// column) publishes a context cell whose origin is the step-aligned mi BELOW
6616// or RIGHT of its own. Counted per publication, `[row_misaligned,
6617// col_misaligned, both]`, so a gate can prove the witness really walks the
6618// realigned path instead of passing on a stream whose chroma units all happen
6619// to start on a cell boundary.
6620thread_local! {
6621 static CHROMA_MIDCELL_PUB_HITS: std::cell::Cell<[usize; 3]> =
6622 const { std::cell::Cell::new([0; 3]) };
6623}
6624
6625/// ChROMA publications that started mid-cell: `[row, col, both]`. See
6626/// [`CHROMA_MIDCELL_PUB_HITS`].
6627#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6628pub fn chroma_midcell_pub_hits() -> [usize; 3] {
6629 CHROMA_MIDCELL_PUB_HITS.with(std::cell::Cell::get)
6630}
6631
6632/// Zeroes [`CHROMA_MIDCELL_PUB_HITS`] so a gate can measure its own decode.
6633#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6634pub fn reset_chroma_midcell_pub_hits() {
6635 CHROMA_MIDCELL_PUB_HITS.with(|c| c.set([0; 3]));
6636}
6637
6638// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6639// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6640// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6641thread_local! {
6642 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6643 const { std::cell::Cell::new([0; 3]) };
6644}
6645
6646/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6647/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6648pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6649 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6650 (v[0], v[1], v[2])
6651}
6652
6653/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6654/// strips, chroma pairs closed, chroma pairs built from two different
6655/// strips' motion vectors)`.
6656pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6657 (
6658 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6659 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6660 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6661 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6662 )
6663}
6664
6665/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6666/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6667/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6668/// that all mean "an ordinary block, chroma of its own".
6669#[derive(Clone, Copy)]
6670pub(crate) struct InterStripChroma {
6671 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6672 /// read and reconstruct NO chroma at all.
6673 has_chroma: bool,
6674 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6675 horz: bool,
6676 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6677 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6678 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6679 pair_mi: (usize, usize),
6680 /// The previous (even) strip's single-reference MC parameters, `None`
6681 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6682 /// and the whole chroma block is predicted from THIS strip's mv.
6683 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6684}
6685
6686/// The single-reference MC parameters of the inter block that decoded
6687/// last -- read by the next 1:4 strip to build its pair's chroma.
6688
6689fn bump_ab16_inter(arm: usize) {
6690 hit_do! {
6691 AB16_INTER_HITS.with(|c| {
6692 let mut v = c.get();
6693 v[arm] += 1;
6694 c.set(v);
6695 });
6696 }
6697}
6698
6699// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6700// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6701// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6702thread_local! {
6703 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6704 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6705 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6706 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6707 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6708 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6709 /// base mi differs from what the strip's own (odd) mi would have said --
6710 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6711 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6712 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6713 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6714 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6715 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6716 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6717 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6718 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6719 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6720 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6721 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6722 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6723 /// block overhanging the frame does NOT code.
6724 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6725 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6726 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6727 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6728 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6729 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6730 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6731 /// hardcoded 4:2:0 span mis-stepped).
6732 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6733 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6734 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6735 /// that replaced the single rect unit).
6736 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6737 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6738 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6739 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6740 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6741 /// units whose libaom-faithful block-relative reach
6742 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6743 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6744 /// no stream reached a rect leaf where the two disagree -- a gate
6745 /// asserting the reach fix must see this nonzero, or the fixture never
6746 /// exercised the fixed path.
6747 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6748 /// lane-av1offtile: 4x4 chroma units a lossless HORZ/VERT strip's plane-
6749 /// major walk skipped because their top-left sample falls outside the
6750 /// CHROMA plane. libaom bounds that walk per plane (`max_block_wide/high`,
6751 /// av1_common_int.h:1565); this walk used to count the block's own
6752 /// `chroma_w / 4` x `chroma_h / 4`. Zero means no stream decoded a
6753 /// lossless strip overhanging the frame edge -- a gate asserting the
6754 /// clip must see this nonzero.
6755 static RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS: std::cell::Cell<usize> =
6756 const { std::cell::Cell::new(0) };
6757}
6758
6759/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6760/// that reconstructed as flat DC before lane-kf1200 r2).
6761pub fn skip_cfl_hits() -> usize {
6762 SKIP_CFL_HITS.with(|c| c.get())
6763}
6764
6765/// How many chroma transform units the frame-edge clip skipped in
6766/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6767/// stream whose lossless blocks never overhang the frame -- a gate asserting
6768/// the clip fired must see this nonzero.
6769pub fn chroma_edge_tu_clip_hits() -> usize {
6770 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6771}
6772
6773/// How many skipped lossless intrabc rect strips had their luma entropy
6774/// bands zeroed per unit (lane-av1-loss64).
6775pub fn skip_lossless_band_reset_hits() -> usize {
6776 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6777}
6778
6779/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6780/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6781/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6782/// must see this nonzero.
6783pub fn rect_split_lossless_chroma444_hits() -> usize {
6784 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6785}
6786
6787/// How many 4x4 chroma units a lossless HORZ/VERT strip's plane-major walk
6788/// skipped for falling outside the chroma plane (lane-av1offtile). Zero means
6789/// no stream decoded a lossless strip overhanging the frame edge -- a gate
6790/// asserting the clip must see this nonzero.
6791pub fn rect_split_lossless_chroma_offtile_hits() -> usize {
6792 RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.get())
6793}
6794
6795/// Reset [`rect_split_lossless_chroma_offtile_hits`] to zero (lane-av1offtile).
6796pub fn reset_rect_split_lossless_chroma_offtile_hits() {
6797 RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.set(0));
6798}
6799
6800/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6801/// per-4x4 inter units (lane-av1-ibc444rect).
6802pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6803 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6804}
6805
6806/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6807/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6808pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6809 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6810}
6811
6812/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6813/// block-relative reach libaom's `has_bottom_left` gives, where the
6814/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6815/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6816pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6817 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6818}
6819
6820/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6821pub fn reset_sub8_chroma444_tu_reach_hits() {
6822 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6823}
6824
6825/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6826pub fn reset_ibc444rect_hits() {
6827 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6828 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6829}
6830
6831/// Gate-side reset for the two lane-av1-loss64 counters above.
6832pub fn reset_loss64_hits() {
6833 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6834 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6835}
6836
6837/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6838/// from the pair's base mi than the strip's own mi would have given.
6839pub fn rect4_16_uv_pair_filt_hits() -> usize {
6840 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6841}
6842
6843/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6844pub fn rect4_16_lossless_chroma_hits() -> usize {
6845 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6846}
6847
6848/// How many 16x4/4x16 strips reconstructed as intra block copy.
6849pub fn rect4_16_intrabc_hits() -> usize {
6850 RECT4_16_INTRABC_HITS.with(|c| c.get())
6851}
6852
6853/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6854pub fn reset_rect4_16_pair_hits() {
6855 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6856 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6857}
6858
6859// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6860// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6861// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6862// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6863// intra-edge filter type must come from the chroma-reference position).
6864thread_local! {
6865 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6866 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6867}
6868
6869/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6870pub fn reelc_chroma_counters() -> (usize, usize) {
6871 (
6872 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6873 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6874 )
6875}
6876
6877/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6878/// strips, chroma-reference strips, strips with a coded residual, strips
6879/// whose luma transform is split)`.
6880pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6881 (
6882 RECT4_16_HORZ_HITS.with(|c| c.get()),
6883 RECT4_16_VERT_HITS.with(|c| c.get()),
6884 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6885 RECT4_16_COEFF_HITS.with(|c| c.get()),
6886 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6887 )
6888}
6889
6890/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6891pub(crate) fn rect4_32_horz_hits() -> usize {
6892 RECT4_32_HORZ_HITS.with(|c| c.get())
6893}
6894
6895/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6896pub(crate) fn rect4_32_vert_hits() -> usize {
6897 RECT4_32_VERT_HITS.with(|c| c.get())
6898}
6899
6900/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6901pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6902 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6903}
6904
6905/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6906pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6907 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6908}
6909
6910/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6911pub(crate) fn inter_sb_horz_hits() -> usize {
6912 INTER_SB_HORZ_HITS.with(|c| c.get())
6913}
6914
6915/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6916pub(crate) fn inter_sb_vert_hits() -> usize {
6917 INTER_SB_VERT_HITS.with(|c| c.get())
6918}
6919
6920/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6921pub(crate) fn inter_sb_horz4_hits() -> usize {
6922 INTER_SB_HORZ4_HITS.with(|c| c.get())
6923}
6924
6925/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6926pub(crate) fn inter_sb_vert4_hits() -> usize {
6927 INTER_SB_VERT4_HITS.with(|c| c.get())
6928}
6929
6930// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6931// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6932// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6933// just inert-compiled. Zero forever on a passing gate means that gate's
6934// stream never carries `delta_q_present=1` through a rect64 block.
6935thread_local! {
6936 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6937 const { std::cell::Cell::new(0) };
6938}
6939
6940/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6941#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6942pub(crate) fn rect64_qidx_drift_hits() -> usize {
6943 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6944}
6945
6946// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6947// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6948// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6949// free-partition gate's proof this round's arms actually fired.
6950thread_local! {
6951 static PARTAB_HITS: std::cell::Cell<usize> =
6952 const { std::cell::Cell::new(0) };
6953}
6954
6955/// Current value of [`PARTAB_HITS`].
6956#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6957pub(crate) fn partab_hits() -> usize {
6958 PARTAB_HITS.with(|c| c.get())
6959}
6960
6961// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6962// one counter per arm rather than one shared total -- the gate hard-asserts
6963// each of these individually nonzero so a recipe that only ever fires
6964// HORZ_A can't silently stand in for the whole set.
6965thread_local! {
6966 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6967 const { std::cell::Cell::new(0) };
6968 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6969 const { std::cell::Cell::new(0) };
6970 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6971 const { std::cell::Cell::new(0) };
6972 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6973 const { std::cell::Cell::new(0) };
6974}
6975
6976/// Current value of [`INTRA_HORZ_A_HITS`].
6977#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6978pub(crate) fn intra_horz_a_hits() -> usize {
6979 INTRA_HORZ_A_HITS.with(|c| c.get())
6980}
6981/// Current value of [`INTRA_HORZ_B_HITS`].
6982#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6983pub(crate) fn intra_horz_b_hits() -> usize {
6984 INTRA_HORZ_B_HITS.with(|c| c.get())
6985}
6986/// Current value of [`INTRA_VERT_A_HITS`].
6987#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6988pub(crate) fn intra_vert_a_hits() -> usize {
6989 INTRA_VERT_A_HITS.with(|c| c.get())
6990}
6991/// Current value of [`INTRA_VERT_B_HITS`].
6992#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6993pub(crate) fn intra_vert_b_hits() -> usize {
6994 INTRA_VERT_B_HITS.with(|c| c.get())
6995}
6996
6997// How many [`read_inter_compound_mode`] reads actually happened
6998// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6999// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
7000// mvstack build), not just that `comp_mode` fired. Still refused right
7001// after (no MV assignment or MC wired), so this only counts attempted
7002// reads.
7003thread_local! {
7004 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
7005 const { std::cell::Cell::new(0) };
7006}
7007
7008/// Current value of [`COMPOUND_MODE_HITS`].
7009#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
7010pub(crate) fn compound_mode_hits() -> usize {
7011 COMPOUND_MODE_HITS.with(|c| c.get())
7012}
7013
7014/// How many query blocks folded in at least one temporal MV candidate
7015/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
7016/// temporal-MV gate's own firing counter (lane-av1tmvp).
7017///
7018/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
7019/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
7020/// this file (`decode_inter_block`) still passes `tpl: None` -- this
7021/// counter compiles and the projection math it counts is unit-tested
7022/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
7023/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
7024/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
7025/// against any real stream today. See the module doc on
7026/// `crate::motion_field` and this crate's ledger for the remaining wiring.
7027#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7028pub(crate) fn tmv_hits() -> usize {
7029 crate::mvstack::tmv_hits()
7030}
7031
7032/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
7033/// produced on this thread, the 10-bit inter gate's firing proof.
7034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7035pub(crate) fn inter_pred_hits() -> usize {
7036 crate::mc::inter_pred_hits()
7037}
7038
7039/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
7040/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
7041/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
7042/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
7043/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
7044/// needs to turn a query block's own resolved `ref_frame` into
7045/// `TplArgs::cur_offset_0` (spec 7.9.3).
7046pub(crate) struct TplFrameArgs<'a> {
7047 pub field: &'a crate::motion_field::TplField,
7048 pub order_hint_bits: u32,
7049 pub order_hint: u32,
7050 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
7051 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
7052 /// frame's own `ref_frame_idx` names for each single reference.
7053 pub ref_order_hints: [u32; 7],
7054}
7055
7056/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
7057/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
7058/// decoded `grid`: every 4x4 unit an inter block covers reads the same
7059/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
7060/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
7061/// exact — every block this crate ever codes is at least 8x8, so no 8x8
7062/// cell straddles two different blocks' values.
7063#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
7064pub(crate) fn build_motion_field(
7065 grid: &MiGrid,
7066 mi_cols: usize,
7067 mi_rows: usize,
7068 order_hint: u32,
7069 order_hint_bits: u32,
7070 ref_order_hints: [u32; 7],
7071 fctx: &FrameCtx,
7072) -> crate::motion_field::MotionField {
7073 let mut field =
7074 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
7075 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
7076 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
7077 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
7078 // referencing one stores only its OTHER side's mv. With
7079 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
7080 // nothing is skipped.
7081 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
7082 // only on the reference frame, so it is 7 table lookups per frame instead
7083 // of two per inter unit.
7084 let other_side: [bool; 8] = std::array::from_fn(|rf| {
7085 let i = rf.wrapping_sub(LAST_FRAME as usize);
7086 order_hint_bits != 0
7087 && i < 7
7088 && (crate::motion_field::get_relative_dist(
7089 order_hint_bits,
7090 ref_order_hints[i],
7091 order_hint,
7092 ) > 0
7093 || ref_order_hints[i] == order_hint)
7094 });
7095 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
7096 // capped at 12 bits per component; a longer one is not stored at all.
7097 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
7098 let (cols, rows, cells) = field.cells_mut();
7099 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
7100 // never touch each other (an 8x8 cell lives in one cell row, and mi row
7101 // `row` writes cell row `row / 2`).
7102 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
7103 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
7104 let out = &mut out[(row / 2 - r0) * cols..][..cols];
7105 for col in 0..mi_cols {
7106 let Some(info) = grid.get_frame(row, col) else {
7107 continue;
7108 };
7109 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
7110 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
7111 // so an intra block -- or an inter block whose every slot is on the
7112 // other side / over the limit -- wipes what an earlier block wrote
7113 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
7114 // share a cell).
7115 if !info.is_inter {
7116 out[col / 2] = None;
7117 continue;
7118 }
7119 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
7120 // qualifying one wins -- a compound block stores its second
7121 // reference's mv, never its first (unless the second is on the
7122 // other side or over the limit). Storing slot 0 unconditionally
7123 // put the wrong (mv, ref_frame_offset) pair in every compound
7124 // block's cell, which a later frame's temporal candidate then
7125 // projected with the wrong reference distance.
7126 let mut saved: Option<crate::motion_field::SavedMv> = None;
7127 for (rf, mv) in [
7128 (info.ref_frame, Some(mv32(info.mv))),
7129 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
7130 ] {
7131 let (Some(mv), true) = (mv, rf > 0) else {
7132 continue;
7133 };
7134 if other_side[rf as usize] {
7135 continue;
7136 }
7137 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
7138 continue;
7139 }
7140 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
7141 }
7142 out[col / 2] = saved;
7143 }
7144 }
7145 };
7146 // lane-mf: the whole-frame pass split over the filter pool in cell-row
7147 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
7148 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
7149 let bands = crate::par::bands(rows, crate::par::filter_threads());
7150 if bands.len() <= 1 {
7151 fill(0, rows, cells);
7152 } else {
7153 let shared = crate::par::Shared::new(cells);
7154 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
7155 // SAFETY: cell rows `r0..r1` are this band's alone.
7156 let cells = unsafe { shared.get() };
7157 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
7158 });
7159 }
7160 if crate::envflags::env_flag!("EC_TRACE_TPL") {
7161 eprintln!("EC_TPL_SAVED oh={order_hint}");
7162 for (r, row) in field.occupancy().iter().enumerate() {
7163 eprintln!("EC_TPL_SAVED r{r} {row}");
7164 }
7165 }
7166 field
7167}
7168
7169/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
7170/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
7171#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7172pub(crate) fn ref_hits(ref_frame: i8) -> usize {
7173 let c = match ref_frame {
7174 LAST2_FRAME => &LAST2_HITS,
7175 LAST3_FRAME => &LAST3_HITS,
7176 GOLDEN_FRAME => &GOLDEN_HITS,
7177 BWDREF_FRAME => &BWDREF_HITS,
7178 ALTREF2_FRAME => &ALTREF2_HITS,
7179 ALTREF_FRAME => &ALTREF_HITS,
7180 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
7181 };
7182 c.with(|v| v.get())
7183}
7184
7185/// The sequence header's `enable_intra_edge_filter`, set once per
7186/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
7187/// own read of it, kept off the call stack (see that function's own doc
7188/// comment for why) rather than threaded through every `read_plane`/
7189/// `decode_block`/`decode_leaf8` call between here and there.
7190
7191/// Set [`ENABLE_EDGE_FILTER`] for this thread.
7192///
7193/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
7194/// never did -- so an inter frame's intra blocks read whatever value the last
7195/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
7196/// harmless (its own key frame sets it first), but a caller that decodes an
7197/// inter frame directly, or a test harness running several streams on one
7198/// thread, inherits a foreign sequence's bit: decode stops being a pure
7199/// function of the bitstream. `decode_stream` now calls this once per stream
7200/// from the sequence header, which covers every frame including inter ones.
7201pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
7202 fctx.enable_edge_filter.with(|f| f.set(value));
7203}
7204
7205/// Current value of [`ANGLE_DELTA_HITS`].
7206#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7207pub(crate) fn angle_delta_hits() -> usize {
7208 ANGLE_DELTA_HITS.with(|c| c.get())
7209}
7210
7211/// Current value of [`TX_CLASS1_HITS`].
7212#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7213pub(crate) fn tx_class1_hits() -> usize {
7214 TX_CLASS1_HITS.with(|c| c.get())
7215}
7216
7217// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
7218// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
7219// bottom) this thread's decode actually reconstructed -- the same
7220// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
7221// genuinely exercised the sub-8x8 leaf path rather than every attempt
7222// coincidentally landing on `PARTITION_NONE`.
7223thread_local! {
7224 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7225 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
7226 /// sub-blocks (lane-intersub8).
7227 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7228 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
7229 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
7230 /// `[1] = VERT` (two BLOCK_4X8).
7231 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
7232 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
7233 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
7234 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
7235 /// MIXED groups whose chroma reference is INTER while its sibling is
7236 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
7237 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
7238 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
7239 /// so only this cell separates the split arm from the HORZ/VERT one).
7240 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
7241}
7242
7243/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
7244/// mixed groups, split 4x4 leaves)`.
7245pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
7246 SUB8_INTRA_RECT_HITS.with(|c| {
7247 let h = c.get();
7248 (h[0], h[1], h[2], h[3], h[4])
7249 })
7250}
7251
7252/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
7253pub fn sub8_inter_rect_hits() -> (usize, usize) {
7254 SUB8_INTER_RECT_HITS.with(|c| {
7255 let h = c.get();
7256 (h[0], h[1])
7257 })
7258}
7259
7260// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
7261// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
7262// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
7263// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
7264// (b) was 0 for every stream before this round -- the leaf path never touched
7265// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
7266// filtered where libaom skips it. A gate asserts both are non-zero.
7267thread_local! {
7268 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7269 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7270 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
7271 // crosses the cropped frame edge -- the only units for which "clamp at
7272 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
7273 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
7274 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
7275 // whose width or height is not a multiple of 8 is the only shape that
7276 // produces one; the straddling-band gate arms assert it grew.
7277 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7278 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
7279 // (see `Neighbours::skip_written`).
7280 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7281 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
7282 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
7283 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
7284 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
7285 // 8-tall strip pair where only one half is skip must still be FILTERED.
7286 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7287 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7288}
7289
7290/// Current value of `RECT_SKIP_BAND_HITS`.
7291pub fn rect_skip_band_hits() -> usize {
7292 RECT_SKIP_BAND_HITS.with(|c| c.get())
7293}
7294
7295/// Current value of `CDEF_MIXED_SKIP_UNITS`.
7296pub fn cdef_mixed_skip_units() -> usize {
7297 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
7298}
7299
7300/// Current value of `CDEF_SKIPPED_UNITS`.
7301#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7302pub(crate) fn cdef_skipped_units() -> usize {
7303 CDEF_SKIPPED_UNITS.with(|c| c.get())
7304}
7305
7306/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
7307/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
7308pub fn cdef_unwritten_skip_units() -> usize {
7309 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
7310}
7311
7312/// Current value of `INTER8_SKIP_BAND_HITS`.
7313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7314pub(crate) fn inter8_skip_band_hits() -> usize {
7315 INTER8_SKIP_BAND_HITS.with(|c| c.get())
7316}
7317
7318/// Current value of `CDEF_STRADDLE_UNITS`.
7319#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7320pub(crate) fn cdef_straddle_units() -> usize {
7321 CDEF_STRADDLE_UNITS.with(|c| c.get())
7322}
7323
7324/// Current value of [`SUB8_SPLIT_HITS`].
7325#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7326pub(crate) fn sub8_split_hits() -> usize {
7327 SUB8_SPLIT_HITS.with(|c| c.get())
7328}
7329
7330/// Current value of [`SUB8_INTER_SPLIT_HITS`].
7331pub fn sub8_inter_split_hits() -> usize {
7332 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
7333}
7334
7335// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
7336// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
7337// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
7338// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
7339// first sub-block's type is never the one). Reading it off sub-block 0
7340// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
7341// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
7342// see this rule through this counter.
7343thread_local! {
7344 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7345}
7346
7347/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
7348pub fn sub8_chroma_tx_from_ref_hits() -> usize {
7349 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
7350}
7351
7352fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
7353 if coeffs && first_sub != chroma_ref {
7354 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
7355 }
7356}
7357
7358// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
7359// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
7360// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
7361// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
7362// asserts on these two rather than a plain leaf count.
7363thread_local! {
7364 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7365 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7366 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
7367 /// two 4x4 transform units, predicted one after the other. A separate
7368 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
7369 /// the gate can prove THIS path fired.
7370 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7371 /// 16x8/8x16 intra strips whose prediction actually read past the block's
7372 /// own width (above-right) or height (below-left) -- the samples
7373 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
7374 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
7375 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7376 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
7377 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
7378 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7379}
7380
7381/// Current value of [`RECT8_SPLIT_TX_HITS`].
7382#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7383pub(crate) fn rect8_split_tx_hits() -> usize {
7384 RECT8_SPLIT_TX_HITS.with(|c| c.get())
7385}
7386
7387/// Current value of [`RECT_STRIP_PRED_HITS`].
7388#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7389pub(crate) fn rect_strip_pred_hits() -> usize {
7390 RECT_STRIP_PRED_HITS.with(|c| c.get())
7391}
7392
7393/// Current value of [`RECT_STRIP_REACH_HITS`].
7394#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7395pub(crate) fn rect_strip_reach_hits() -> usize {
7396 RECT_STRIP_REACH_HITS.with(|c| c.get())
7397}
7398
7399/// Current value of [`TX4X8_CODED_HITS`].
7400#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7401pub(crate) fn tx4x8_coded_hits() -> usize {
7402 TX4X8_CODED_HITS.with(|c| c.get())
7403}
7404
7405/// Current value of [`TX8X4_CODED_HITS`].
7406#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7407pub(crate) fn tx8x4_coded_hits() -> usize {
7408 TX8X4_CODED_HITS.with(|c| c.get())
7409}
7410
7411// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
7412// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
7413// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
7414// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
7415// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
7416// (`eob_pt_{16,64,128,256}_chroma_class1`).
7417thread_local! {
7418 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
7419 const { std::cell::Cell::new(0) };
7420}
7421
7422/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
7423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7424pub(crate) fn chroma_eob_class1_hits() -> usize {
7425 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
7426}
7427
7428/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
7429/// `tx_type` put this block's `eob_pt` on the class-1 row.
7430fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
7431 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
7432 hit!(CHROMA_EOB_CLASS1_HITS);
7433 }
7434}
7435
7436// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
7437// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
7438// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
7439// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
7440// looked identical to a same-plane disagreement. Set by `exec_intra` (the
7441// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
7442// by the `EC_PRED` rung, so it cannot change a decode.
7443thread_local! {
7444 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7445}
7446
7447/// The plane index the `EC_PRED` rung prints as `plane=`.
7448fn recon_plane() -> usize {
7449 RECON_PLANE.with(std::cell::Cell::get)
7450}
7451
7452/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
7453/// either of its two early returns.
7454struct PlaneGuard(usize);
7455impl Drop for PlaneGuard {
7456 fn drop(&mut self) {
7457 RECON_PLANE.with(|c| c.set(self.0));
7458 }
7459}
7460
7461const SUB_MI: u32 = 4;
7462const MI: usize = 4;
7463const SB: usize = 64;
7464/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
7465/// (tile start, superblock-row start).
7466///
7467/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
7468/// `av1_get_partition_plane_context` reads its own zero-initialised
7469/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
7470/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
7471/// (64), which reads identically at every level up to 64x64 but sets the bit
7472/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
7473/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
7474/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
7475const NO_NEIGHBOUR_SIDE: usize = 128;
7476const BLOCK: usize = 32;
7477const SUB: usize = 16;
7478const TX32: usize = 32;
7479const TX16: usize = 16;
7480const TX8: usize = 8;
7481const TX4: usize = 4;
7482const DC_PRED: usize = 0;
7483/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7484/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7485/// constant.
7486const V_PRED: usize = 1;
7487const H_PRED: usize = 2;
7488/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7489/// `Fimode_To_Intradir`, libaom `blockd.h`).
7490const D157_PRED: usize = 6;
7491/// The last directional mode, `D67_PRED`.
7492const D67_PRED: usize = 8;
7493/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7494/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7495/// codes anything else, so this decoder never reads anything else either.
7496const ANGLE_DELTA_ZERO: usize = 3;
7497const NUM_BASE_LEVELS: i32 = 2;
7498const COEFF_BASE_RANGE: i32 = 12;
7499const BR_STEP: i32 = 3;
7500const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7501
7502/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7503/// whose probability mass a superblock or block half outside the frame
7504/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7505/// duplicated here (that module is another lane's territory this round) and
7506/// kept in step with it by the byte-exact round-trip tests below rather than
7507/// by sharing code.
7508const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7509const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7510
7511fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7512 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7513 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7514 }
7515}
7516
7517fn element_prob(cdf: &[u16], element: usize) -> u16 {
7518 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7519}
7520
7521/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7522/// with: the mass of `elements` becomes the probability of the one partition
7523/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7524/// (the encoder's non-adapting counterpart to this read).
7525fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7526 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7527 [32768 - split, 32768, 0]
7528}
7529
7530fn unsupported(what: impl Into<String>) -> Error {
7531 Error::unsupported("AV1 tile", what.into())
7532}
7533
7534/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7535/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7536/// same rule.
7537pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7538 match base_q_idx {
7539 0..=20 => 0,
7540 21..=60 => 1,
7541 61..=120 => 2,
7542 _ => 3,
7543 }
7544}
7545
7546/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7547/// [`crate::tile`]'s writer generates its scan tables with.
7548fn default_scan(side: usize) -> &'static [u16] {
7549 // One table per transform side (4/8/16/32), built once: this used to be a
7550 // fresh heap allocation plus the whole anti-diagonal walk on every
7551 // transform block read.
7552 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7553 [
7554 default_scan_gen(4),
7555 default_scan_gen(8),
7556 default_scan_gen(16),
7557 default_scan_gen(32),
7558 ]
7559 });
7560 assert!(
7561 matches!(side, 4 | 8 | 16 | 32),
7562 "no default scan for a {side}-point transform"
7563 );
7564 &SCANS[side.trailing_zeros() as usize - 2]
7565}
7566
7567fn default_scan_gen(side: usize) -> Vec<u16> {
7568 let mut scan = Vec::with_capacity(side * side);
7569 for d in 0..(2 * side - 1) {
7570 let lo = d.saturating_sub(side - 1);
7571 let hi = d.min(side - 1);
7572 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7573 if d % 2 == 0 {
7574 scan.extend(diagonal.rev());
7575 } else {
7576 scan.extend(diagonal);
7577 }
7578 }
7579 scan
7580}
7581
7582/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7583/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7584/// in, instead of the default zigzag. libaom's own tables are keyed by a
7585/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7586/// physically column-major level buffer, but they decompose to the exact
7587/// same (row, col) walk as a flat row-major traversal of *our* row-major
7588/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7589/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7590/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7591/// transposed (column 0 down every row, then column 1, ...).
7592pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7593 class_scan_table_wh(side, side, class)
7594}
7595
7596/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7597/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7598/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7599/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7600/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7601/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7602fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7603 match class {
7604 TxClass::Vert => (0..(w * h) as u16).collect(),
7605 TxClass::Horiz => (0..w)
7606 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7607 .collect(),
7608 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7609 }
7610}
7611
7612fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7613 match scan_idx {
7614 0 => 0,
7615 i if i <= area / 8 => 1,
7616 i if i <= area / 4 => 2,
7617 _ => 3,
7618 }
7619}
7620
7621/// One cell of [`read_coeffs`]'s level buffer.
7622///
7623/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7624/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7625/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7626/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7627/// zero cells instead of needing the `row >= side || col >= side` edge test
7628/// this used to run five times per coefficient. Nothing writes a padding
7629/// cell, so the values are the same zeros the test returned.
7630#[inline]
7631fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7632 grid[row * stride + col] as i32
7633}
7634
7635/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7636/// `txb_common.h`): everything but the two lone-axis-identity types this
7637/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7638#[derive(Clone, Copy, PartialEq, Eq)]
7639pub(crate) enum TxClass {
7640 TwoD,
7641 Horiz,
7642 Vert,
7643}
7644
7645impl TxClass {
7646 pub(crate) fn of(tx_type: TxType) -> Self {
7647 match tx_type {
7648 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7649 // key on axis alone -- FLIPADST is still ADST for this purpose.
7650 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7651 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7652 _ => Self::TwoD,
7653 }
7654 }
7655}
7656
7657/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7658/// table (indexed by the position along the transform's *coded* axis --
7659/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7660/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7661/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7662pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7663 match i {
7664 0 => 26,
7665 1 => 31,
7666 _ => 36,
7667 }
7668}
7669
7670fn base_ctx(
7671 grid: &[u8],
7672 stride: usize,
7673 row: usize,
7674 col: usize,
7675 class: TxClass,
7676 rect_shape: Option<(usize, usize)>,
7677) -> usize {
7678 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7679 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7680 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7681 // position through the full 1D neighbour sum and offset table. Skipping
7682 // that for every class desynced the last (DC) coefficient of a
7683 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7684 // 0, which then read one extra `BR` symbol at the max and forced a
7685 // spurious third Golomb call).
7686 if class == TxClass::TwoD && row == 0 && col == 0 {
7687 return 0;
7688 }
7689 let offsets: [(usize, usize); 5] = match class {
7690 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7691 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7692 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7693 };
7694 let mag: i32 = offsets
7695 .iter()
7696 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7697 .sum();
7698 let ctx = ((mag + 1) >> 1).min(4) as usize;
7699 match class {
7700 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7701 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7702 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7703 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7704 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7705 // strip, which own a genuinely different table from the square one
7706 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7707 // square table vs the real ctx 13 the rect table gives).
7708 TxClass::TwoD => {
7709 // lane-rectsplit r4: apply libaom's GENERATING RULE
7710 // (`txb_common.h:199-209`) directly instead of indexing the
7711 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7712 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7713 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7714 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7715 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7716 // transcriptions are `[col][row]` and this read had them as
7717 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7718 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7719 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7720 // pins the rule against the tables over their whole 5x5 domain.
7721 if let Some((w, h)) = rect_shape {
7722 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7723 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7724 }
7725 if w < h && row < 2 {
7726 return ctx + 11;
7727 }
7728 if w > h && col < 2 {
7729 return ctx + 16;
7730 }
7731 }
7732 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7733 }
7734 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7735 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7736 }
7737}
7738
7739/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7740/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7741/// function of the tx class alone, which is fixed for a whole transform unit,
7742/// so resolving it once per unit takes the class match and the `(dr, dc)`
7743/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7744/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7745/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7746/// original `(dr, dc)` form.
7747fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7748 match class {
7749 TxClass::TwoD => (
7750 [stride, 1, stride + 1, 2 * stride, 2],
7751 [stride, 1, stride + 1],
7752 ),
7753 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7754 TxClass::Vert => (
7755 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7756 [stride, 1, 2 * stride],
7757 ),
7758 }
7759}
7760
7761/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7762/// neighbours) + 1) >> 1`, clamped to 4.
7763#[inline(always)]
7764fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7765 let mut mag = 0u32;
7766 for &t in taps {
7767 mag += u32::from(grid[idx + t]).min(3);
7768 }
7769 (((mag + 1) >> 1) as usize).min(4)
7770}
7771
7772/// [`br_ctx`]'s neighbour sum, off flat taps.
7773#[inline(always)]
7774fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7775 let mut mag = 0u32;
7776 for &t in taps {
7777 mag += u32::from(grid[idx + t]);
7778 }
7779 (((mag + 1) >> 1) as usize).min(6)
7780}
7781
7782/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7783/// origin-offset tail the two coefficient readers state inline; kept as the
7784/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7785/// flat one against.
7786#[cfg(test)]
7787fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7788 let extra = match class {
7789 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7790 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7791 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7792 };
7793 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7794 let mag = (((mag + 1) >> 1).min(6)) as usize;
7795 if row == 0 && col == 0 {
7796 return mag;
7797 }
7798 let near_origin = match class {
7799 TxClass::TwoD => row < 2 && col < 2,
7800 TxClass::Horiz => col == 0,
7801 TxClass::Vert => row == 0,
7802 };
7803 if near_origin { mag + 7 } else { mag + 14 }
7804}
7805
7806/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7807/// transposed from libaom's column-major buffer into this decoder's row-major
7808/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7809/// against the real table). Not the square zigzag formula generalized to
7810/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7811const SCAN_32X16: [u16; 512] = [
7812 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7813 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7814 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7815 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7816 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7817 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7818 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7819 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7820 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7821 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7822 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7823 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7824 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7825 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7826 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7827 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7828 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7829 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7830 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7831 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7832 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7833 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7834 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7835 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7836 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7837 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7838 510, 479, 511,
7839];
7840
7841/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7842/// [`SCAN_32X16`]'s doc comment).
7843const SCAN_16X32: [u16; 512] = [
7844 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,
7845 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7846 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7847 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7848 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7849 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7850 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7851 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7852 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7853 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7854 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7855 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7856 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7857 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7858 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7859 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7860 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7861 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7862 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7863 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7864 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7865 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7866 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7867 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7868 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7869 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7870];
7871
7872/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7873/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7874/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7875/// the same source).
7876const SCAN_4X8: [u16; 32] = [
7877 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,
7878 23, 26, 29, 27, 30, 31,
7879];
7880
7881/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7882const SCAN_8X4: [u16; 32] = [
7883 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,
7884 29, 22, 15, 30, 23, 31,
7885];
7886
7887/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7888/// [`SCAN_32X16`]'s doc comment).
7889const SCAN_16X8: [u16; 128] = [
7890 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,
7891 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7892 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7893 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7894 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7895 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7896];
7897
7898/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7899/// [`SCAN_32X16`]'s doc comment).
7900const SCAN_8X16: [u16; 128] = [
7901 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,
7902 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7903 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7904 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7905 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7906 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7907];
7908
7909/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7910/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7911/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7912/// scans column-major (`p = col * height + row`), so a naive copy of
7913/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7914/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7915/// are byte-identical to this decoder's [`SCAN_8X16`].
7916const SCAN_32X8: [u16; 256] = [
7917 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7918 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7919 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7920 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7921 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7922 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7923 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7924 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7925 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7926 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7927 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7928 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7929 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7930];
7931/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7932/// 16x64 `PARTITION_VERT_4` strip).
7933const SCAN_8X32: [u16; 256] = [
7934 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,
7935 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7936 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7937 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7938 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7939 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7940 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7941 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7942 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7943 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7944 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7945 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7946 239, 246, 253, 247, 254, 255,
7947];
7948/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7949/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7950/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7951/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7952/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7953/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7954/// were emitted -- a naive copy installs the transpose (class
7955/// reference-layout-not-spec).
7956const SCAN_16X4: [u16; 64] = [
7957 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,
7958 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7959 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7960];
7961/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7962/// 8x32 `PARTITION_VERT_4` strip).
7963const SCAN_4X16: [u16; 64] = [
7964 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,
7965 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7966 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7967];
7968
7969/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7970/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7971/// padding already holds.
7972#[inline]
7973fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7974 grid[row * stride + col] as i32
7975}
7976
7977/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7978/// the rect generalization is libaom's own comment in
7979/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7980/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7981/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7982/// [`decode_block_rect`] codes (see that function's own doc comment).
7983fn base_ctx_rect(
7984 grid: &[u8],
7985 stride: usize,
7986 w: usize,
7987 h: usize,
7988 row: usize,
7989 col: usize,
7990 class: TxClass,
7991) -> usize {
7992 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7993 // the 2D class short-circuits the DC position.
7994 if class == TxClass::TwoD && row == 0 && col == 0 {
7995 return 0;
7996 }
7997 let offsets: [(usize, usize); 5] = match class {
7998 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7999 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
8000 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
8001 };
8002 let mag: i32 = offsets
8003 .iter()
8004 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
8005 .sum();
8006 let ctx = ((mag + 1) >> 1).min(4) as usize;
8007 match class {
8008 TxClass::TwoD => {
8009 if w < h && row < 2 {
8010 return ctx + 11;
8011 }
8012 if w > h && col < 2 {
8013 return ctx + 16;
8014 }
8015 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8016 }
8017 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
8018 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
8019 // position along one axis only).
8020 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
8021 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
8022 }
8023}
8024
8025/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
8026/// neighbour-offset math itself is shape-independent, only the boundary
8027/// clamp needs the real bound in each axis.
8028/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
8029/// its body was character-for-character [`br_ctx`]'s, which
8030/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
8031#[cfg(test)]
8032fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
8033 let extra = match class {
8034 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
8035 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
8036 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
8037 };
8038 let mag = neighbour_rect(grid, stride, row + 1, col)
8039 + neighbour_rect(grid, stride, row, col + 1)
8040 + extra;
8041 let mag = (((mag + 1) >> 1).min(6)) as usize;
8042 if row == 0 && col == 0 {
8043 return mag;
8044 }
8045 let near_origin = match class {
8046 TxClass::TwoD => row < 2 && col < 2,
8047 TxClass::Horiz => col == 0,
8048 TxClass::Vert => row == 0,
8049 };
8050 if near_origin { mag + 7 } else { mag + 14 }
8051}
8052
8053fn dc_vote(dc: Option<bool>) -> i32 {
8054 match dc {
8055 None => 0,
8056 Some(true) => -1,
8057 Some(false) => 1,
8058 }
8059}
8060
8061fn dc_sign_ctx(vote: i32) -> usize {
8062 match vote.signum() {
8063 0 => 0,
8064 -1 => 1,
8065 _ => 2,
8066 }
8067}
8068
8069/// The `tx_type` a CDF symbol names, given the width of the row it was read
8070/// from.
8071///
8072/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
8073/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
8074/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
8075/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
8076/// members are a prefix of the five.
8077///
8078/// One function rather than a `match` at each reader, so
8079/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
8080/// tests the mapping the readers actually use.
8081pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
8082 match cdf_len {
8083 17 => TxType::from_symbol_all16(t),
8084 13 => TxType::from_symbol_set2_12(t),
8085 8 => TxType::from_symbol_set1(t),
8086 _ => TxType::from_symbol(t),
8087 }
8088}
8089
8090/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
8091/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
8092/// (class `table-and-reader-move-together` -- the writer picks its symbol
8093/// through the reader's own map, so the two cannot drift).
8094pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
8095 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
8096}
8097
8098/// The remainder of a level the base and base-range syntax could not reach
8099/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
8100/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
8101pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
8102 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
8103 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
8104 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
8105 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
8106 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
8107 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
8108 // stream_can_carry` enumerates that whole value domain.
8109 //
8110 // So this refusal never names a reader gap: it is always the SYMPTOM of an
8111 // earlier desync (class `refusal-hides-a-defect`), and every historical
8112 // instance was closed by fixing that desync -- lane-dgolomb's
8113 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
8114 // Raising the cap only trades a clean refusal for silent corruption:
8115 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
8116 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
8117 // from a refusal into a frame-0 LUMA MISMATCH.
8118 let mut length = 1u32;
8119 while dec.literal(1) == 0 {
8120 length += 1;
8121 if length > 20 {
8122 return Err(unsupported("a Golomb tail longer than this decoder reads"));
8123 }
8124 }
8125 let mut x = 1u32;
8126 for _ in 1..length {
8127 x = (x << 1) | dec.literal(1);
8128 }
8129 Ok(x - 1)
8130}
8131
8132/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
8133/// [`crate::tile`]'s `write_eob`.
8134fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
8135 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
8136 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
8137
8138 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8139 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
8140 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
8141 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
8142 // `eob_multi_ctx`). Missing that split desynced the very first
8143 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
8144 // against a real aomdec trace).
8145 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
8146 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
8147 (_, Some(class1)) => class1,
8148 };
8149 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8150 let (range, value) = dec.debug_state();
8151 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
8152 }
8153 crate::msac::SymbolDecoder::set_symr_cdf("eob_pt");
8154 let group = dec.symbol(eob_pt) + 1;
8155 if trace {
8156 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
8157 }
8158 let bits = OFFSET_BITS[group];
8159 let mut offset = 0u32;
8160 if bits > 0 {
8161 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
8162 if trace {
8163 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
8164 }
8165 offset = top << (bits - 1);
8166 if bits > 1 {
8167 offset |= dec.literal(bits - 1);
8168 }
8169 }
8170 GROUP_START[group] + offset as usize
8171}
8172
8173/// One transform block's levels, the inverse of [`crate::tile`]'s
8174/// `write_coeffs`, returned as a `side * side` grid in raster order, along
8175/// with the transform type that grid was coded under (`DCT_DCT` when the
8176/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
8177/// 64-point transforms, which never code anything else).
8178///
8179/// # Errors
8180/// Returns an error if the `tx_type` symbol decodes to a value outside its
8181/// CDF's own set (a corrupt or unsupported bitstream) — every value the
8182/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
8183/// produce dispatches to a real inverse transform.
8184/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
8185/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
8186/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
8187/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
8188/// the plane's own predicted mode instead. Every entry this table can
8189/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
8190/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
8191/// table ever names), so unlike the CDF-coded luma path there is no
8192/// ext-tx-set membership check to fall back from here.
8193pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
8194 use crate::intra::{
8195 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
8196 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
8197 };
8198 match mode {
8199 DC_PRED | D45_PRED => TxType::DctDct,
8200 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
8201 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
8202 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
8203 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
8204 }
8205}
8206
8207/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
8208/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
8209/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
8210fn is_smooth_mode(mode: usize) -> bool {
8211 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
8212}
8213
8214/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
8215/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
8216/// nine of them inside the base/sign loops pinned nine sets of values in the
8217/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
8218/// traffic). Out of line, the loop keeps its values in registers and the
8219/// trace output is character-for-character what it was.
8220#[cold]
8221#[inline(never)]
8222fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
8223 eprintln!(
8224 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
8225 );
8226}
8227
8228#[cold]
8229#[inline(never)]
8230fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
8231 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
8232}
8233
8234#[cold]
8235#[inline(never)]
8236fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
8237 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
8238}
8239
8240#[cold]
8241#[inline(never)]
8242fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
8243 let (rng, _) = dec.debug_state();
8244 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
8245}
8246
8247#[cold]
8248#[inline(never)]
8249fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
8250 let (rng, _) = dec.debug_state();
8251 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
8252}
8253
8254#[cold]
8255#[inline(never)]
8256fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
8257 let (rng, _) = dec.debug_state();
8258 eprintln!(
8259 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
8260 negative as i32
8261 );
8262}
8263
8264#[cold]
8265#[inline(never)]
8266fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
8267 let (rng, _) = dec.debug_state();
8268 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
8269}
8270
8271#[cold]
8272#[inline(never)]
8273fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
8274 let (rng, _) = dec.debug_state();
8275 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
8276}
8277
8278// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
8279#[track_caller]
8280fn read_coeffs(
8281 dec: &mut SymbolDecoder,
8282 coding: &mut TxbTables,
8283 scan: &[u16],
8284 skip_ctx: usize,
8285 sign_ctx: usize,
8286 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
8287 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
8288 // nothing at all; `DctDct` for every luma call and every chroma call at
8289 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
8290 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
8291 default_tx_type: TxType,
8292 // `Some((w, h))` with `w != h` when this read is a superblock-level
8293 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
8294 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
8295 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
8296 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
8297 // caller's block genuinely is `side` x `side`.
8298 rect_shape: Option<(usize, usize)>,
8299) -> Result<(Grid, TxType)> {
8300 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8301 let side = coding.side;
8302 // lane-av1readcensus: this unit's own entry state, so the census line
8303 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
8304 // (which prints `r->ec.rng` before the same `txb_skip` read).
8305 let census_entry_rng = dec.debug_state().0;
8306 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
8307 // lane-av1ibcfork: the per-unit BIT INTERVAL, the twin of the oracle's
8308 // `EC_ECDUMP_IN` / `_OUT` / `_END`. The census plane, not a fresh label:
8309 // it is the same source `census_unit` reads, so the interval line and the
8310 // census line can never disagree about which plane a unit is on.
8311 let iv_plane = CENSUS_PLANE.with(|c| c.get()).min(2);
8312 let iv_bit = unit_iv_in(iv_plane, census_w, census_h, skip_ctx, dec);
8313 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8314 let (range, value) = dec.debug_state();
8315 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
8316 }
8317 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
8318 let (range, value) = dec.debug_state();
8319 let bit = dec.debug_bitpos();
8320 eprintln!(
8321 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
8322 );
8323 }
8324 let dbg_txbskip = if coeff_trace_on() {
8325 coding.txb_skip[skip_ctx]
8326 } else {
8327 [0; 3]
8328 };
8329 let sq_bit = if coeff_trace_on() {
8330 dec.debug_bitpos()
8331 } else {
8332 0
8333 };
8334 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8335 unit_iv_skip(
8336 dec, iv_bit, iv_plane, census_w, census_h, skip_ctx, all_zero,
8337 );
8338 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
8339 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
8340 // filter on it before pairing anything against the oracle.
8341 if crate::envflags::env_flag!("EC_IBCTX") {
8342 eprintln!(
8343 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
8344 coding.side,
8345 std::panic::Location::caller(),
8346 );
8347 }
8348 if coeff_trace_on() {
8349 let (rng, _) = dec.debug_state();
8350 eprintln!(
8351 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}",
8352 coding.side,
8353 all_zero as i32,
8354 dec.debug_bitpos()
8355 );
8356 }
8357 if crate::envflags::env_flag!("EC_AV1_TELL") {
8358 eprintln!(
8359 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
8360 all_zero as u8,
8361 dec.debug_bitpos(),
8362 dec.debug_state().0
8363 );
8364 }
8365 if trace {
8366 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
8367 }
8368 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8369 let (range, value) = dec.debug_state();
8370 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
8371 }
8372 if all_zero {
8373 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
8374 // shared zero grid instead of allocating and zeroing its own.
8375 census_unit(
8376 census_w,
8377 census_h,
8378 TxType::DctDct,
8379 0,
8380 true,
8381 census_entry_rng,
8382 dec,
8383 );
8384 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
8385 return Ok((Grid::Zero(side * side), TxType::DctDct));
8386 }
8387 let mut grid = vec![0i32; side * side];
8388 let mut tx_type = default_tx_type;
8389 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8390 // The CDF row's own width names its set (lane-cdffwd2: extended
8391 // past the original two-way intra split once wider `reduced_tx_set
8392 // == 0` inter sets joined the table): 17 slots (16 symbols) is
8393 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
8394 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
8395 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
8396 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
8397 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
8398 let len = tx_type_cdf.len();
8399 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
8400 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
8401 }
8402 crate::msac::SymbolDecoder::set_symr_cdf("tx_type");
8403 let t = dec.symbol(tx_type_cdf);
8404 crate::census::tx_type(len, t);
8405 if coeff_trace_on() {
8406 let (rng, _) = dec.debug_state();
8407 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
8408 }
8409 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8410 let (range, value) = dec.debug_state();
8411 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
8412 }
8413 if trace {
8414 eprintln!("TRACE tx_type value={t} len={len}");
8415 }
8416 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8417 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8418 })?;
8419 }
8420
8421 let class = TxClass::of(tx_type);
8422 if class != TxClass::TwoD {
8423 hit!(TX_CLASS1_HITS);
8424 hit!(RECT_CLASS1_HITS);
8425 }
8426 let eob = read_eob(dec, coding, class);
8427 if trace {
8428 eprintln!("TRACE eob value={eob}");
8429 }
8430 let ec_trace_coeff = coeff_trace_on();
8431 if ec_trace_coeff {
8432 let (rng, _) = dec.debug_state();
8433 let cls = match class {
8434 TxClass::TwoD => "2d",
8435 TxClass::Horiz => "horiz",
8436 TxClass::Vert => "vert",
8437 };
8438 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
8439 }
8440 let class_scan;
8441 let scan: &[u16] = if class == TxClass::TwoD {
8442 scan
8443 } else {
8444 class_scan = class_scan_table(side, class);
8445 &class_scan
8446 };
8447 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
8448 // coefficient `pos / side`, `pos % side` was a hardware divide where a
8449 // shift and a mask say the same thing, and the level buffer fits a fixed
8450 // 32x32 frame of stack instead of a heap allocation per transform block.
8451 debug_assert!(side.is_power_of_two() && side <= 32);
8452 let sh = side.trailing_zeros();
8453 let col_mask = side - 1;
8454 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
8455 // `stride = side + 4` columns and four spare rows, so the widest read
8456 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
8457 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
8458 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
8459 let stride = side + 4;
8460 let mut levels_buf = [0u8; 36 * 36];
8461 let levels = &mut levels_buf[..stride * stride];
8462 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
8463 // `pos >> sh` / `& mask` decomposition and load the level back out of the
8464 // padded frame just to skip the zeros. The base pass already knows both,
8465 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
8466 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
8467 // pass walks that list in reverse (the base pass runs in reverse scan
8468 // order, so reversing it is forward scan order: the same coefficients, in
8469 // the same order, with the same `c` the trace prints).
8470 let mut nz_buf = [0u16; 1024];
8471 let mut nz_n = 0usize;
8472 let (base_taps, br_taps) = flat_taps(stride, class);
8473 for scan_idx in (0..eob).rev() {
8474 let pos = scan[scan_idx] as usize;
8475 let (row, col) = (pos >> sh, pos & col_mask);
8476 let idx = row * stride + col;
8477 let level = if scan_idx == eob - 1 {
8478 let ctx = eob_coeff_ctx(scan_idx, side * side);
8479 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8480 if trace {
8481 trace_base_eob(scan_idx, pos, row, col, ctx, v);
8482 }
8483 v
8484 } else {
8485 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
8486 if row == 0 && col == 0 {
8487 0
8488 } else {
8489 base_mag(levels, idx, &base_taps)
8490 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8491 }
8492 } else {
8493 base_ctx(levels, stride, row, col, class, rect_shape)
8494 };
8495 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8496 if ec_trace_coeff {
8497 // `pos` in libaom's column-major `coeff_idx` convention, so
8498 // the ladder lines up with instrumented `aomdec`.
8499 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
8500 }
8501 if trace {
8502 trace_base(scan_idx, pos, row, col, ctx, v);
8503 }
8504 v
8505 };
8506 let level = if level > NUM_BASE_LEVELS {
8507 let ctx = {
8508 let mag = br_mag(levels, idx, &br_taps);
8509 if row == 0 && col == 0 {
8510 mag
8511 } else {
8512 let near_origin = match class {
8513 TxClass::TwoD => row < 2 && col < 2,
8514 TxClass::Horiz => col == 0,
8515 TxClass::Vert => row == 0,
8516 };
8517 if near_origin { mag + 7 } else { mag + 14 }
8518 }
8519 };
8520 let mut level = level;
8521 let mut sent = 0;
8522 loop {
8523 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8524 if ec_trace_coeff {
8525 // lane-leaf8tx r3: the `br` rung was missing from THIS
8526 // path's trace, so the cross-decoder range ladder was
8527 // blind to every base-range symbol and mis-reported the
8528 // first divergence (class [[gate-blind-to-feature]]).
8529 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8530 }
8531 if trace {
8532 trace_br(scan_idx, pos, row, col, ctx, k);
8533 }
8534 level += k;
8535 sent += BR_STEP;
8536 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8537 break;
8538 }
8539 }
8540 level
8541 } else {
8542 level
8543 };
8544 if ec_trace_coeff && scan_idx == eob - 1 {
8545 coeff_step_base_eob_level(dec, level);
8546 }
8547 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8548 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8549 // added in the sign pass below, straight into `grid`), so the context
8550 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8551 // byte gather (lane-coefbuf).
8552 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8553 levels[idx] = level as u8;
8554 if level != 0 {
8555 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8556 nz_n += 1;
8557 }
8558 }
8559 if ec_trace_coeff {
8560 let (rng, _) = dec.debug_state();
8561 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8562 }
8563
8564 for &packed in nz_buf[..nz_n].iter().rev() {
8565 let c = (packed >> 4) as usize;
8566 let pos = scan[c] as usize;
8567 let level = (packed & 15) as i32;
8568 let negative = if pos == 0 {
8569 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8570 if trace {
8571 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8572 }
8573 v
8574 } else {
8575 dec.literal(1) == 1
8576 };
8577 if ec_trace_coeff {
8578 coeff_step_sign(dec, c, negative);
8579 }
8580 let level = if level > MAX_BR_LEVEL {
8581 let g = read_golomb(dec)?;
8582 if trace {
8583 eprintln!("TRACE golomb pos={pos} value={g}");
8584 }
8585 level + g as i32
8586 } else {
8587 level
8588 };
8589 if ec_trace_coeff {
8590 coeff_step_post_golomb(dec, c, level);
8591 }
8592 grid[pos] = if negative { -level } else { level };
8593 }
8594 census_unit(
8595 census_w,
8596 census_h,
8597 tx_type,
8598 eob,
8599 false,
8600 census_entry_rng,
8601 dec,
8602 );
8603 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
8604 Ok((Grid::Own(grid), tx_type))
8605}
8606
8607/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8608/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8609/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8610/// can ever produce, since every `tx_type` this decoder's rect sets can read
8611/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8612/// rather than guess-decode if a non-2D class ever shows up here, since
8613/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8614/// form for those.
8615
8616// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
8617// of this reader -- the only thing that identifies a unit's route. No plane is
8618// printed here: the plane is the ORACLE's side of the pairing, and a label
8619// here is one more thing that can disagree with it.
8620#[track_caller]
8621fn read_coeffs_rect(
8622 dec: &mut SymbolDecoder,
8623 coding: &mut TxbTables,
8624 scan: &[u16],
8625 w: usize,
8626 h: usize,
8627 skip_ctx: usize,
8628 sign_ctx: usize,
8629 default_tx_type: TxType,
8630 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8631 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8632 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8633 // independent lane reports.
8634 plane: usize,
8635) -> Result<(Grid, TxType)> {
8636 let rect_trace = coeff_trace_on();
8637 let entry_rng = dec.debug_state().0;
8638 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8639 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8640 // plane itself rather than inheriting whichever reader did last. The
8641 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8642 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8643 // value -- and the other plane-owning readers stamp on entry.
8644 set_census_plane(plane);
8645 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
8646 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
8647 let iv_bit = unit_iv_in(plane, w, h, skip_ctx, dec);
8648 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8649 unit_iv_skip(dec, iv_bit, plane, w, h, skip_ctx, all_zero);
8650 if rect_trace {
8651 eprintln!(
8652 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
8653 all_zero as i32,
8654 dec.debug_state().0,
8655 dec.debug_bitpos()
8656 );
8657 }
8658 if ibctx_on {
8659 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
8660 // range: the only collision-free key for pairing this unit against the
8661 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
8662 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
8663 // either way, which is exactly the artifact that made an earlier
8664 // round of this lane claim a false exactness.
8665 eprintln!(
8666 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
8667 dec.debug_bitpos(),
8668 std::panic::Location::caller(),
8669 );
8670 }
8671 if all_zero {
8672 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8673 unit_iv_end(dec, plane, w, h, skip_ctx);
8674 return Ok((Grid::Zero(w * h), TxType::DctDct));
8675 }
8676 let mut grid = vec![0i32; w * h];
8677 hit!(RECT_COEFF_TU_HITS);
8678 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8679 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8680 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8681 // context offsets -- both of which now have rect forms
8682 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8683 // The rect sets that carry no symbol at all still pass `None` here.
8684 let mut tx_type = default_tx_type;
8685 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8686 let len = tx_type_cdf.len();
8687 let t = dec.symbol(tx_type_cdf);
8688 crate::census::tx_type(len, t);
8689 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8690 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8691 })?;
8692 if rect_trace {
8693 eprintln!(
8694 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8695 dec.debug_state().0
8696 );
8697 }
8698 }
8699 let class = TxClass::of(tx_type);
8700 if class != TxClass::TwoD {
8701 hit!(TX_CLASS1_HITS);
8702 }
8703 let eob = read_eob(dec, coding, class);
8704 if rect_trace {
8705 eprintln!(
8706 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8707 dec.debug_state().0
8708 );
8709 }
8710 let class_scan;
8711 let scan: &[u16] = if class == TxClass::TwoD {
8712 scan
8713 } else {
8714 class_scan = class_scan_table_wh(w, h, class);
8715 &class_scan
8716 };
8717 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8718 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8719 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8720 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8721 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8722 // mask rather than a hardware divide.
8723 let stride = w + 4;
8724 let n = stride * (h + 4);
8725 if !(w.is_power_of_two() && n <= 36 * 36) {
8726 panic!("rect coeff scratch w={w} h={h} n={n}");
8727 }
8728 let (mut b96, mut b256, mut b768);
8729 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8730 let levels: &mut [u8] = if n <= 96 {
8731 b96 = [0u8; 96];
8732 &mut b96[..n]
8733 } else if n <= 256 {
8734 b256 = [0u8; 256];
8735 &mut b256[..n]
8736 } else {
8737 b768 = [0u8; 768];
8738 &mut b768[..n]
8739 };
8740 let wsh = w.trailing_zeros();
8741 let wmask = w - 1;
8742 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8743 let mut nz_buf = [0u16; 1024];
8744 let mut nz_n = 0usize;
8745 let (base_taps, br_taps) = flat_taps(stride, class);
8746 let (wlt, wgt) = (w < h, w > h);
8747 for scan_idx in (0..eob).rev() {
8748 let pos = scan[scan_idx] as usize;
8749 let (row, col) = (pos >> wsh, pos & wmask);
8750 let idx = row * stride + col;
8751 // libaom's column-major `coeff_idx`, for ladder comparison.
8752 let _apos = col * h + row;
8753 let level = if scan_idx == eob - 1 {
8754 let ctx = eob_coeff_ctx(scan_idx, w * h);
8755 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8756 // lane-av1oddheightfork2: the `base_eob` rung moved to the end of
8757 // the loop body (below). libaom prints its `tag=base_eob` AFTER
8758 // that coefficient's own br loop (decodetxb.c:317-338), so the rung
8759 // has to carry the POST-br level and rng to be the oracle's twin;
8760 // printed here it labelled the pre-br read and every rect unit's
8761 // ladder disagreed with aomdec by exactly its br tail.
8762 v
8763 } else {
8764 let ctx = if class == TxClass::TwoD {
8765 if row == 0 && col == 0 {
8766 0
8767 } else {
8768 let m = base_mag(levels, idx, &base_taps);
8769 if wlt && row < 2 {
8770 m + 11
8771 } else if wgt && col < 2 {
8772 m + 16
8773 } else {
8774 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8775 }
8776 }
8777 } else {
8778 base_ctx_rect(levels, stride, w, h, row, col, class)
8779 };
8780 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8781 if rect_trace {
8782 eprintln!(
8783 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8784 dec.debug_state().0
8785 );
8786 }
8787 v
8788 };
8789 let level = if level > NUM_BASE_LEVELS {
8790 let ctx = {
8791 let mag = br_mag(levels, idx, &br_taps);
8792 if row == 0 && col == 0 {
8793 mag
8794 } else {
8795 let near_origin = match class {
8796 TxClass::TwoD => row < 2 && col < 2,
8797 TxClass::Horiz => col == 0,
8798 TxClass::Vert => row == 0,
8799 };
8800 if near_origin { mag + 7 } else { mag + 14 }
8801 }
8802 };
8803 let mut level = level;
8804 let mut sent = 0;
8805 loop {
8806 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8807 if rect_trace {
8808 eprintln!(
8809 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8810 dec.debug_state().0
8811 );
8812 }
8813 level += k;
8814 sent += BR_STEP;
8815 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8816 break;
8817 }
8818 }
8819 level
8820 } else {
8821 level
8822 };
8823 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8824 levels[idx] = level as u8;
8825 if level != 0 {
8826 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8827 nz_n += 1;
8828 }
8829 if rect_trace && scan_idx == eob - 1 {
8830 // the oracle's `tag=base_eob`: POST-br level, POST-br rng, with the
8831 // same `get_lower_levels_ctx_eob` ctx (the same `eob_coeff_ctx`).
8832 let ctx = eob_coeff_ctx(scan_idx, w * h);
8833 let (rng, _) = dec.debug_state();
8834 eprintln!(
8835 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={level} rng={rng}"
8836 );
8837 }
8838 }
8839 if rect_trace {
8840 let (rng, _) = dec.debug_state();
8841 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8842 }
8843 for &packed in nz_buf[..nz_n].iter().rev() {
8844 let pos = scan[(packed >> 4) as usize] as usize;
8845 let level = (packed & 15) as i32;
8846 let negative = if pos == 0 {
8847 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8848 } else {
8849 dec.literal(1) == 1
8850 };
8851 if rect_trace {
8852 let (rng, _) = dec.debug_state();
8853 eprintln!(
8854 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8855 u8::from(negative)
8856 );
8857 }
8858 let level = if level > MAX_BR_LEVEL {
8859 let g = read_golomb(dec)?;
8860 level + g as i32
8861 } else {
8862 level
8863 };
8864 if rect_trace {
8865 // lane-av1oddheightfork2: the twin of the square reader's
8866 // `coeff_step_post_golomb`. The oracle's `EC_COEFF_STEP
8867 // tag=post_golomb` (decodetxb.c, after read_golomb) fires for a RECT
8868 // unit exactly as it does for a square one, but this reader had no
8869 // rung for it, so every rect unit's ladder was one step short and
8870 // the pairing had to guess whether a golomb had been read. This
8871 // rung reads no bits: it prints the state after the read it labels.
8872 let (rng, _) = dec.debug_state();
8873 eprintln!(
8874 "EC_COEFF_STEP tag=post_golomb c={} pos={pos} level={level} rng={rng}",
8875 (packed >> 4)
8876 );
8877 }
8878 grid[pos] = if negative { -level } else { level };
8879 }
8880 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8881 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8882 // grids differ is a reader defect, one whose grids agree is a transform
8883 // defect.
8884 if crate::envflags::env_flag!("EC_DQCOEFF") {
8885 let nz: Vec<String> = grid
8886 .iter()
8887 .enumerate()
8888 .filter(|&(_, &v)| v != 0)
8889 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8890 .collect();
8891 eprintln!(
8892 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8893 nz.join(",")
8894 );
8895 }
8896 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8897 unit_iv_end(dec, plane, w, h, skip_ctx);
8898 Ok((Grid::Own(grid), tx_type))
8899}
8900
8901/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8902/// [`read_plane`] family already has.
8903///
8904/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8905/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8906/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8907/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8908/// enforces that for every strip that reads its chroma through it, but the rect
8909/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8910/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8911/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8912/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8913/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8914/// symbol -- and therefore every later pixel -- is decoded from the wrong
8915/// place, without ever tripping a refusal (the desynced values stay inside
8916/// every coded alphabet).
8917fn read_chroma_coeffs_rect(
8918 dec: &mut SymbolDecoder,
8919 coding: &mut TxbTables,
8920 scan: &[u16],
8921 w: usize,
8922 h: usize,
8923 skip_ctx: usize,
8924 sign_ctx: usize,
8925 default_tx_type: TxType,
8926 fctx: &crate::decode::FrameCtx,
8927 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8928 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8929 // V-plane read was indistinguishable from a luma one in the log).
8930 plane: usize,
8931) -> Result<(Grid, TxType)> {
8932 if mono(fctx) {
8933 return Ok((Grid::Zero(w * h), TxType::DctDct));
8934 }
8935 read_coeffs_rect(
8936 dec,
8937 coding,
8938 scan,
8939 w,
8940 h,
8941 skip_ctx,
8942 sign_ctx,
8943 default_tx_type,
8944 plane,
8945 )
8946}
8947
8948/// What one coded block leaves behind for the blocks that read it as a
8949/// neighbour: whether it coded anything at all, and the sign of its DC —
8950/// [`crate::tile`]'s own private `Neighbour`.
8951#[derive(Clone, Copy, Default)]
8952struct Neighbour {
8953 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8954 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8955 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8956 /// boolean (`level != 0`) is enough for every context this decoder read
8957 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8958 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8959 /// needs the actual magnitude tier of its above/left neighbours, not
8960 /// just whether they coded anything.
8961 level: u8,
8962 dc: Option<bool>,
8963}
8964
8965/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8966/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8967/// grid is dropped, never a panic. One `memset` per grid row instead of a
8968/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8969/// is contiguous, so this writes exactly the cells the cell loop did,
8970/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8971/// next row.
8972#[inline]
8973fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8974 let end = (start + n).min(dst.len());
8975 if start < end {
8976 dst[start..end].fill(v);
8977 }
8978}
8979
8980fn neighbour_state(grid: &[i32]) -> Neighbour {
8981 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8982 // sum has no early exit, so the 60% of units that code nothing used to
8983 // walk their whole grid here.
8984 if is_zero_grid(grid) {
8985 return Neighbour::default();
8986 }
8987 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8988 Neighbour {
8989 level: cul.min(7) as u8,
8990 dc: (grid[0] != 0).then_some(grid[0] < 0),
8991 }
8992}
8993
8994/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8995/// transform unit smaller than the block it sits in): `top`/`left` are the
8996/// above/left neighbours' magnitude tiers, each already clamped to 4.
8997pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8998 [1, 2, 2, 2, 3],
8999 [2, 4, 4, 4, 5],
9000 [2, 4, 4, 4, 5],
9001 [2, 4, 4, 4, 5],
9002 [3, 5, 5, 5, 6],
9003];
9004
9005/// The `skip` flag, its written-instrument bit, and the covering coded
9006/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
9007/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
9008/// nothing else, so a block's row is one fill instead of four, and the
9009/// deblocker's `pu_edge` reads origin and dims off one cache line.
9010#[derive(Clone, Copy)]
9011struct BlkCell {
9012 skip: bool,
9013 written: bool,
9014 org: [u16; 2],
9015 dim: [u8; 2],
9016}
9017
9018/// The neighbour state a block's contexts are read from — a duplicate of
9019/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
9020/// territory this round), kept at the same two granularities the real writer
9021/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
9022/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
9023/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
9024/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
9025/// chroma transform straddling the true, odd-sized frame edge see its
9026/// neighbour's state clamped at its own subsampled edge rather than luma's.
9027#[derive(Clone)]
9028struct Neighbours {
9029 above: Vec<[Neighbour; 3]>,
9030 left: Vec<[Neighbour; 3]>,
9031 above_mode: Vec<usize>,
9032 left_mode: Vec<usize>,
9033 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
9034 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
9035 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
9036 /// luma one -- the same block can (and often does) code a different
9037 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
9038 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
9039 /// within-block neighbour finer than this grid) is luma-only -- a known,
9040 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
9041 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
9042 above_uv_mode: Vec<usize>,
9043 left_uv_mode: Vec<usize>,
9044 above_side: Vec<usize>,
9045 left_side: Vec<usize>,
9046 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
9047 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
9048 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
9049 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
9050 /// array cannot tell the second leaf's partition symbol that the first
9051 /// one was coded at 8x8.
9052 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
9053 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
9054 above_side_mi: Vec<u8>,
9055 left_side_mi: Vec<u8>,
9056 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
9057 /// / row, with the mi position it was written at
9058 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
9059 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
9060 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
9061 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
9062 /// leaf whose neighbour is another split group needs that group's leaf 3
9063 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
9064 /// and read only by [`decode_leaf_split4`]; the position guard makes it
9065 /// fall back to the coarse slot whenever the real neighbour was a block
9066 /// of 8x8 or larger (whose one mode is correct for every row it spans).
9067 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
9068 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
9069 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
9070 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
9071 /// frame is 65536 px = 16384 mi).
9072 sub8_mode_col: Vec<(u16, u8)>,
9073 sub8_mode_row: Vec<(u16, u8)>,
9074 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
9075 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
9076 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
9077 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
9078 /// the leaf above writes the same row slot the block to the left owns.
9079 uv_mode_col: Vec<(u16, u8)>,
9080 uv_mode_row: Vec<(u16, u8)>,
9081 /// Every mi cell's own `uv_mode`, the mi grid libaom's
9082 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
9083 /// blockd.h). lane-t900 r12: the one-slot-per-column
9084 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
9085 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
9086 /// overwrote the row the pair's chroma-ref half then wanted to read --
9087 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
9088 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
9089 uv_mode_grid: Vec<u8>,
9090 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
9091 /// every other band here).
9092 uv_grid_cols: usize,
9093 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
9094 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
9095 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
9096 /// the `+ss_y` read compares written by the same block?", which is the
9097 /// whole question the `+ss_y` term turns on: the term is only observable
9098 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
9099 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
9100 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
9101 /// in this tile can never be mistaken for a written one.
9102 uv_owner: Vec<u32>,
9103 /// Whether the block above/left of this column/row was coded `skip` --
9104 /// an inter frame's own `skip` context (spec `SkipContext`), which the
9105 /// key-frame writer never tracks (its skip context is always zero); a
9106 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
9107 /// `left_skip`.
9108 above_skip: Vec<bool>,
9109 left_skip: Vec<bool>,
9110 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
9111 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
9112 /// pixels last written over each unit by `set_txfm_ctxs`/
9113 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
9114 /// symbol reads its context from (lane-txselect, spec 5.11.17).
9115 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
9116 /// array is exactly libaom's per-superblock-row reset, since each mi row
9117 /// is only ever visited inside one superblock row.
9118 above_txfm: Vec<u8>,
9119 left_txfm: Vec<u8>,
9120 /// Whether the block above/left of this column/row coded `skip_mode`
9121 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
9122 /// lane-av1comp round 14.
9123 above_skip_mode: Vec<bool>,
9124 left_skip_mode: Vec<bool>,
9125 /// Whether the block above/left was coded inter -- the `is_inter`
9126 /// context (spec `av1_get_intra_inter_context`), a duplicate of
9127 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
9128 above_inter: Vec<bool>,
9129 left_inter: Vec<bool>,
9130 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
9131 /// alphabet) the block above/left of this column/row coded, or `-1` for
9132 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
9133 /// functions (`mvstack::ref_ctx` family) need the real reference, not
9134 /// just "was it inter" (lane-av1refs: every inter block used to be
9135 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
9136 /// enough).
9137 above_ref: Vec<i8>,
9138 left_ref: Vec<i8>,
9139 /// The block above/left's *second* reference frame when it was coded
9140 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
9141 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
9142 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
9143 /// `i8`, once a compound `read_ref_frames` lands.
9144 /// lane-publish2 audit: the "always `None` today" note this doc used to
9145 /// carry is long stale -- compound blocks do occur, and
9146 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
9147 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
9148 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
9149 /// [`crate::mvstack::NeighbourRef`] construction (class
9150 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
9151 above_ref1: Vec<Option<i8>>,
9152 left_ref1: Vec<Option<i8>>,
9153 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
9154 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
9155 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
9156 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
9157 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
9158 above_comp_group_idx: Vec<u8>,
9159 left_comp_group_idx: Vec<u8>,
9160 above_compound_idx: Vec<u8>,
9161 left_compound_idx: Vec<u8>,
9162 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
9163 /// `3` = "no info": an intra neighbour or the frame's own border) of the
9164 /// block above/left of this column/row -- spec
9165 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
9166 above_filter: Vec<[u8; 2]>,
9167 left_filter: Vec<[u8; 2]>,
9168 mi_cols: usize,
9169 mi_rows: usize,
9170 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
9171 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
9172 /// 7.15) never filters an 8x8 luma block whose covering coded block read
9173 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
9174 /// grain [`Self::record_mi`] already writes at), read back at 8x8
9175 /// granularity by [`apply_cdef`] since `skip` is constant across every
9176 /// mi cell one coded block covers.
9177 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
9178 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
9179 /// the `skip` bit at this mi cell during this frame. A fresh
9180 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
9181 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
9182 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
9183 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
9184 /// unobservable from the pixels alone. Counted by
9185 /// [`cdef_unwritten_skip_units`].
9186 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
9187 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
9188 /// which re-enables the loop filter at a prediction boundary between two
9189 /// skipped inter blocks (lane-mergefix r4). Written by
9190 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
9191 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
9192 /// that cell -- the other half of `pu_edge`: libaom tests the edge
9193 /// coordinate against the block's size in the FILTERED plane's own
9194 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
9195 blk_grid: Vec<BlkCell>,
9196 skip_grid_cols_mi: usize,
9197 /// Per-4x4-mi `is_inter_block` of the coded block COVERING that cell --
9198 /// lane-av1txctxband. libaom's `get_tx_size_context`
9199 /// (`av1/common/pred_common.h:361-370`) gates its "an inter neighbour
9200 /// contributes its own BLOCK size" override on `xd->above_mbmi` /
9201 /// `xd->left_mbmi`, which `set_mi_offsets` takes as `xd->mi[-mi_stride]`
9202 /// / `xd->mi[-1]`: the block whose bottom (left) edge abuts THIS block's
9203 /// top (right) edge at THIS cell. `setup_mbs` (`decodeframe.c:355-361`)
9204 /// writes that pointer into EVERY mi cell a block covers, so libaom's
9205 /// granularity is the covering block PER CELL -- not one slot per column.
9206 /// [`Self::above_inter`]/[`Self::left_inter`] are per-COLUMN bands holding
9207 /// the LAST block written in that column, which is the covering block only
9208 /// for the block immediately below it: on a 4:4:4 lossy `--sb-size=128`
9209 /// cq-62 stream the 8x4 intra leaf at mi(57,52) read `above_inter` as
9210 /// `true` (stale, from an intrabc block earlier in column 52) with
9211 /// `above_side_mi` 4, took the override, and read `tx_size_cat0[1]` where
9212 /// libaom reads row 2 -- the `EC_SYMR` fork at read 32813.
9213 /// Written by exactly the three places that already write the bands:
9214 /// [`Self::record_inter_rect_mi`], `record_intrabc_mi_rect` and
9215 /// `fill_lf_grid_rect`'s intra-only clear.
9216 inter_grid: Vec<bool>,
9217 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
9218 /// never splits a coded block's transform below its own size (round 2:
9219 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
9220 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
9221 /// edge-length lookup (`apply_deblock`).
9222 tx_grid: Vec<u8>,
9223 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
9224 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
9225 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
9226 tx_h_grid: Vec<u8>,
9227 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
9228 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
9229 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
9230 /// does NOT follow luma's `tx_depth` split, so deriving it as
9231 /// `tx_grid / 2` invented chroma transform edges the deblocker then
9232 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
9233 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
9234 /// every caller routes through.
9235 uv_tx_grid: Vec<u8>,
9236 uv_tx_h_grid: Vec<u8>,
9237 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
9238 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
9239 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
9240 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
9241 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
9242 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
9243 /// reference onto `LAST_FRAME`'s own delta).
9244 ref_grid: Vec<i8>,
9245 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
9246 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
9247 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
9248 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
9249 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
9250 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
9251 /// to know which mode produced the value.
9252 delta_lf_grid: Vec<[i8; 4]>,
9253 /// The block above/left's own palette-Y size (0 = not a palette block)
9254 /// and its base colours -- `av1_get_palette_mode_ctx`/
9255 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
9256 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
9257 above_palette_size: Vec<u8>,
9258 left_palette_size: Vec<u8>,
9259 above_palette_colors: Vec<[u16; 8]>,
9260 left_palette_colors: Vec<[u16; 8]>,
9261 /// As the four fields above, for the neighbour's own chroma (U-channel
9262 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
9263 /// palette size/colours (lane-palette2 r1).
9264 above_palette_uv_size: Vec<u8>,
9265 left_palette_uv_size: Vec<u8>,
9266 above_palette_uv_colors: Vec<[u16; 8]>,
9267 left_palette_uv_colors: Vec<[u16; 8]>,
9268 /// This tile's own top-left corner, in 4x4 mode-info units (spec
9269 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
9270 /// neighbour" check compares against this instead of literal `0`, since a
9271 /// block at the tile's own top/left edge has no usable neighbour even
9272 /// though a decoded block sits there in the picture (spec `decode_tile`'s
9273 /// per-tile `clear_above_context`/`left_available`/`up_available`).
9274 /// `0` for a single-tile frame, matching every existing caller exactly.
9275 tile_row0_mi: usize,
9276 tile_col0_mi: usize,
9277}
9278
9279#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9280impl Neighbours {
9281 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
9282 /// true (unpadded) size in 4x4 mode-info units.
9283 fn new(
9284 cols: usize,
9285 rows: usize,
9286 mi_cols: usize,
9287 mi_rows: usize,
9288 fctx: &crate::decode::FrameCtx,
9289 ) -> Self {
9290 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
9291 // neighbour state over the whole 64-row extent, past the frame's last
9292 // mi row (mi_rows 198, block rows 192..208). libaom's own context
9293 // buffers are superblock-aligned for exactly that reason
9294 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
9295 // side arrays to a superblock multiple and leave those cells unread --
9296 // every availability check uses the true `mi_rows`/`mi_cols` below.
9297 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
9298 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
9299 Self {
9300 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
9301 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
9302 above_mode: vec![DC_PRED; cols],
9303 left_mode: vec![DC_PRED; rows],
9304 above_uv_mode: vec![DC_PRED; cols],
9305 left_uv_mode: vec![DC_PRED; rows],
9306 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
9307 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
9308 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
9309 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
9310 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
9311 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
9312 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
9313 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
9314 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
9315 uv_grid_cols: cols * (SUB / MI),
9316 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
9317 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
9318 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
9319 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
9320 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
9321 // 16x16 block beside it, which a SUB-grid slot cannot name
9322 // (class context-read-from-one-cell).
9323 above_skip: vec![false; cols * (SUB / MI)],
9324 left_skip: vec![false; rows * (SUB / MI)],
9325 above_skip_mode: vec![false; cols * (SUB / MI)],
9326 left_skip_mode: vec![false; rows * (SUB / MI)],
9327 above_inter: vec![false; cols * (SUB / MI)],
9328 left_inter: vec![false; rows * (SUB / MI)],
9329 above_ref: vec![-1; cols * (SUB / MI)],
9330 left_ref: vec![-1; rows * (SUB / MI)],
9331 above_ref1: vec![None; cols * (SUB / MI)],
9332 left_ref1: vec![None; rows * (SUB / MI)],
9333 above_comp_group_idx: vec![0; cols * (SUB / MI)],
9334 left_comp_group_idx: vec![0; rows * (SUB / MI)],
9335 above_compound_idx: vec![0; cols * (SUB / MI)],
9336 left_compound_idx: vec![0; rows * (SUB / MI)],
9337 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
9338 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
9339 mi_cols,
9340 mi_rows,
9341 blk_grid: vec![
9342 BlkCell {
9343 skip: false,
9344 written: false,
9345 org: [0; 2],
9346 dim: [1; 2]
9347 };
9348 cols * (SUB / MI) * rows * (SUB / MI)
9349 ],
9350 skip_grid_cols_mi: cols * (SUB / MI),
9351 inter_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
9352 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9353 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9354 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9355 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9356 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
9357 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
9358 above_palette_size: vec![0; cols * (SUB / MI)],
9359 left_palette_size: vec![0; rows * (SUB / MI)],
9360 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
9361 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
9362 above_palette_uv_size: vec![0; cols * (SUB / MI)],
9363 left_palette_uv_size: vec![0; rows * (SUB / MI)],
9364 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
9365 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
9366 tile_row0_mi: 0,
9367 tile_col0_mi: 0,
9368 }
9369 }
9370
9371 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
9372 /// tile's own column span (`col1_mi` exclusive), plus recording
9373 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
9374 /// availability check below. Left context resets every superblock row
9375 /// regardless of tile ([`Self::start_row`], already called once per SB
9376 /// row by every caller) so it needs no tile-specific reset here.
9377 fn start_tile(
9378 &mut self,
9379 row0_mi: usize,
9380 col0_mi: usize,
9381 col1_mi: usize,
9382 fctx: &crate::decode::FrameCtx,
9383 ) {
9384 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
9385 // are tile-relative, same as every other neighbour lookup here.
9386 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
9387 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
9388 // tile writes, so the `+ss_y` read's "different block?" probe never
9389 // compares against a cell a previous tile left behind.
9390 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
9391 self.tile_row0_mi = row0_mi;
9392 self.tile_col0_mi = col0_mi;
9393 let end = col1_mi.min(self.above.len());
9394 for i in col0_mi.min(end)..end {
9395 self.above[i] = Default::default();
9396 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
9397 }
9398 let (sc0, sc1) = (
9399 col0_mi / (SUB / MI),
9400 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
9401 );
9402 for i in sc0.min(sc1)..sc1 {
9403 self.above_mode[i] = DC_PRED;
9404 self.above_side[i] = NO_NEIGHBOUR_SIDE;
9405 }
9406 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
9407 // the tile's own mi column span directly.
9408 let mend = col1_mi.min(self.above_skip.len());
9409 for i in col0_mi.min(mend)..mend {
9410 self.above_skip[i] = false;
9411 self.above_skip_mode[i] = false;
9412 self.above_inter[i] = false;
9413 self.above_ref[i] = -1;
9414 self.above_ref1[i] = None;
9415 self.above_comp_group_idx[i] = 0;
9416 self.above_compound_idx[i] = 0;
9417 self.above_filter[i] = [3u8; 2];
9418 }
9419 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
9420 // stale `(row, mode)` from the tile to the LEFT names an mi row this
9421 // tile's first block would read as its own above neighbour.
9422 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
9423 for i in col0_mi.min(mcol_end)..mcol_end {
9424 self.sub8_mode_col[i] = (u16::MAX, 0);
9425 self.uv_mode_col[i] = (u16::MAX, 0);
9426 }
9427 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
9428 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
9429 // not zero) -- without it a second tile column reads the first one's
9430 // resolved transform sizes as its own above context.
9431 let tend = col1_mi.min(self.above_txfm.len());
9432 for i in col0_mi.min(tend)..tend {
9433 self.above_txfm[i] = TXFM_CTX_INIT;
9434 }
9435 }
9436
9437 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
9438 /// for a non-palette block, clearing any stale neighbour state) into every
9439 /// [`SUB`]-grid cell it covers on both the above and left edges --
9440 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
9441 /// call sites are all square blocks).
9442 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
9443 self.record_palette_y_rect(
9444 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9445 side,
9446 side,
9447 size,
9448 colors,
9449 );
9450 }
9451
9452 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
9453 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
9454 /// [`Self::record`]): a true rect strip's above/left neighbour spans
9455 /// differ.
9456 fn record_palette_y_rect(
9457 &mut self,
9458 mi: (usize, usize),
9459 w: usize,
9460 h: usize,
9461 size: usize,
9462 colors: [u16; 8],
9463 ) {
9464 let (r, c) = mi;
9465 if crate::envflags::env_flag!("EC_PALPUB") {
9466 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
9467 }
9468 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
9469 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
9470 // cell immediately left of the block, not its 16px [`SUB`] cell. The
9471 // old SUB grid let a 16x8 strip pair share one slot, so the second
9472 // strip of mi(0,8) read the FIRST strip's palette size and the colour
9473 // cache came out one entry short (class [[context-read-from-one-cell]]).
9474 for cell in 0..(w / MI).max(1) {
9475 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
9476 *e = size as u8;
9477 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
9478 // neighbour's colours only where its palette size > 0, so a
9479 // non-palette block need not stamp 16 bytes of zeroes here.
9480 if size > 0 {
9481 self.above_palette_colors[c + cell] = colors;
9482 }
9483 }
9484 }
9485 for cell in 0..(h / MI).max(1) {
9486 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
9487 *e = size as u8;
9488 if size > 0 {
9489 self.left_palette_colors[r + cell] = colors;
9490 }
9491 }
9492 }
9493 }
9494
9495 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
9496 /// neighbours that are themselves a palette-Y block, plus
9497 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
9498 /// cache (pred_common.c:73).
9499 ///
9500 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
9501 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
9502 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
9503 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
9504 /// the ctx too made every superblock in the frame's second SB row read
9505 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
9506 /// palette block decoded as "no palette" and the tile desynced from
9507 /// there (class [[cdf-row-held-constant]]).
9508 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
9509 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9510 }
9511
9512 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
9513 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
9514 /// drops the above neighbour on a 64-px superblock boundary
9515 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
9516 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
9517 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
9518 /// every strip in an SB's top cell row, which libaom does not do.
9519 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
9520 let (r, c) = mi;
9521 let above_ok = r % 16 != 0;
9522 // `xd->above_mbmi` exists for every row but the tile's own first.
9523 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
9524 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
9525 (
9526 usize::from(self.above_palette_size[c]),
9527 self.above_palette_colors[c],
9528 )
9529 } else {
9530 (0, [0u16; 8])
9531 };
9532 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
9533 // is NULL whenever the block sits at its TILE's own left column
9534 // (`left_available`), not the frame's -- without this guard a second
9535 // tile column reads the previous tile's palette colours into its cache
9536 // and its `palette_y_mode` ctx.
9537 let left_ok = c > self.tile_col0_mi;
9538 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
9539 (
9540 usize::from(self.left_palette_size[r]),
9541 self.left_palette_colors[r],
9542 )
9543 } else {
9544 (0, [0u16; 8])
9545 };
9546 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
9547 let mut cache = Vec::with_capacity(16);
9548 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9549 if cache.last() != Some(&v) {
9550 cache.push(v);
9551 }
9552 };
9553 let (mut ai, mut li) = (0usize, 0usize);
9554 while ai < above_n && li < left_n {
9555 let (va, vl) = (above_colors[ai], left_colors[li]);
9556 if vl < va {
9557 push_dedup(&mut cache, vl);
9558 li += 1;
9559 } else {
9560 push_dedup(&mut cache, va);
9561 ai += 1;
9562 if vl == va {
9563 li += 1;
9564 }
9565 }
9566 }
9567 while ai < above_n {
9568 push_dedup(&mut cache, above_colors[ai]);
9569 ai += 1;
9570 }
9571 while li < left_n {
9572 push_dedup(&mut cache, left_colors[li]);
9573 li += 1;
9574 }
9575 (ctx, cache)
9576 }
9577
9578 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
9579 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9580 /// same way (lane-palette2 r1).
9581 fn record_palette_uv(
9582 &mut self,
9583 at: (usize, usize),
9584 side: usize,
9585 size: usize,
9586 colors: [u16; 8],
9587 ) {
9588 self.record_palette_uv_rect(
9589 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9590 side,
9591 side,
9592 size,
9593 colors,
9594 );
9595 }
9596
9597 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9598 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9599 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9600 /// luma resolution regardless of which plane the recorded state is for).
9601 fn record_palette_uv_rect(
9602 &mut self,
9603 mi: (usize, usize),
9604 w: usize,
9605 h: usize,
9606 size: usize,
9607 colors: [u16; 8],
9608 ) {
9609 let (r, c) = mi;
9610 // mi granularity, see [`Self::record_palette_y_rect`].
9611 for cell in 0..(w / MI).max(1) {
9612 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9613 *e = size as u8;
9614 if size > 0 {
9615 self.above_palette_uv_colors[c + cell] = colors;
9616 }
9617 }
9618 }
9619 for cell in 0..(h / MI).max(1) {
9620 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9621 *e = size as u8;
9622 if size > 0 {
9623 self.left_palette_uv_colors[r + cell] = colors;
9624 }
9625 }
9626 }
9627 }
9628
9629 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9630 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9631 /// no neighbour lookup at all (it is this block's own just-decided Y
9632 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9633 /// so only the cache is wanted here.
9634 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9635 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9636 }
9637
9638 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9639 /// [`Self::palette_ctx_and_cache_mi`].
9640 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9641 let (r, c) = mi;
9642 let above_ok = r % 16 != 0;
9643 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9644 (
9645 usize::from(self.above_palette_uv_size[c]),
9646 self.above_palette_uv_colors[c],
9647 )
9648 } else {
9649 (0, [0u16; 8])
9650 };
9651 // Same tile-relative left availability as the luma cache above.
9652 let left_ok = c > self.tile_col0_mi;
9653 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9654 (
9655 usize::from(self.left_palette_uv_size[r]),
9656 self.left_palette_uv_colors[r],
9657 )
9658 } else {
9659 (0, [0u16; 8])
9660 };
9661 let mut cache = Vec::with_capacity(16);
9662 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9663 if cache.last() != Some(&v) {
9664 cache.push(v);
9665 }
9666 };
9667 let (mut ai, mut li) = (0usize, 0usize);
9668 while ai < above_n && li < left_n {
9669 let (va, vl) = (above_colors[ai], left_colors[li]);
9670 if vl < va {
9671 push_dedup(&mut cache, vl);
9672 li += 1;
9673 } else {
9674 push_dedup(&mut cache, va);
9675 ai += 1;
9676 if vl == va {
9677 li += 1;
9678 }
9679 }
9680 }
9681 while ai < above_n {
9682 push_dedup(&mut cache, above_colors[ai]);
9683 ai += 1;
9684 }
9685 while li < left_n {
9686 push_dedup(&mut cache, left_colors[li]);
9687 li += 1;
9688 }
9689 cache
9690 }
9691
9692 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9693 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9694 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9695 /// units as [`Self::fill_skip_grid`].
9696 fn fill_lf_grid(
9697 &mut self,
9698 at_mi: (usize, usize),
9699 side_mi: usize,
9700 tx_px: u8,
9701 ref_frame: i8,
9702 fctx: &crate::decode::FrameCtx,
9703 ) {
9704 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9705 }
9706
9707 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9708 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9709 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9710 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9711 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9712 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9713 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9714 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9715 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9716 /// block's published transform extent to its own size is exactly that
9717 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9718 /// that needs it is the 128 root, whose chroma extent is the one
9719 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9720 /// never suppressed (libaom's `is_inter_block` term), so this is called
9721 /// only from the skipped-inter branch.
9722 ///
9723 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
9724 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
9725 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
9726 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
9727 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
9728 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
9729 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
9730 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
9731 /// no format guard was possible inside this method until now.
9732 ///
9733 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
9734 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
9735 /// every edge it lets through then meets the SAME libaom rule applied at
9736 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
9737 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
9738 /// skip_at && skip_at`. Inside one skipped block both cells are that same
9739 /// block, so all four terms hold and the edge dies there too. The masking
9740 /// is TOTAL, not incidental: this method is only ever called for a block
9741 /// that is itself skipped, so no input exists on which one side of an
9742 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
9743 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
9744 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
9745 /// differ from each other in not one sample. The gate for this value is
9746 /// therefore a source scan, not a pixel gate --
9747 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
9748 fn suppress_internal_lf_edges(
9749 &mut self,
9750 at_mi: (usize, usize),
9751 w_mi: usize,
9752 h_mi: usize,
9753 fctx: &FrameCtx,
9754 ) {
9755 let (mi_r, mi_c) = at_mi;
9756 let (uv_w, uv_h) = (
9757 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
9758 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
9759 );
9760 for rr in 0..h_mi {
9761 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9762 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9763 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9764 }
9765 }
9766
9767 fn fill_lf_grid_rect(
9768 &mut self,
9769 at_mi: (usize, usize),
9770 w_mi: usize,
9771 h_mi: usize,
9772 tx_px: u8,
9773 tx_h_px: u8,
9774 ref_frame: i8,
9775 fctx: &crate::decode::FrameCtx,
9776 ) {
9777 self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, true, fctx)
9778 }
9779
9780 /// [`Self::fill_lf_grid_rect`] for a block whose transform tree ALREADY
9781 /// published its own `TXFM_CONTEXT` bands -- every body that ran
9782 /// [`read_block_tx_size_rect`] / [`read_block_tx_size`] / an inline
9783 /// var-tx tree of its own.
9784 ///
9785 /// libaom's `parse_decode_block` (`decodeframe.c:1227-1236`) is an
9786 /// EITHER/OR: the var-tx branch calls `read_tx_size_vartx`, which
9787 /// publishes through `txfm_partition_update` PER LEAF
9788 /// (`av1_common_int.h:1684-1695`) and never calls `set_txfm_ctxs`; the
9789 /// `else` branch calls `read_tx_size` + `set_txfm_ctxs` exactly once, over
9790 /// the whole block. So on the var-tx path there is NO whole-footprint
9791 /// publish to reproduce, and one written here is not merely redundant --
9792 /// it OVERWRITES the leaves' sizes with the block's own.
9793 ///
9794 /// lane-av1oddheightfork3, measured on the pinned
9795 /// `420_oddheight_320x236.obu` (then diverging: Y 234349 / U 56957 /
9796 /// V 52981, 0/16 frames; byte-exact since this lane): the INTRABC 8x16
9797 /// block at mi(44,58) split into two 8x8
9798 /// leaves, whose per-leaf writes put `8` into `left_txfm[44..48]`, and
9799 /// this publish then put the BLOCK's `16` back over those same four
9800 /// cells. The next block, the INTRABC 8x16 at mi(44,60), read
9801 /// `txfm_partition_context` with `left = 16` where libaom has `8` (the
9802 /// `above` operand agreed at 8 on both sides, printed by the oracle rung
9803 /// `EC_VARTXCTX` in `scripts/instrument-aom-oracle.sh`), took ctx 12
9804 /// against libaom's 13, decoded `is_split = 0` against libaom's `1`, and
9805 /// read no children against libaom's two -- the frame's first divergent
9806 /// read.
9807 fn fill_lf_grid_rect_after_vartx(
9808 &mut self,
9809 at_mi: (usize, usize),
9810 w_mi: usize,
9811 h_mi: usize,
9812 tx_px: u8,
9813 tx_h_px: u8,
9814 ref_frame: i8,
9815 fctx: &crate::decode::FrameCtx,
9816 ) {
9817 self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, false, fctx)
9818 }
9819
9820 #[allow(clippy::too_many_arguments)]
9821 fn fill_lf_grid_rect_inner(
9822 &mut self,
9823 at_mi: (usize, usize),
9824 w_mi: usize,
9825 h_mi: usize,
9826 tx_px: u8,
9827 tx_h_px: u8,
9828 ref_frame: i8,
9829 publish_txfm_bands: bool,
9830 fctx: &crate::decode::FrameCtx,
9831 ) {
9832 let (mi_r, mi_c) = at_mi;
9833 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9834 // half its luma one (min 4 px, the smallest transform), capped at
9835 // TX_32X32 -- independent of this block's luma `tx_depth`.
9836 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9837 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9838 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9839 eprintln!(
9840 "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}"
9841 );
9842 }
9843 crate::census::tx(tx_px, tx_h_px);
9844 let cur = fctx.current_delta_lf.with(|c| c.get());
9845 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9846 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9847 } else {
9848 [cur[0].clamp(-63, 63) as i8; 4]
9849 };
9850 for rr in 0..h_mi {
9851 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9852 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9853 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9854 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9855 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9856 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9857 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9858 }
9859 if publish_txfm_bands && fctx.intra_only.with(std::cell::Cell::get) {
9860 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9861 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9862 // xd)` for EVERY block, an intra-only frame's included, and
9863 // `get_tx_size_context` / `txfm_partition_context` read those two
9864 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9865 // over the same footprint, so the publish is this write: the
9866 // `skip && is_inter` term is 0 for every intra-only block that is
9867 // not an intrabc one, and the bodies that can code an intrabc
9868 // block publish their own (the term is then the BLOCK size, a value
9869 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9870 // Inter frames publish at their own sites and are excluded here
9871 // because their skipped-block term needs the block size too.
9872 txfm_partition_update_rect(
9873 self,
9874 at_mi,
9875 (tx_px as usize, tx_h_px as usize),
9876 (w_mi * MI, h_mi * MI),
9877 );
9878 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9879 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9880 // instead of its transform band. Every block stamps its own cells
9881 // here; the intrabc bodies re-stamp theirs `true` afterwards
9882 // (`record_intrabc_inter_bands`).
9883 for i in 0..w_mi {
9884 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9885 *cell = false;
9886 }
9887 }
9888 for i in 0..h_mi {
9889 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9890 *cell = false;
9891 }
9892 }
9893 // lane-av1txctxband: the same clear at libaom's own per-CELL
9894 // granularity. The band above clears one slot per column, so a
9895 // block that covered column 52 and a later block in the SAME
9896 // column but a different row leave the band describing whichever
9897 // wrote last; the grid clears exactly the cells this block owns.
9898 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, false);
9899 }
9900 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9901 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9902 // not just the intrabc ones. A later intrabc block's DV predictor is
9903 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9904 // `MB_MODE_INFO` for EVERY block and steps by
9905 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9906 // non-intrabc neighbour reads as uncovered and the scan advances it
9907 // by one cell instead of by its real width.
9908 fctx.intrabc_mi_grid.with(|g| {
9909 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9910 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9911 }
9912 });
9913 }
9914
9915 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9916 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9917 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9918 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9919 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9920 /// dims from the LEAF span and so invented chroma transform edges the
9921 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9922 /// are already correct from the block's own fill over the same span.
9923 fn fill_lf_grid_leaf_luma(
9924 &mut self,
9925 at_mi: (usize, usize),
9926 w_mi: usize,
9927 h_mi: usize,
9928 tx_px: u8,
9929 tx_h_px: u8,
9930 ) {
9931 let (mi_r, mi_c) = at_mi;
9932 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9933 eprintln!(
9934 "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}"
9935 );
9936 }
9937 for rr in 0..h_mi {
9938 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9939 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9940 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9941 }
9942 }
9943
9944 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9945 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9946 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9947 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9948 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9949 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9950 }
9951
9952 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9953 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9954 let (mi_r, mi_c) = at_mi;
9955 if skip && w_mi != h_mi {
9956 hit!(RECT_SKIP_BAND_HITS);
9957 }
9958 // lane-census: an INTRA frame's blocks never reach the inter
9959 // publisher, and this one is what every coded block writes.
9960 crate::census::block_intra_frame(w_mi, h_mi, skip);
9961 for rr in 0..h_mi {
9962 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9963 fill_span(
9964 &mut self.blk_grid,
9965 start,
9966 w_mi,
9967 BlkCell {
9968 skip,
9969 written: true,
9970 org: [mi_r as u16, mi_c as u16],
9971 dim: [w_mi as u8, h_mi as u8],
9972 },
9973 );
9974 }
9975 }
9976 /// Publishes one coded block's `is_inter_block` over EVERY 4x4 mi cell it
9977 /// covers -- lane-av1txctxband. libaom's `setup_mbs`
9978 /// (`decodeframe.c:355-361`) writes the block's own `MB_MODE_INFO`
9979 /// pointer into all of them, so `xd->mi[-xd->mi_stride]` /
9980 /// `xd->mi[-1]` name the block COVERING the cell, not "the last block
9981 /// written in this column" ([`Self::above_inter`] /
9982 /// [`Self::left_inter`], which is a per-column band and therefore stale
9983 /// for any block below the last writer in its column).
9984 /// Separate from [`Self::fill_skip_grid_rect`] because the two publishers
9985 /// run in BOTH orders at different call sites; both write disjoint fields,
9986 /// so the order does not matter. The value read is libaom's
9987 /// `is_inter_block` (`blockd.h:372-374`): an INTRABC block counts.
9988 fn mark_inter_grid_rect(
9989 &mut self,
9990 at_mi: (usize, usize),
9991 w_mi: usize,
9992 h_mi: usize,
9993 is_inter: bool,
9994 ) {
9995 for rr in 0..h_mi {
9996 let start = (at_mi.0 + rr) * self.skip_grid_cols_mi + at_mi.1;
9997 fill_span(&mut self.inter_grid, start, w_mi, is_inter);
9998 }
9999 }
10000
10001 /// `is_inter_block` of the coded block covering the mi cell
10002 /// `(mi_r, mi_c)`, or `false` for a cell no block has written yet (a tile
10003 /// border or a not-yet-decoded cell) -- lane-av1txctxband. The caller's
10004 /// `up_available` / `left_available` guard already excludes the borders.
10005 fn inter_at(&self, mi_r: usize, mi_c: usize) -> bool {
10006 self.inter_grid
10007 .get(mi_r * self.skip_grid_cols_mi + mi_c)
10008 .copied()
10009 .unwrap_or(false)
10010 }
10011
10012 /// The covering block's own `(block_size_wide, block_size_high)` in
10013 /// pixels at the mi cell `(mi_r, mi_c)`, from [`Self::blk_grid`]'s `dim`
10014 /// (the published mi extent) scaled by [`MI`] -- lane-av1txctxband. This
10015 /// is libaom's `block_size_wide[above_mbmi->bsize]` /
10016 /// `block_size_high[left_mbmi->bsize]`, read at the abutting CELL rather
10017 /// than from the per-column [`Self::above_side_mi`] /
10018 /// [`Self::left_side_mi`] band.
10019 fn blk_side_at(&self, mi_r: usize, mi_c: usize) -> (usize, usize) {
10020 self.blk_grid
10021 .get(mi_r * self.skip_grid_cols_mi + mi_c)
10022 .filter(|c| c.written)
10023 .map_or((0, 0), |c| (c.dim[0] as usize * MI, c.dim[1] as usize * MI))
10024 }
10025
10026 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
10027 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
10028 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
10029 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
10030 /// straddle the region with a mix of skip/non-skip blocks).
10031 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
10032 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
10033 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
10034 /// filtered edge's two sides are each exactly one coded block wide.
10035 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
10036 self.blk_grid
10037 .get(mi_r * self.skip_grid_cols_mi + mi_c)
10038 .is_some_and(|c| c.skip)
10039 }
10040
10041 /// The `skip_txfm` context of a block whose top-left mi cell is
10042 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
10043 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
10044 /// with an absent neighbour contributing 0. The mi grid is per tile, so
10045 /// row/column 0 is a tile edge and has no neighbour on that axis.
10046 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
10047 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
10048 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
10049 }
10050
10051 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
10052 (0..2).all(|rr| {
10053 (0..2).all(|cc| {
10054 self.blk_grid
10055 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
10056 .is_some_and(|c| c.skip)
10057 })
10058 })
10059 }
10060
10061 fn start_row(&mut self) {
10062 self.left.iter_mut().for_each(|l| *l = Default::default());
10063 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
10064 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
10065 self.left_side
10066 .iter_mut()
10067 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
10068 self.left_side_mi
10069 .iter_mut()
10070 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
10071 self.left_skip.iter_mut().for_each(|s| *s = false);
10072 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
10073 self.left_inter.iter_mut().for_each(|i| *i = false);
10074 self.left_ref.iter_mut().for_each(|r| *r = -1);
10075 self.left_ref1.iter_mut().for_each(|r| *r = None);
10076 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
10077 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
10078 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
10079 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
10080 // context (a tile/SB-row boundary has no left neighbour).
10081 self.sub8_mode_row
10082 .iter_mut()
10083 .for_each(|s| *s = (u16::MAX, 0));
10084 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
10085 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
10086 // are per-mi maps like every other one here, so they reset with the
10087 // row too -- the left guard above is what actually stops a cross-tile
10088 // read, this keeps a stale colour out of the arrays at all.
10089 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
10090 self.left_palette_colors
10091 .iter_mut()
10092 .for_each(|c| *c = [0u16; 8]);
10093 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
10094 self.left_palette_uv_colors
10095 .iter_mut()
10096 .for_each(|c| *c = [0u16; 8]);
10097 // lane-mergefix r2: `av1_zero_left_context` memsets
10098 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
10099 // every superblock row of every tile -- the var-tx left context does
10100 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
10101 // previous tile column's last block otherwise).
10102 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
10103 }
10104
10105 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
10106 /// block that reads it as a neighbour -- [`crate::tile`]'s
10107 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
10108 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
10109 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
10110 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
10111 /// the real value, not just `is_inter`).
10112 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10113 fn record_inter(
10114 &mut self,
10115 at: (usize, usize),
10116 side: usize,
10117 skip: bool,
10118 is_inter: bool,
10119 ref_frame: i8,
10120 filter: [u8; 2],
10121 skip_mode: bool,
10122 ) {
10123 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
10124 }
10125
10126 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
10127 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
10128 /// r1: a true rectangular strip's above-context span (its own width) and
10129 /// left-context span (its own height) differ, unlike every caller before
10130 /// this round (class neighbour-votes-all-its-fields).
10131 #[allow(clippy::too_many_arguments)]
10132 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10133 fn record_inter_rect(
10134 &mut self,
10135 at: (usize, usize),
10136 w_sub: usize,
10137 h_sub: usize,
10138 skip: bool,
10139 is_inter: bool,
10140 ref_frame: i8,
10141 filter: [u8; 2],
10142 skip_mode: bool,
10143 ) {
10144 let (r, c) = at;
10145 self.record_inter_rect_mi(
10146 (r * (SUB / MI), c * (SUB / MI)),
10147 w_sub / MI,
10148 h_sub / MI,
10149 skip,
10150 is_inter,
10151 ref_frame,
10152 filter,
10153 skip_mode,
10154 );
10155 }
10156
10157 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
10158 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
10159 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
10160 /// routes through the wrapper above.
10161 #[allow(clippy::too_many_arguments)]
10162 fn record_inter_rect_mi(
10163 &mut self,
10164 at_mi: (usize, usize),
10165 w_mi: usize,
10166 h_mi: usize,
10167 skip: bool,
10168 is_inter: bool,
10169 ref_frame: i8,
10170 filter: [u8; 2],
10171 skip_mode: bool,
10172 ) {
10173 let (r, c) = at_mi;
10174 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
10175 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
10176 // writes for a whole block class): an INTER block left the luma mode
10177 // map untouched, so a later intra block's `get_intra_edge_filter_type`
10178 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
10179 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
10180 // block in that pixel row -- the directional edge filter then ran at
10181 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
10182 // which for an inter block is an INTER mode (>= NEARESTMV) and is
10183 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
10184 // already stamped it).
10185 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
10186 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
10187 // uv map must read DC_PRED over an inter block's cells too.
10188 if is_inter {
10189 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
10190 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
10191 }
10192 // lane-av1txctxband: the per-CELL `is_inter_block` the per-column
10193 // `above_inter` band stands in for, at libaom's own granularity.
10194 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, is_inter);
10195 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
10196 self.above_skip[c..c + w_mi].fill(skip);
10197 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
10198 self.above_inter[c..c + w_mi].fill(is_inter);
10199 self.above_ref[c..c + w_mi].fill(ref_frame);
10200 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
10201 // this with the block's real second reference for a compound block,
10202 // called right after this one (lane-publish2 audit).
10203 self.above_ref1[c..c + w_mi].fill(None);
10204 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
10205 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
10206 // as `3`/`1` even though this block has no second reference.
10207 // `record_compound_ctx` overwrites this with the real bit for an
10208 // actual compound block's cells, called right after this one.
10209 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
10210 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
10211 self.above_filter[c..c + w_mi].fill(filter);
10212 self.left_skip[r..r + h_mi].fill(skip);
10213 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
10214 self.left_inter[r..r + h_mi].fill(is_inter);
10215 self.left_ref[r..r + h_mi].fill(ref_frame);
10216 self.left_ref1[r..r + h_mi].fill(None);
10217 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
10218 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
10219 self.left_filter[r..r + h_mi].fill(filter);
10220 }
10221
10222 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
10223 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
10224 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
10225 /// `get_comp_index_context`) -- called right after `record_inter` for
10226 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
10227 /// stamps `above_ref1`/`left_ref1` with the block's real second
10228 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
10229 /// this is the one caller that actually knows it) -- so the next block's
10230 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
10231 /// neighbour instead of `record_inter`'s single-ref default.
10232 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10233 fn record_compound_ctx(
10234 &mut self,
10235 at: (usize, usize),
10236 side: usize,
10237 ref1: i8,
10238 comp_group_idx: u8,
10239 compound_idx: u8,
10240 ) {
10241 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
10242 }
10243
10244 /// [`Self::record_compound_ctx`] with independent above/left extents,
10245 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
10246 #[allow(clippy::too_many_arguments)]
10247 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10248 fn record_compound_ctx_rect(
10249 &mut self,
10250 at: (usize, usize),
10251 w_sub: usize,
10252 h_sub: usize,
10253 ref1: i8,
10254 comp_group_idx: u8,
10255 compound_idx: u8,
10256 ) {
10257 let (r, c) = at;
10258 self.record_compound_ctx_rect_mi(
10259 (r * (SUB / MI), c * (SUB / MI)),
10260 w_sub / MI,
10261 h_sub / MI,
10262 ref1,
10263 comp_group_idx,
10264 compound_idx,
10265 );
10266 }
10267
10268 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
10269 /// [`Self::record_inter_rect_mi`]).
10270 fn record_compound_ctx_rect_mi(
10271 &mut self,
10272 at_mi: (usize, usize),
10273 w_mi: usize,
10274 h_mi: usize,
10275 ref1: i8,
10276 comp_group_idx: u8,
10277 compound_idx: u8,
10278 ) {
10279 let (r, c) = at_mi;
10280 crate::census::compound();
10281 for cell in 0..w_mi {
10282 self.above_ref1[c + cell] = Some(ref1);
10283 self.above_comp_group_idx[c + cell] = comp_group_idx;
10284 self.above_compound_idx[c + cell] = compound_idx;
10285 }
10286 for cell in 0..h_mi {
10287 self.left_ref1[r + cell] = Some(ref1);
10288 self.left_comp_group_idx[r + cell] = comp_group_idx;
10289 self.left_compound_idx[r + cell] = compound_idx;
10290 }
10291 }
10292
10293 /// The context of a block's partition symbol: delegates to the mi-precise
10294 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
10295 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
10296 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
10297 /// only touches the finer mi arrays -- leaves them stale for the *next*
10298 /// sibling's own partition symbol.
10299 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
10300 let (r, c) = at;
10301 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
10302 }
10303
10304 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
10305 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
10306 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
10307 /// than the enclosing 16x16 slot's stale, shared state.
10308 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
10309 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
10310 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
10311 }
10312
10313 /// The gathered coded/DC-sign state of the blocks above and to the left
10314 /// of a block `side` samples across, per plane.
10315 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
10316 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
10317 }
10318
10319 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
10320 /// units, for the same reason [`Self::record_mi`] does.
10321 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
10322 let side_mi = side / MI;
10323 // One pass over the cells accumulating all three planes, not one pass
10324 // per plane: the three planes of a cell live in the same
10325 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
10326 // cache lines three times (lane-publish). Clamp each edge to the true
10327 // frame extent: a block at the right/bottom edge may be padded beyond
10328 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
10329 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
10330 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
10331 let mut out = [(false, false, 0i32); 3];
10332 for cell in 0..above_mi {
10333 let above = &self.above[mi_c + cell];
10334 for (plane, o) in out.iter_mut().enumerate() {
10335 o.0 |= above[plane].level != 0;
10336 o.2 += dc_vote(above[plane].dc);
10337 }
10338 }
10339 for cell in 0..left_mi {
10340 let left = &self.left[mi_r + cell];
10341 for (plane, o) in out.iter_mut().enumerate() {
10342 o.1 |= left[plane].level != 0;
10343 o.2 += dc_vote(left[plane].dc);
10344 }
10345 }
10346 out
10347 }
10348
10349 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
10350 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
10351 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
10352 /// spans TWO luma mi columns. Both cells of a column carry the covering
10353 /// unit's whole-unit dc sign (the same value libaom stores), so the
10354 /// per-luma-mi sum counts each chroma column twice -- and
10355 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
10356 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
10357 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
10358 /// Sampling every second above cell counts each chroma column once,
10359 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
10360 /// its per-mi cells already line up one-to-one. The level booleans are
10361 /// ORs over duplicated cells, so the sampling cannot change them.
10362 fn around_mi_422_chroma(
10363 &self,
10364 (mi_r, mi_c): (usize, usize),
10365 w: usize,
10366 h: usize,
10367 ) -> [(bool, bool, i32); 3] {
10368 let (w_mi, h_mi) = (w / MI, h / MI);
10369 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10370 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10371 let mut out = [(false, false, 0i32); 3];
10372 for cell in (0..above_mi).step_by(2) {
10373 let above = &self.above[mi_c + cell];
10374 for (plane, o) in out.iter_mut().enumerate() {
10375 o.0 |= above[plane].level != 0;
10376 o.2 += dc_vote(above[plane].dc);
10377 }
10378 }
10379 for cell in 0..left_mi {
10380 let left = &self.left[mi_r + cell];
10381 for (plane, o) in out.iter_mut().enumerate() {
10382 o.1 |= left[plane].level != 0;
10383 o.2 += dc_vote(left[plane].dc);
10384 }
10385 }
10386 if crate::envflags::env_flag!("EC_DCDUMP") {
10387 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
10388 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
10389 // The above rows are the SAMPLED (every-second) cells.
10390 for (plane, o) in out.iter().enumerate() {
10391 let vote = o.2;
10392 let ab: Vec<String> = (0..above_mi)
10393 .step_by(2)
10394 .map(|k| {
10395 format!(
10396 "{:?}/{}",
10397 self.above[mi_c + k][plane].dc,
10398 self.above[mi_c + k][plane].level
10399 )
10400 })
10401 .collect();
10402 let lf: Vec<String> = (0..left_mi)
10403 .map(|k| {
10404 format!(
10405 "{:?}/{}",
10406 self.left[mi_r + k][plane].dc,
10407 self.left[mi_r + k][plane].level
10408 )
10409 })
10410 .collect();
10411 eprintln!(
10412 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
10413 ab.join(","),
10414 lf.join(",")
10415 );
10416 }
10417 }
10418 out
10419 }
10420
10421 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
10422 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
10423 /// extent pattern for a true rectangular strip's own coefficient context.
10424 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
10425 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
10426 }
10427
10428 /// [`Self::around_rect`] taking the block's position directly in 4x4
10429 /// mode-info units, mirroring [`Self::around_mi`].
10430 fn around_mi_rect(
10431 &self,
10432 (mi_r, mi_c): (usize, usize),
10433 w: usize,
10434 h: usize,
10435 ) -> [(bool, bool, i32); 3] {
10436 let (w_mi, h_mi) = (w / MI, h / MI);
10437 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10438 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10439 // [`Self::around_mi`]'s single pass, with the two extents split.
10440 let mut out = [(false, false, 0i32); 3];
10441 for cell in 0..above_mi {
10442 let above = &self.above[mi_c + cell];
10443 for (plane, o) in out.iter_mut().enumerate() {
10444 o.0 |= above[plane].level != 0;
10445 o.2 += dc_vote(above[plane].dc);
10446 }
10447 }
10448 for cell in 0..left_mi {
10449 let left = &self.left[mi_r + cell];
10450 for (plane, o) in out.iter_mut().enumerate() {
10451 o.1 |= left[plane].level != 0;
10452 o.2 += dc_vote(left[plane].dc);
10453 }
10454 }
10455 if crate::envflags::env_flag!("EC_DCDUMP") {
10456 for (plane, o) in out.iter().enumerate() {
10457 let vote = o.2;
10458 let ab: Vec<String> = (0..above_mi)
10459 .map(|k| {
10460 format!(
10461 "{:?}/{}",
10462 self.above[mi_c + k][plane].dc,
10463 self.above[mi_c + k][plane].level
10464 )
10465 })
10466 .collect();
10467 let lf: Vec<String> = (0..left_mi)
10468 .map(|k| {
10469 format!(
10470 "{:?}/{}",
10471 self.left[mi_r + k][plane].dc,
10472 self.left[mi_r + k][plane].level
10473 )
10474 })
10475 .collect();
10476 eprintln!(
10477 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
10478 ab.join(","),
10479 lf.join(",")
10480 );
10481 }
10482 }
10483 out
10484 }
10485
10486 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
10487 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
10488 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
10489 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
10490 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
10491 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
10492 /// is always 0, spec's `plane_bsize == tx_size` branch).
10493 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
10494 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
10495 }
10496
10497 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
10498 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
10499 /// context over `tx_size_wide` and the left one over `tx_size_high`.
10500 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
10501 let side_mi = w_mi;
10502 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10503 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10504 let mut top = 0u8;
10505 let mut left = 0u8;
10506 for cell in 0..above_mi {
10507 top |= self.above[mi_c + cell][0].level;
10508 }
10509 for cell in 0..left_mi {
10510 left |= self.left[mi_r + cell][0].level;
10511 }
10512 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
10513 if crate::envflags::env_flag!("EC_ECDUMP") {
10514 let ab: Vec<String> = (0..above_mi)
10515 .map(|k| self.above[mi_c + k][0].level.to_string())
10516 .collect();
10517 let lf: Vec<String> = (0..left_mi)
10518 .map(|k| self.left[mi_r + k][0].level.to_string())
10519 .collect();
10520 // lane-av1mix: the last few msac register states, so the
10521 // byte-position of the `all_zero` read can be matched against
10522 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
10523 // second run.
10524 let recent = crate::msac::symtrace::ecdump_recent(4)
10525 .iter()
10526 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
10527 .collect::<Vec<_>>()
10528 .join(" ");
10529 eprintln!(
10530 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
10531 ab.join(","),
10532 lf.join(","),
10533 recent
10534 );
10535 }
10536 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10537 eprintln!(
10538 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
10539 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
10540 );
10541 }
10542 ctx
10543 }
10544
10545 /// Writes one coded block into every cell it covers, on both grids: the
10546 /// mode/side arrays up to `side`'s own width, and the coefficient-context
10547 /// arrays up to the true frame edge — the units past it are left at their
10548 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
10549 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
10550 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
10551 /// not from this block's own side).
10552 fn record(
10553 &mut self,
10554 at: (usize, usize),
10555 side: usize,
10556 mode: usize,
10557 uv_mode: usize,
10558 grids: &[&[i32]; 3],
10559 ) {
10560 self.record_rect(at, side, side, mode, uv_mode, grids);
10561 }
10562
10563 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
10564 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
10565 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
10566 /// spec's per-edge partition-context rule, so a true rectangular block
10567 /// naturally wants two different values here rather than one.
10568 /// Writes this block's luma `mode` into the mi-granular
10569 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
10570 /// position a *later* neighbour would read it from: the block's LAST mi
10571 /// row for every column it spans (what the block below reads via
10572 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
10573 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
10574 /// read these back, and only when the recorded position is exactly their
10575 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
10576 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
10577 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
10578 let mode = mode as u8;
10579 for cell in 0..mi_w {
10580 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
10581 *slot = (last_r, mode);
10582 }
10583 }
10584 for cell in 0..mi_h {
10585 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
10586 *slot = (last_c, mode);
10587 }
10588 }
10589 }
10590
10591 /// The mi-exact above/left neighbour luma mode for a block whose top-left
10592 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
10593 /// mi position (then the coarse [`SUB`]-grid slot is right by
10594 /// construction). See [`Self::record_mode_mi`].
10595 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10596 match self.sub8_mode_col.get(mi_c) {
10597 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
10598 Some(usize::from(m))
10599 }
10600 _ => None,
10601 }
10602 }
10603
10604 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10605 match self.sub8_mode_row.get(mi_r) {
10606 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
10607 Some(usize::from(m))
10608 }
10609 _ => None,
10610 }
10611 }
10612
10613 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
10614 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
10615 fn record_uv_mode_mi(
10616 &mut self,
10617 mi_r: usize,
10618 mi_c: usize,
10619 mi_w: usize,
10620 mi_h: usize,
10621 uv_mode: usize,
10622 ) {
10623 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
10624 fill_span(
10625 &mut self.uv_mode_col,
10626 mi_c,
10627 mi_w,
10628 (last_r as u16, uv_mode as u8),
10629 );
10630 fill_span(
10631 &mut self.uv_mode_row,
10632 mi_r,
10633 mi_h,
10634 (last_c as u16, uv_mode as u8),
10635 );
10636 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
10637 // covers, so the chroma neighbour read below is a plain grid read.
10638 let stride = self.uv_grid_cols;
10639 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
10640 for row in mi_r..=last_r {
10641 fill_span(
10642 &mut self.uv_mode_grid,
10643 row * stride + mi_c,
10644 n,
10645 uv_mode as u8,
10646 );
10647 }
10648 // lane-av1leftwit: stamp the writing block's own mi over its extent,
10649 // the same cells and the same clipping as `uv_mode_grid` above.
10650 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
10651 for row in mi_r..=last_r {
10652 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
10653 }
10654 if crate::envflags::env_flag!("EC_LEFTSSY") {
10655 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
10656 }
10657 }
10658
10659 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
10660 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
10661 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
10662 /// block has recorded the exact neighbouring mi.
10663 fn smooth_uv_neighbour(
10664 &self,
10665 mi_r: usize,
10666 mi_c: usize,
10667 r: usize,
10668 c: usize,
10669 fctx: &crate::decode::FrameCtx,
10670 ) -> bool {
10671 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
10672 // REFERENCE block, not off the mi that carries the chroma syntax.
10673 // `set_mi_row_col` (`blockd.h`) takes
10674 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
10675 // only then `chroma_above_mbmi = base_mi[-stride]` /
10676 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
10677 // the ODD mi, so without the snap we looked one mi row/column too far
10678 // down/right -- the mi-exact slot never matched and the coarse
10679 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
10680 // 8x4 at (688, 100) = mi (51, 344): libaom's
10681 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
10682 // `UV_SMOOTH_PRED`), ours was 0, which flips
10683 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
10684 // false for type 1, TRUE for type 0) and upsampled an edge libaom
10685 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
10686 // predicting from it (class `context-read-from-one-cell`).
10687 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
10688 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
10689 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
10690 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
10691 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
10692 let snap_y = (1usize << ss_y(fctx)) - 1;
10693 let snap_x = (1usize << ss_x(fctx)) - 1;
10694 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
10695 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
10696 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
10697 // the two chroma-reference offsets on top of it -- see its own comment
10698 // for which axis each one moves.
10699 self.smooth_uv_neighbour_unsnapped(
10700 mi_r & !snap_y,
10701 mi_c & !snap_x,
10702 r,
10703 c,
10704 ss_x(fctx),
10705 ss_y(fctx),
10706 true,
10707 )
10708 }
10709
10710 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
10711 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
10712 /// counter wants this: it measures how often the snap CHANGES the answer,
10713 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
10714 /// decode path uses the snapping form.
10715 /// `decode_path` is `true` only for the snapping form every decode call
10716 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
10717 /// `+ss_y` counters measure a read that actually filters a chroma edge and
10718 /// not the counter-only one.
10719 ///
10720 /// lane-av1leftwit: the mirror's justification used to be "no committed
10721 /// fixture reaches the shape on the decode path", and that was false --
10722 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
10723 /// counter-only mirror at an ODD mi row is still not a decode-path read,
10724 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
10725 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
10726 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
10727 fn smooth_uv_neighbour_unsnapped(
10728 &self,
10729 mi_r: usize,
10730 mi_c: usize,
10731 r: usize,
10732 c: usize,
10733 ss_x: usize,
10734 ss_y: usize,
10735 decode_path: bool,
10736 ) -> bool {
10737 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10738 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10739 // array that `start_tile` does not clear, so a block on a tile's first
10740 // mi row used to read the uv_mode of the block above it in the tile
10741 // ABOVE and filter its chroma edge at that neighbour's strength
10742 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10743 // at chroma (120, 32), the top-right tile's first block).
10744 let have_above = mi_r > self.tile_row0_mi;
10745 let have_left = mi_c > self.tile_col0_mi;
10746 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10747 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10748 {
10749 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10750 }
10751 // The mi grid is libaom's own read; the two maps below stay as the
10752 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10753 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10754 (col < self.uv_grid_cols)
10755 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10756 .flatten()
10757 .filter(|&m| m != u8::MAX)
10758 .map(usize::from)
10759 };
10760 // libaom's two chroma-reference mi, from `set_mi_row_col`
10761 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10762 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10763 // snap -- i.e. already libaom's `base_mi`:
10764 //
10765 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10766 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10767 //
10768 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10769 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10770 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10771 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10772 // boolean it feeds is simply not exercised differently by that stream
10773 // at its blocks. One chroma column spans two luma mi columns, so the
10774 // chroma edge reaches into the right-hand luma block, and that is where
10775 // its reference lives.
10776 //
10777 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10778 // last open item lane-av1422warp carried. libaom puts the left
10779 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10780 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10781 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10782 // read (the above) and regressed the byte-exact 4:2:0 control, which
10783 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10784 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10785 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10786 // measured. Measured over all 48 committed fixtures that decode
10787 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10788 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10789 // put a 1-mi-tall left neighbour in front of a decode-path read at
10790 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10791 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10792 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10793 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10794 // changing is what is still unwitnessed.
10795 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10796 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10797 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10798 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10799 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10800 // row at every subsampling. The term is only observable when the two
10801 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10802 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10803 // and only libaom's is the chroma reference. Three counters measure
10804 // that, and the third is the one the other two need: a read can only
10805 // differ if the two cells are written by DIFFERENT blocks, which
10806 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10807 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10808 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10809 // reads > 0 is the term being unobservable on real material, not
10810 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10811 // whether the mode value, and the boolean this feeds
10812 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10813 // edge filter), actually moved.
10814 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10815 let read_left = |row: usize| -> usize {
10816 match self.uv_mode_row.get(row) {
10817 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10818 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10819 _ if have_left => self.left_uv_mode[r],
10820 _ => DC_PRED,
10821 }
10822 };
10823 let above = match self.uv_mode_col.get(above_mi.1) {
10824 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10825 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10826 _ if have_above => self.above_uv_mode[c],
10827 _ => DC_PRED,
10828 };
10829 let left = read_left(left_mi.0);
10830 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10831 // how many chroma edge-filter-type reads took this path at all, so a
10832 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10833 // term did not change the answer". The two DIFF buckets compare
10834 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10835 // every committed fixture and every one of the ~1000 encodes swept in
10836 // `lanes/av1leftref.report.md`, which is what makes the read change a
10837 // proven no-op on today's material rather than an unmeasured guess.
10838 if decode_path && have_left && ss_y > 0 {
10839 hit!(UV_LEFT_SS_Y_READS);
10840 // The pre-lane read, kept as the counter's own-row arm: it is what
10841 // this decoder answered before the `+ss_y` term landed, and
10842 // comparing against it is what proves the term is load-bearing.
10843 let own_row = read_left(mi_r);
10844 if own_row != left {
10845 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10846 }
10847 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10848 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10849 }
10850 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10851 // cells are one left mi column apart, so they are two different
10852 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10853 let col = left_mi.1;
10854 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10855 let own = (col < self.uv_grid_cols)
10856 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10857 .flatten()
10858 .filter(|o| o & 0xff00_0000 == epoch)
10859 .unwrap_or(0);
10860 let down = self
10861 .uv_owner
10862 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10863 .copied()
10864 .filter(|o| o & 0xff00_0000 == epoch)
10865 .unwrap_or(0);
10866 if own != 0 && down != 0 && own != down {
10867 hit!(UV_LEFT_1MI_SPLIT_HITS);
10868 if crate::envflags::env_flag!("EC_LEFTSSY") {
10869 eprintln!(
10870 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10871 owners=({},{})->({},{}) modes={own_row}/{left}",
10872 epoch >> 24,
10873 own >> 12 & 0xfff,
10874 own & 0xfff,
10875 down >> 12 & 0xfff,
10876 down & 0xfff,
10877 );
10878 }
10879 }
10880 }
10881 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10882 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10883 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10884 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10885 }) {
10886 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10887 }
10888 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10889 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10890 // have been filtered at the wrong strength by the coarse map alone.
10891 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10892 hit!(UV_MODE_MI_OVERRIDE_HITS);
10893 }
10894 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10895 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10896 {
10897 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10898 }
10899 is_smooth_mode(above) || is_smooth_mode(left)
10900 }
10901
10902 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10903 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10904 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10905 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10906 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10907 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10908 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10909 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10910 /// a different CDF for the same mode value).
10911 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10912 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10913 /// only when `up_available` and `left_mbmi` only when `left_available`;
10914 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10915 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10916 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10917 /// strip's mode as its "left neighbour" (measured on the band fixture at
10918 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10919 fn modes_above_left_mi(
10920 &self,
10921 mi_r: usize,
10922 mi_c: usize,
10923 fallback: (usize, usize),
10924 ) -> (usize, usize) {
10925 let above = if mi_r > self.tile_row0_mi {
10926 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10927 } else {
10928 DC_PRED
10929 };
10930 let left = if mi_c > self.tile_col0_mi {
10931 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10932 } else {
10933 DC_PRED
10934 };
10935 (above, left)
10936 }
10937
10938 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10939 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10940 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10941 /// per superblock row and never per tile, so the first block column of
10942 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10943 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10944 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10945 /// `up_available`/`left_available` and uses DC_PRED otherwise
10946 /// ([`Self::modes_above_left_mi`]).
10947 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10948 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10949 let (above, left) =
10950 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10951 if above != self.above_mode[c] || left != self.left_mode[r] {
10952 hit!(MODE_MI_OVERRIDE_HITS);
10953 }
10954 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10955 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10956 {
10957 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10958 }
10959 // A neighbour the coarse band offered where the tile edge makes it
10960 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10961 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10962 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10963 {
10964 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10965 }
10966 (above, left)
10967 }
10968
10969 fn record_rect(
10970 &mut self,
10971 at: (usize, usize),
10972 w: usize,
10973 h: usize,
10974 mode: usize,
10975 uv_mode: usize,
10976 grids: &[&[i32]; 3],
10977 ) {
10978 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10979 }
10980
10981 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10982 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10983 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10984 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10985 /// the [`SUB`]-unit path does).
10986 fn record_rect_mi(
10987 &mut self,
10988 at_mi: (usize, usize),
10989 w: usize,
10990 h: usize,
10991 mode: usize,
10992 uv_mode: usize,
10993 grids: &[&[i32]; 3],
10994 ) {
10995 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10996 self.record_mi_rect(at_mi, w, h, grids);
10997 }
10998
10999 /// [`Self::record_rect_mi`]'s mode and transform-size half, without the
11000 /// coefficient-context stamp.
11001 fn record_rect_mi_modes(
11002 &mut self,
11003 at_mi: (usize, usize),
11004 w: usize,
11005 h: usize,
11006 mode: usize,
11007 uv_mode: usize,
11008 ) {
11009 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
11010 // lane-inter4 r2: a strip whose own footprint runs past the frame's
11011 // last 16-px column/row stamps only the cells that exist (libaom's
11012 // arrays are padded past the frame and those cells are never read).
11013 for cell in 0..w / SUB {
11014 if c + cell >= self.above_mode.len() {
11015 break;
11016 }
11017 self.above_mode[c + cell] = mode;
11018 self.above_uv_mode[c + cell] = uv_mode;
11019 self.above_side[c + cell] = w;
11020 }
11021 for cell in 0..h / SUB {
11022 if r + cell >= self.left_mode.len() {
11023 break;
11024 }
11025 self.left_mode[r + cell] = mode;
11026 self.left_uv_mode[r + cell] = uv_mode;
11027 self.left_side[r + cell] = h;
11028 }
11029 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
11030 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
11031 }
11032
11033 /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv
11034 /// plane block is SEVERAL transform units, each of which stamped its own
11035 /// span through [`Self::record_mi_chroma`]. Writing one whole-block state
11036 /// over them is the `override-slot-on-one-arm` class: libaom keeps the
11037 /// per-unit above/left contexts distinct, and the next block's first
11038 /// unit reads them. The luma plane has one unit here, so it is stamped
11039 /// exactly as the whole-block record stamps it.
11040 fn record_rect_mi_luma_only(
11041 &mut self,
11042 at_mi: (usize, usize),
11043 w: usize,
11044 h: usize,
11045 mode: usize,
11046 uv_mode: usize,
11047 luma_grid: &[i32],
11048 ) {
11049 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
11050 fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8);
11051 fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8);
11052 self.record_mi_luma_rect(at_mi, w, h, luma_grid);
11053 }
11054
11055 /// The coefficient-context half of [`Self::record`], taking the block's
11056 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
11057 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
11058 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
11059 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
11060 self.record_mi_rect(at_mi, side, side, grids);
11061 }
11062
11063 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
11064 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
11065 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
11066 let (mi_r, mi_c) = at_mi;
11067 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
11068 let (w_mi, h_mi) = (w / MI, h / MI);
11069 if crate::envflags::env_flag!("EC_ECPUB") {
11070 eprintln!(
11071 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
11072 states[0].level
11073 );
11074 }
11075 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
11076 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
11077 // A chroma 4x4 unit straddling the true luma edge is still whole in
11078 // chroma's own halved grid, so libaom rounds the luma bound up to the
11079 // plane's own 4x4 unit before clamping a subsampled plane
11080 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
11081 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11082 let bound_h = [
11083 self.mi_rows,
11084 round_up_even(self.mi_rows),
11085 round_up_even(self.mi_rows),
11086 ];
11087 let bound_w = [
11088 self.mi_cols,
11089 round_up_even(self.mi_cols),
11090 round_up_even(self.mi_cols),
11091 ];
11092 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
11093 // past the padded side arrays (mi_rows 198, block rows 192..208);
11094 // libaom's own arrays are superblock-sized, so those cells simply
11095 // have no reader -- [`fill_span`] drops them, as the `break` did.
11096 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
11097 // predicate is three contiguous runs: all planes, chroma only, none
11098 // (lane-mi).
11099 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
11100 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
11101 let uv_only = [Neighbour::default(), states[1], states[2]];
11102 fill_span(&mut self.left, mi_r, luma_h, states);
11103 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
11104 fill_span(
11105 &mut self.left,
11106 mi_r + chroma_h,
11107 h_mi - chroma_h,
11108 [Neighbour::default(); 3],
11109 );
11110 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
11111 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
11112 let uv_only_w = [Neighbour::default(), states[1], states[2]];
11113 fill_span(&mut self.above, mi_c, luma_w, states);
11114 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
11115 fill_span(
11116 &mut self.above,
11117 mi_c + chroma_w,
11118 w_mi - chroma_w,
11119 [Neighbour::default(); 3],
11120 );
11121 }
11122
11123 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
11124 /// inside a coded block whose luma transform is smaller than its own
11125 /// side (`TxMode::Select`): the real per-transform-unit coefficient
11126 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
11127 /// coarse per-block `tx_grid`/`fill_lf_grid` state
11128 /// [`Self::record_split_luma`] still writes once for the whole block.
11129 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
11130 /// the caller's own [`Self::record_split_luma`] call sets those once,
11131 /// at the block's own true side, not this TU's.
11132 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
11133 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
11134 }
11135
11136 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
11137 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
11138 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
11139 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
11140 /// coefficient-context arrays are indexed by luma mi, the convention
11141 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
11142 /// clamp included.
11143 fn record_mi_chroma(
11144 &mut self,
11145 (mi_r, mi_c): (usize, usize),
11146 w_px: usize,
11147 h_px: usize,
11148 plane: usize,
11149 grid: &[i32],
11150 ) {
11151 // lane-arfchroma: a 4x4 CHROMA transform unit is `4 << ss` luma px per
11152 // axis, i.e. `1 << ss` LUMA mi, so its context cell is the step-aligned
11153 // group of mi a block may only PART of. A block starting mid-cell (a
11154 // 16x4 / 4x16 1:4 strip, whose mi row/col is ODD at 4:2:0) stamped its
11155 // own origin plus the mi row/col BELOW it, so the strip above a block
11156 // handed that block a "left neighbour" libaom never had -- its chroma
11157 // cell is one row up -- and the block's chroma `txb_skip` context came
11158 // out one base high (ours 2, libaom 7+1 = 8, at 320x240 frame 2 block
11159 // mi (4,0) of the 4:2:0 lossless alt-ref witness). Align the origin
11160 // DOWN to the cell: that is where libaom's per-plane 2-D
11161 // `left/above_context_map` cell lives, indexed in the PLANE's own 4x4
11162 // units rather than in luma mi.
11163 let (step_x, step_y) = (w_px / MI, h_px / MI);
11164 // the flags read the CALLER's origin, before the shadowing align below
11165 let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0);
11166 if row_mid || col_mid {
11167 CHROMA_MIDCELL_PUB_HITS.with(|c| {
11168 let mut v = c.get();
11169 v[0] += usize::from(row_mid);
11170 v[1] += usize::from(col_mid);
11171 v[2] += usize::from(row_mid && col_mid);
11172 c.set(v);
11173 });
11174 }
11175 let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1));
11176 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11177 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
11178 let state = neighbour_state(grid);
11179 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
11180 eprintln!(
11181 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
11182 state.level,
11183 state.dc.map_or(-1, |s| i32::from(s))
11184 );
11185 }
11186 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
11187 self.left[mi_r + cell][plane] = state;
11188 }
11189 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
11190 self.above[mi_c + cell][plane] = state;
11191 }
11192 }
11193
11194 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
11195 /// r1): the above context spans the unit's width, the left context its
11196 /// height, which for a square unit is the same loop it always was.
11197 fn record_mi_luma_rect(
11198 &mut self,
11199 (mi_r, mi_c): (usize, usize),
11200 w_px: usize,
11201 h_px: usize,
11202 grid: &[i32],
11203 ) {
11204 let state = neighbour_state(grid);
11205 if crate::envflags::env_flag!("EC_ECPUB") {
11206 eprintln!(
11207 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
11208 state.level
11209 );
11210 }
11211 for cell in 0..h_px / MI {
11212 if mi_r + cell < self.mi_rows {
11213 self.left[mi_r + cell][0] = state;
11214 }
11215 }
11216 for cell in 0..w_px / MI {
11217 if mi_c + cell < self.mi_cols {
11218 self.above[mi_c + cell][0] = state;
11219 }
11220 }
11221 }
11222
11223 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
11224 /// block whose luma was decoded as several transform units through
11225 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
11226 /// whole-block luma write -- everything [`Self::record`] does except
11227 /// plane 0, which is already correct per-TU by the time this runs.
11228 fn record_split_luma(
11229 &mut self,
11230 at: (usize, usize),
11231 side: usize,
11232 mode: usize,
11233 uv_mode: usize,
11234 chroma_grids: [&[i32]; 2],
11235 ) {
11236 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
11237 }
11238
11239 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
11240 /// extents in pixels (lane-rectsplit r1), the same relationship
11241 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
11242 /// luma transform split into several square units needs exactly this
11243 /// bookkeeping, at its own true rectangular extents.
11244 fn record_split_luma_rect(
11245 &mut self,
11246 at: (usize, usize),
11247 w: usize,
11248 h: usize,
11249 mode: usize,
11250 uv_mode: usize,
11251 chroma_grids: [&[i32]; 2],
11252 ) {
11253 let (r, c) = at;
11254 self.record_split_luma_rect_mi(
11255 (r * (SUB / MI), c * (SUB / MI)),
11256 w,
11257 h,
11258 mode,
11259 uv_mode,
11260 chroma_grids,
11261 );
11262 }
11263
11264 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
11265 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
11266 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
11267 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
11268 /// convention [`decode_block_rect4`] already established for 1:4 strips.
11269 fn record_split_luma_rect_mi(
11270 &mut self,
11271 at_mi: (usize, usize),
11272 w: usize,
11273 h: usize,
11274 mode: usize,
11275 uv_mode: usize,
11276 chroma_grids: [&[i32]; 2],
11277 ) {
11278 self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode);
11279 let (mi_r, _) = at_mi;
11280 let (w_mi, h_mi) = (w / MI, h / MI);
11281 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11282 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
11283 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
11284 let plane = plane_idx + 1;
11285 let state = neighbour_state(grid);
11286 for cell in 0..h_mi {
11287 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
11288 self.left[mi_r + cell][plane] = state;
11289 }
11290 }
11291 for cell in 0..w_mi {
11292 if cell < w_mi.min(bound_w.saturating_sub(at_mi.1)) {
11293 self.above[at_mi.1 + cell][plane] = state;
11294 }
11295 }
11296 }
11297 }
11298
11299 /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half,
11300 /// without the per-plane coefficient stamp -- see
11301 /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block
11302 /// must not take the whole-block stamp.
11303 fn record_split_luma_rect_mi_modes(
11304 &mut self,
11305 at_mi: (usize, usize),
11306 w: usize,
11307 h: usize,
11308 mode: usize,
11309 uv_mode: usize,
11310 ) {
11311 let (mi_r, mi_c) = at_mi;
11312 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11313 for cell in 0..w.div_ceil(SUB) {
11314 if c + cell >= self.above_mode.len() {
11315 break;
11316 }
11317 self.above_mode[c + cell] = mode;
11318 self.above_uv_mode[c + cell] = uv_mode;
11319 self.above_side[c + cell] = w;
11320 }
11321 for cell in 0..h.div_ceil(SUB) {
11322 if r + cell >= self.left_mode.len() {
11323 break;
11324 }
11325 self.left_mode[r + cell] = mode;
11326 self.left_uv_mode[r + cell] = uv_mode;
11327 self.left_side[r + cell] = h;
11328 }
11329
11330 let (w_mi, h_mi) = (w / MI, h / MI);
11331 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
11332 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
11333 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
11334 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
11335 }
11336}
11337
11338/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
11339/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
11340/// exactly — including its skip context, which the real key-frame writer
11341/// always writes at a fixed context of zero (it never tracks a neighbour-based
11342/// one for intra blocks; that is the inter-frame writer's rule instead).
11343/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
11344/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
11345/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
11346/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
11347/// plain DC chroma.
11348/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
11349/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
11350/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
11351/// instead (the defect commit 1a89ed9 fixed at the square sites).
11352pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
11353 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
11354 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
11355}
11356
11357/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
11358/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
11359/// bound (spec `filter_intra_mode_info` never reads a symbol there).
11360pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
11361 match side {
11362 4 => Some(0),
11363 8 => Some(1),
11364 16 => Some(2),
11365 32 => Some(3),
11366 _ => None,
11367 }
11368}
11369
11370/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
11371/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
11372/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
11373/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
11374fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
11375 match (bw, bh) {
11376 (32, 16) => Some(4),
11377 (16, 32) => Some(5),
11378 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
11379 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
11380 // here dropped that symbol on every DC_PRED strip of that size and
11381 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
11382 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
11383 (16, 8) => Some(6),
11384 (8, 16) => Some(7),
11385 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
11386 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
11387 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
11388 (4, 8) => Some(8),
11389 (8, 4) => Some(9),
11390 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
11391 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
11392 // `use_filter_intra` symbol on those strips although aomenc writes
11393 // one for every DC_PRED block of that shape with
11394 // `--enable-filter-intra=1` (its default), silently desyncing the
11395 // tile (class symbol-consumption-gap).
11396 (32, 8) => Some(10),
11397 (8, 32) => Some(11),
11398 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
11399 // strips), rows 17/16 of `default_filter_intra_cdfs`.
11400 (16, 4) => Some(12),
11401 (4, 16) => Some(13),
11402 _ if bw == bh => filter_intra_size_class(bw),
11403 _ => None,
11404 }
11405}
11406
11407/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
11408/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
11409/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
11410/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
11411/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
11412pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
11413 palette_bsize_ctx_wh(side, side)
11414}
11415
11416/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
11417/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
11418/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
11419/// for ANY bsize, not just the square ones a hand-picked table happened to
11420/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
11421/// row breaks the moment its indexing field moves off the diagonal, and a
11422/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
11423/// block dimension is a power of two, so `bw*bh` always is too and
11424/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
11425/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
11426fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
11427 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
11428 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
11429 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
11430 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
11431 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
11432 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
11433 if bw > 64 || bh > 64 || bw * bh < 64 {
11434 return None;
11435 }
11436 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
11437}
11438
11439/// A just-decoded palette-Y block's own size, base colours (only the first
11440/// `size` entries are real), and per-pixel colour-index map (`side*side`,
11441/// row-major, each entry `< size`).
11442struct PaletteY {
11443 size: usize,
11444 colors: [u16; 8],
11445 map: Vec<u8>,
11446}
11447
11448/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
11449/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
11450/// shared between U and V, both co-located after 4:2:0 subsampling) plus
11451/// each plane's own base colours.
11452struct PaletteUv {
11453 size: usize,
11454 u_colors: [u16; 8],
11455 v_colors: [u16; 8],
11456 map: Vec<u8>,
11457}
11458
11459/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
11460/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
11461/// `get_unsigned_bits`, which is the same formula): smallest `n` with
11462/// `2^n >= x`, `0` for `x <= 1`.
11463pub(crate) fn ceil_log2(x: u32) -> u32 {
11464 if x < 2 {
11465 0
11466 } else {
11467 32 - (x - 1).leading_zeros()
11468 }
11469}
11470
11471/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
11472/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
11473fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
11474 let l = ceil_log2(n as u32);
11475 let m = (1usize << l) - n;
11476 let v = dec.literal(l - 1) as usize;
11477 if v < m {
11478 v
11479 } else {
11480 (v << 1) - m + dec.literal(1) as usize
11481 }
11482}
11483
11484/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
11485/// colours (already-known, from the above/left neighbours) with the
11486/// ascending `transmitted` ones (delta-coded off the wire) back into one
11487/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
11488/// value picks the cached copy first, matching the C `<=`.
11489fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
11490 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
11491 let (mut ci, mut ti) = (0, 0);
11492 while ci < cached.len() && ti < transmitted.len() {
11493 if cached[ci] <= transmitted[ti] {
11494 out.push(cached[ci]);
11495 ci += 1;
11496 } else {
11497 out.push(transmitted[ti]);
11498 ti += 1;
11499 }
11500 }
11501 out.extend_from_slice(&cached[ci..]);
11502 out.extend_from_slice(&transmitted[ti..]);
11503 out
11504}
11505
11506/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
11507/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
11508/// each delta's width, the `range` bound and the clamp) is sized by
11509/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
11510/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
11511/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
11512/// the msac range, so a cross-decoder range ladder stays bit-identical
11513/// through the whole miscount -- only the decoded VALUE differs (class
11514/// `compare-range-not-tell`'s blind spot). (this
11515/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
11516/// (one flag bit each, in cache order), then delta-codes the remainder
11517/// (first value raw, each following delta `>= 1` off a shrinking bit width),
11518/// and merges the two ascending lists back together.
11519fn read_palette_colors_y(
11520 dec: &mut SymbolDecoder,
11521 n: usize,
11522 cache: &[u16],
11523 fctx: &crate::decode::FrameCtx,
11524) -> [u16; 8] {
11525 let mut cached = Vec::with_capacity(n);
11526 for &c in cache {
11527 if cached.len() >= n {
11528 break;
11529 }
11530 if dec.literal(1) == 1 {
11531 cached.push(c);
11532 }
11533 }
11534 let bd = u32::from(bit_depth(fctx));
11535 let max_val = (1i32 << bd) - 1;
11536 let mut colors = [0u16; 8];
11537 let n_cached = cached.len();
11538 if n_cached < n {
11539 let mut transmitted = Vec::with_capacity(n - n_cached);
11540 let first = dec.literal(bd) as u16;
11541 transmitted.push(first);
11542 if n_cached + 1 < n {
11543 let min_bits = bd - 3;
11544 let mut bits = min_bits + dec.literal(2);
11545 let mut range = (1i32 << bd) - i32::from(first) - 1;
11546 for _ in (n_cached + 1)..n {
11547 let delta = dec.literal(bits) as i32 + 1;
11548 let prev = *transmitted.last().unwrap();
11549 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
11550 range -= i32::from(val) - i32::from(prev);
11551 bits = bits.min(ceil_log2(range.max(0) as u32));
11552 transmitted.push(val);
11553 }
11554 }
11555 let merged = merge_colors(&transmitted, &cached);
11556 colors[..n].copy_from_slice(&merged);
11557 } else {
11558 colors[..n].copy_from_slice(&cached[..n]);
11559 }
11560 colors
11561}
11562
11563/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
11564/// `bit_depth` (see [`read_palette_colors_y`]): U reads
11565/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
11566/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
11567/// unbiased by `+1` -- both differences from Y's own reader, matching the C
11568/// side by side). V never uses a cache: a leading bit picks either `n` raw
11569/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
11570/// rather than clamp.
11571fn read_palette_colors_uv(
11572 dec: &mut SymbolDecoder,
11573 n: usize,
11574 cache: &[u16],
11575 fctx: &crate::decode::FrameCtx,
11576) -> ([u16; 8], [u16; 8]) {
11577 let mut cached = Vec::with_capacity(n);
11578 for &c in cache {
11579 if cached.len() >= n {
11580 break;
11581 }
11582 if dec.literal(1) == 1 {
11583 cached.push(c);
11584 }
11585 }
11586 let bd = u32::from(bit_depth(fctx));
11587 let max_val = 1i32 << bd;
11588 let mut u_colors = [0u16; 8];
11589 let n_cached = cached.len();
11590 if n_cached < n {
11591 let mut transmitted = Vec::with_capacity(n - n_cached);
11592 let first = dec.literal(bd) as u16;
11593 transmitted.push(first);
11594 if n_cached + 1 < n {
11595 let min_bits = bd - 3;
11596 let mut bits = min_bits + dec.literal(2);
11597 let mut range = max_val - i32::from(first);
11598 for _ in (n_cached + 1)..n {
11599 let delta = dec.literal(bits) as i32;
11600 let prev = *transmitted.last().unwrap();
11601 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
11602 range -= i32::from(val) - i32::from(prev);
11603 bits = bits.min(ceil_log2(range.max(0) as u32));
11604 transmitted.push(val);
11605 }
11606 }
11607 let merged = merge_colors(&transmitted, &cached);
11608 u_colors[..n].copy_from_slice(&merged);
11609 } else {
11610 u_colors[..n].copy_from_slice(&cached[..n]);
11611 }
11612 let mut v_colors = [0u16; 8];
11613 if dec.literal(1) == 1 {
11614 let min_bits_v = bd - 4;
11615 let bits = min_bits_v + dec.literal(2);
11616 v_colors[0] = dec.literal(bd) as u16;
11617 for i in 1..n {
11618 let mut delta = dec.literal(bits) as i32;
11619 if delta != 0 && dec.literal(1) == 1 {
11620 delta = -delta;
11621 }
11622 let mut val = i32::from(v_colors[i - 1]) + delta;
11623 if val < 0 {
11624 val += max_val;
11625 }
11626 if val >= max_val {
11627 val -= max_val;
11628 }
11629 v_colors[i] = val as u16;
11630 }
11631 } else {
11632 for i in 0..n {
11633 v_colors[i] = dec.literal(bd) as u16;
11634 }
11635 }
11636 (u_colors, v_colors)
11637}
11638
11639/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
11640/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
11641/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
11642const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
11643
11644/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
11645/// map's own per-pixel context and colour-order permutation, from the
11646/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
11647/// selection sort). `map`'s stride is `side` (this decoder never crops a
11648/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
11649/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
11650/// actual colour index to store.
11651pub(crate) fn palette_color_index_context(
11652 map: &[u8],
11653 side: usize,
11654 row: usize,
11655 col: usize,
11656 n: usize,
11657) -> (usize, [u8; 8]) {
11658 let left = if col >= 1 {
11659 Some(map[row * side + col - 1])
11660 } else {
11661 None
11662 };
11663 let up_left = if col >= 1 && row >= 1 {
11664 Some(map[(row - 1) * side + col - 1])
11665 } else {
11666 None
11667 };
11668 let up = if row >= 1 {
11669 Some(map[(row - 1) * side + col])
11670 } else {
11671 None
11672 };
11673 let mut scores = [0i32; 8];
11674 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
11675 if let Some(v) = neighbour {
11676 scores[v as usize] += weight;
11677 }
11678 }
11679 let mut color_order = [0u8; 8];
11680 for i in 0..8 {
11681 color_order[i] = i as u8;
11682 }
11683 for i in 0..3 {
11684 let mut max = scores[i];
11685 let mut max_idx = i;
11686 for j in (i + 1)..n {
11687 if scores[j] > max {
11688 max = scores[j];
11689 max_idx = j;
11690 }
11691 }
11692 if max_idx != i {
11693 let max_score = scores[max_idx];
11694 let max_color = color_order[max_idx];
11695 for k in (i + 1..=max_idx).rev() {
11696 scores[k] = scores[k - 1];
11697 color_order[k] = color_order[k - 1];
11698 }
11699 scores[i] = max_score;
11700 color_order[i] = max_color;
11701 }
11702 }
11703 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
11704 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
11705 (ctx as usize, color_order)
11706}
11707
11708/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
11709/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
11710/// cut by the frame's bottom or right mi edge codes its colour-index map only
11711/// over this part and replicates it outward -- reading the full `bw x bh` grid
11712/// consumed symbols libaom never wrote and desynced the rest of the tile
11713/// (lane-svtinter; class map-read-past-frame-edge).
11714fn palette_onscreen(
11715 mi_r: usize,
11716 mi_c: usize,
11717 bw: usize,
11718 bh: usize,
11719 fctx: &crate::decode::FrameCtx,
11720) -> (usize, usize) {
11721 // lane-palw: the ENCODER's own in-process reconstruct runs on a
11722 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
11723 // frame encoders publish the header's mi dims onto it themselves
11724 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
11725 // clamp and `tile::write_color_index_map`'s now agree there too.
11726 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
11727 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
11728}
11729
11730/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
11731/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
11732/// compute the same on-screen extent or the decoder reads a different number
11733/// of symbols than the encoder wrote.
11734pub(crate) fn palette_onscreen_dims(
11735 mi_r: usize,
11736 mi_c: usize,
11737 bw: usize,
11738 bh: usize,
11739 (mi_rows, mi_cols): (usize, usize),
11740) -> (usize, usize) {
11741 (
11742 bw.min(mi_cols.saturating_sub(mi_c) * MI),
11743 bh.min(mi_rows.saturating_sub(mi_r) * MI),
11744 )
11745}
11746
11747/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
11748/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
11749/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
11750/// together or a cut 8-wide block reads its chroma map at the wrong width.
11751/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
11752/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
11753/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
11754pub(crate) fn palette_onscreen_uv(
11755 luma: (usize, usize),
11756 on: (usize, usize),
11757 chroma: (usize, usize),
11758 ss: (usize, usize),
11759) -> (usize, usize) {
11760 (
11761 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
11762 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
11763 )
11764}
11765
11766/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
11767/// map's wavefront decode over a `side x side` grid, read over the on-screen
11768/// `on_side x on_side` corner (see [`palette_onscreen`]).
11769fn decode_color_index_map(
11770 dec: &mut SymbolDecoder,
11771 cdfs: &mut Cdfs,
11772 n: usize,
11773 side: usize,
11774 on: (usize, usize),
11775 uv: bool,
11776) -> Vec<u8> {
11777 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
11778}
11779
11780/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
11781/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
11782/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
11783/// independently rather than one shared `side` -- the square call above is
11784/// just `bw == bh`.
11785fn decode_color_index_map_wh(
11786 dec: &mut SymbolDecoder,
11787 cdfs: &mut Cdfs,
11788 n: usize,
11789 bw: usize,
11790 bh: usize,
11791 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
11792 on: (usize, usize),
11793 uv: bool,
11794) -> Vec<u8> {
11795 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
11796 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11797 if on_bw < bw || on_bh < bh {
11798 hit!(PALETTE_ONSCREEN_CUT_HITS);
11799 }
11800 let mut map = vec![0u8; bw * bh];
11801 if trace {
11802 let (rng, _) = dec.debug_state();
11803 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
11804 }
11805 map[0] = read_uniform(dec, n) as u8;
11806 if trace {
11807 let (rng, _) = dec.debug_state();
11808 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11809 }
11810 for i in 1..(on_bw + on_bh - 1) {
11811 let j_hi = i.min(on_bw - 1);
11812 let j_lo = i.saturating_sub(on_bh - 1);
11813 for j in (j_lo..=j_hi).rev() {
11814 let row = i - j;
11815 let col = j;
11816 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11817 if trace {
11818 let (rng, _) = dec.debug_state();
11819 let row_cdf = if uv {
11820 &cdfs.palette_uv_color_index[n - 2][ctx]
11821 } else {
11822 &cdfs.palette_y_color_index[n - 2][ctx]
11823 };
11824 eprintln!(
11825 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11826 row_cdf[0], row_cdf[n]
11827 );
11828 }
11829 let symbol = if uv {
11830 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11831 } else {
11832 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11833 };
11834 map[row * bw + col] = color_order[symbol];
11835 if trace {
11836 let (rng, _) = dec.debug_state();
11837 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11838 }
11839 }
11840 }
11841 palette_replicate(&mut map, bw, bh, on);
11842 map
11843}
11844
11845/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11846/// last on-screen column then the last on-screen row are replicated over the
11847/// off-screen remainder, so the prediction still covers the whole block. The
11848/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11849/// so the pixels it prices and reconstructs are the ones the on-screen
11850/// symbols it writes really decode to.
11851pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11852 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11853 for row in 0..on_bh {
11854 let last = map[row * bw + on_bw - 1];
11855 map[row * bw + on_bw..row * bw + bw].fill(last);
11856 }
11857 for row in on_bh..bh {
11858 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11859 }
11860}
11861
11862/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11863/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11864/// size class comes from [`filter_intra_size_class_rect`] instead of the
11865/// square-only [`filter_intra_size_class`], and the palette read (when
11866/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11867/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11868/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11869/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11870#[allow(clippy::too_many_arguments)]
11871fn read_intra_mode_rect(
11872 dec: &mut SymbolDecoder,
11873 cdfs: &mut Cdfs,
11874 above_mode: usize,
11875 left_mode: usize,
11876 cfl: bool,
11877 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11878 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11879 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11880 // chroma is coded once, on the closing strip). Every other caller is a
11881 // block big enough to own its chroma and passes `true`.
11882 has_chroma: bool,
11883 bw: usize,
11884 bh: usize,
11885 enable_filter_intra: bool,
11886 skip_ctx: usize,
11887 allow_screen_content_tools: bool,
11888 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11889 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11890 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11891 palette: Option<(usize, &[u16])>,
11892 palette_uv_cache: &[u16],
11893 mi_r: usize,
11894 mi_c: usize,
11895 fctx: &crate::decode::FrameCtx,
11896) -> Result<(
11897 bool,
11898 usize,
11899 i32,
11900 usize,
11901 i32,
11902 Option<(i32, i32)>,
11903 Option<usize>,
11904 Option<PaletteY>,
11905 Option<PaletteUv>,
11906 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11907 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11908 // straight out of `read_intra_frame_mode_info` then, so every later field
11909 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11910 // no filter intra). A caller that can reconstruct intrabc at its shape
11911 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11912 // name with the same string it always did.
11913 Option<(i32, i32)>,
11914)> {
11915 // lane-av1mono: libaom guards every chroma symbol read with
11916 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11917 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11918 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11919 // into the same `has_chroma` this reader already gates on.
11920 let has_chroma = has_chroma && !mono(fctx);
11921 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11922 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11923 if ec_istep {
11924 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11925 // (decodemv.c:818), printed at the same point: before the first
11926 // mode-info symbol of the block, so a cross-decoder range ladder can
11927 // be keyed on the BLOCK, not just on the symbol sequence.
11928 eprintln!(
11929 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11930 enable_filter_intra as i32,
11931 filter_intra_size_class_rect(bw, bh),
11932 dec.debug_state().0
11933 );
11934 }
11935 macro_rules! istep {
11936 ($name:literal, $val:expr) => {
11937 if ec_istep {
11938 let (rng, _) = dec.debug_state();
11939 eprintln!(
11940 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11941 $name, $val
11942 );
11943 }
11944 };
11945 }
11946 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11947 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11948 // the one point every rect caller routes through, so no call site can
11949 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11950 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11951 let cfl = if cfl && bw.max(bh) > 32 {
11952 hit!(NOCFL_UV_MODE_HITS);
11953 false
11954 } else {
11955 cfl
11956 };
11957 // lane-intra14 r1: on the INTER block path everything up to and including
11958 // `is_inter` was already read by [`decode_inter_block`], so this reader
11959 // starts at the mode syntax with the `skip` that caller read.
11960 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11961 let skip = if let Some((_, skip)) = inter {
11962 skip
11963 } else {
11964 // Same `intra_segment_id` placement as the square reader above.
11965 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11966 if seg_id_pre_skip(fctx) {
11967 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11968 }
11969 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11970 istep!("skip", skip as i32);
11971 if !seg_id_pre_skip(fctx) {
11972 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11973 }
11974 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11975 istep!("cdef", 0);
11976 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11977 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11978 // `false`.
11979 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11980 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11981 istep!("dq", 0);
11982 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11983 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11984 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11985 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11986 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11987 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11988 // decoder at the FIRST symbol of the first rect block of every
11989 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11990 // block at this shape is out of scope, so the flag is consumed and
11991 // refused by name when it fires.
11992 if allow_intrabc_frame(fctx) {
11993 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11994 hit!(RECT_INTRABC_READS);
11995 istep!("intrabc", use_intrabc as i32);
11996 if use_intrabc {
11997 hit!(INTRABC_HITS);
11998 // libaom `read_intrabc_info`: the DV read, then an immediate
11999 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
12000 // no angle deltas, no palette, no filter intra. The caller owns
12001 // the reconstruction at its own shape.
12002 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
12003 return Ok((
12004 skip,
12005 DC_PRED,
12006 0,
12007 DC_PRED,
12008 0,
12009 None,
12010 None,
12011 None,
12012 None,
12013 Some(dv),
12014 ));
12015 }
12016 }
12017 skip
12018 };
12019 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
12020 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
12021 // off `kf_y_mode_cdf[above][left]`).
12022 let mode = if let Some((size_group, _)) = inter {
12023 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
12024 dec.symbol(&mut cdfs.y_mode[size_group])
12025 } else {
12026 let above_ctx = INTRA_MODE_CTX[above_mode];
12027 let left_ctx = INTRA_MODE_CTX[left_mode];
12028 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
12029 };
12030 istep!("mode", mode as i32);
12031 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
12032 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
12033 } else {
12034 0
12035 };
12036 istep!("angle_y", angle_delta_y);
12037 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
12038 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
12039 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
12040 // here, from the block's own size, is the single point every caller routes
12041 // through -- a caller passing `true` for a >32 strip used to pick the
12042 // 14-symbol CFL CDF, same value but a different range (class
12043 // wrong-alphabet-same-value).
12044 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
12045 let uv_mode = if !has_chroma {
12046 DC_PRED
12047 } else if cfl {
12048 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
12049 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
12050 } else {
12051 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
12052 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
12053 };
12054 istep!("uv_mode", uv_mode as i32);
12055 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
12056 Some(read_cfl_alphas(dec, cdfs))
12057 } else {
12058 None
12059 };
12060 if has_chroma && (9..=12).contains(&uv_mode) {
12061 hit!(SMOOTH_UV_HITS);
12062 }
12063 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
12064 hit!(DIRECTIONAL_UV_HITS);
12065 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
12066 } else {
12067 0
12068 };
12069 istep!("angle_uv", angle_delta_uv);
12070 if angle_delta_uv != 0 {
12071 hit!(UV_ANGLE_DELTA_HITS);
12072 }
12073 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
12074 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
12075 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
12076 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
12077 // colours only here, the colour-index maps deferred past `filter_intra`
12078 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
12079 // runs from the caller, after the whole mode-info read).
12080 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
12081 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
12082 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
12083 // r6: this is the exact site the removed blanket refusal used to
12084 // guard -- reached for EVERY rect strip in a screen-content frame,
12085 // independent of whether the block ends up using a palette.
12086 hit!(RECT_SCREEN_CONTENT_HITS);
12087 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
12088 let use_palette_y =
12089 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
12090 if use_palette_y {
12091 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
12092 let colors = read_palette_colors_y(dec, n, cache, fctx);
12093 palette_y_pending = Some((n, colors));
12094 }
12095 let palette_uv_mode_ctx = usize::from(use_palette_y);
12096 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
12097 if has_chroma
12098 && uv_mode == DC_PRED
12099 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
12100 {
12101 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
12102 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
12103 palette_uv_pending = Some((n, u_colors, v_colors));
12104 }
12105 }
12106 let mut filter_intra = None;
12107 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12108 let (rng, _) = dec.debug_state();
12109 eprintln!(
12110 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
12111 class={:?} rng={rng}",
12112 enable_filter_intra as i32,
12113 filter_intra_size_class_rect(bw, bh)
12114 );
12115 }
12116 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
12117 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
12118 if mode == DC_PRED
12119 && enable_filter_intra
12120 && palette_y_pending.is_none()
12121 && let Some(class) = filter_intra_size_class_rect(bw, bh)
12122 {
12123 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
12124 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12125 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
12126 }
12127 istep!("use_filter_intra", use_filter_intra as i32);
12128 if use_filter_intra {
12129 hit!(FILTER_INTRA_HITS);
12130 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
12131 istep!("filter_intra_mode", fi_mode as i32);
12132 filter_intra = Some(fi_mode);
12133 }
12134 }
12135 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
12136 // same order as [`read_intra_mode`]'s own square path.
12137 let palette_y = palette_y_pending.map(|(n, colors)| {
12138 let map = decode_color_index_map_wh(
12139 dec,
12140 cdfs,
12141 n,
12142 bw,
12143 bh,
12144 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
12145 false,
12146 );
12147 hit!(PALETTE_HITS);
12148 hit!(PALETTE_RECT_HITS);
12149 PaletteY {
12150 size: n,
12151 colors,
12152 map,
12153 }
12154 });
12155 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
12156 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
12157 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
12158 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
12159 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
12160 // chroma palette and desynced the tile from there.
12161 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
12162 let on = palette_onscreen_uv(
12163 (bw, bh),
12164 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
12165 (cw, ch),
12166 (ss_x(fctx), ss_y(fctx)),
12167 );
12168 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
12169 hit!(PALETTE_UV_HITS);
12170 PaletteUv {
12171 size: n,
12172 u_colors,
12173 v_colors,
12174 map,
12175 }
12176 });
12177 Ok((
12178 skip,
12179 mode,
12180 angle_delta_y,
12181 uv_mode,
12182 angle_delta_uv,
12183 alpha,
12184 filter_intra,
12185 palette_y,
12186 palette_uv,
12187 None,
12188 ))
12189}
12190
12191/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
12192/// at the strip's REAL mi position. `av1_get_palette_cache` reads
12193/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
12194/// block, so each strip owns its own rows and columns and no aliasing rule
12195/// is needed (lane-kf900 r6).
12196#[allow(clippy::too_many_arguments)]
12197fn record_strip_palette(
12198 n: &mut Neighbours,
12199 mi: (usize, usize),
12200 bw: usize,
12201 bh: usize,
12202 y_size: usize,
12203 y_colors: [u16; 8],
12204 uv_size: usize,
12205 uv_colors: [u16; 8],
12206) {
12207 let (r, c) = mi;
12208 // lane-t900 r23 rung: every publication of a block's palette state into
12209 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
12210 // path left a stale `left_palette_size` behind when
12211 // `av1_get_palette_mode_ctx` disagrees with libaom's.
12212 if crate::envflags::env_flag!("EC_PALPUB") {
12213 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
12214 }
12215 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
12216 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
12217 // existed because the 16px [`SUB`] cell held one slot for all the strips
12218 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
12219 // real neighbour leaf 1 reads.
12220 {
12221 for cell in 0..(bw / MI).max(1) {
12222 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
12223 *e = y_size as u8;
12224 n.above_palette_uv_size[c + cell] = uv_size as u8;
12225 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
12226 // colours of a size-0 neighbour are never read.
12227 if y_size > 0 {
12228 n.above_palette_colors[c + cell] = y_colors;
12229 }
12230 if uv_size > 0 {
12231 n.above_palette_uv_colors[c + cell] = uv_colors;
12232 }
12233 }
12234 }
12235 }
12236 {
12237 for cell in 0..(bh / MI).max(1) {
12238 if n.left_palette_size.get(r + cell).is_none() {
12239 break;
12240 }
12241 n.left_palette_size[r + cell] = y_size as u8;
12242 n.left_palette_uv_size[r + cell] = uv_size as u8;
12243 if y_size > 0 {
12244 n.left_palette_colors[r + cell] = y_colors;
12245 }
12246 if uv_size > 0 {
12247 n.left_palette_uv_colors[r + cell] = uv_colors;
12248 }
12249 }
12250 }
12251}
12252
12253/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
12254fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
12255 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
12256 i32::from(y.data[ly * y.width + lx])
12257 })
12258}
12259
12260/// Everything a rect strip already read out of the stream before its luma
12261/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
12262/// (nine values that would otherwise be nine more parameters).
12263struct RectStripModes {
12264 skip: bool,
12265 mode: usize,
12266 angle_delta_y: i32,
12267 uv_predict_mode: usize,
12268 angle_delta_uv: i32,
12269 alpha: Option<(i32, i32)>,
12270 filter_intra: Option<usize>,
12271 smooth_neighbor: bool,
12272 smooth_neighbor_uv: bool,
12273 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
12274 /// mapped through the colour table), sliced per transform unit below --
12275 /// palette prediction reads no edge pixels, so a unit's slice of the
12276 /// whole-block map IS its prediction. Without this a palette strip whose
12277 /// transform splits predicted DC and came out flat grey while the entropy
12278 /// stream stayed in sync (the coefficients are read either way).
12279 palette_y: Option<Vec<u16>>,
12280 /// As `palette_y`, for the un-split chroma transform (U, V).
12281 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
12282}
12283
12284/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
12285/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
12286/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
12287/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
12288/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
12289/// TX_32X16`) and only the second reaches a square -- the reason
12290/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
12291/// already square) mis-tiled 1:4 strips.
12292fn depth_to_tx_wh(
12293 bw: usize,
12294 bh: usize,
12295 depth: usize,
12296 fctx: &crate::decode::FrameCtx,
12297) -> (usize, usize) {
12298 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
12299 // `read_tx_size`: the lossless early return comes before
12300 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
12301 if lossless(fctx) {
12302 return (4, 4);
12303 }
12304 let (mut w, mut h) = (bw.min(64), bh.min(64));
12305 for _ in 0..depth {
12306 match w.cmp(&h) {
12307 std::cmp::Ordering::Greater => w /= 2,
12308 std::cmp::Ordering::Less => h /= 2,
12309 std::cmp::Ordering::Equal => {
12310 w /= 2;
12311 h /= 2;
12312 }
12313 }
12314 }
12315 (w, h)
12316}
12317
12318/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
12319/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
12320/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
12321/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
12322/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
12323/// 2-px-wide area is not a transform shape. The strip pairs with its
12324/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
12325/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
12326/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
12327/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
12328/// the entropy context on the floored cell. Returns
12329/// `(pair block width, pair block height, write anchor x, entropy mi column)`
12330/// for that pair, or `None` when the strip keeps its own plane block at its
12331/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
12332/// 2 px wide) and every 4:2:2 strip of 8 px or more.
12333fn chroma422_pair_plane(
12334 ss_x: bool,
12335 ss_y: bool,
12336 mi_col: usize,
12337 bw: usize,
12338 bh: usize,
12339) -> Option<(usize, usize, usize, usize)> {
12340 if ss_x && !ss_y && (bw >> 1) == 2 {
12341 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
12342 } else {
12343 None
12344 }
12345}
12346
12347/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
12348/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
12349/// rect path here refused by name until now ("per-unit rect prediction is not
12350/// ported").
12351///
12352/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
12353/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
12354/// strip the very first step already lands on a SQUARE transform
12355/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
12356/// every further step halves a square) -- so each unit is square and reads
12357/// through the ordinary square [`read_plane`]. What is genuinely rectangular
12358/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
12359/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
12360/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
12361/// split by luma's depth.
12362///
12363/// Each unit predicts off whatever the earlier units of this same block
12364/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
12365/// inside `av1_foreach_transformed_block`, raster order), which is exactly
12366/// what predicting the whole strip in one shot got wrong.
12367#[allow(clippy::too_many_arguments)]
12368fn decode_rect_split(
12369 dec: &mut SymbolDecoder,
12370 cdfs: &mut Cdfs,
12371 neighbours: &mut Neighbours,
12372 at_mi: (usize, usize),
12373 bw: usize,
12374 bh: usize,
12375 // The transform unit's own width and height in pixels. Square for every
12376 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
12377 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
12378 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
12379 tx_w: usize,
12380 tx_h: usize,
12381 m: &RectStripModes,
12382 y: &mut PlaneBuf<'static>,
12383 u: &mut PlaneBuf<'static>,
12384 v: &mut PlaneBuf<'static>,
12385 base_q_idx: u8,
12386 reduced_tx_set: bool,
12387 fctx: &crate::decode::FrameCtx,
12388) -> Result<()> {
12389 let (mi_r, mi_c) = at_mi;
12390 let (px, py) = (mi_c * MI, mi_r * MI);
12391 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
12392 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
12393 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
12394 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
12395 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
12396 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
12397 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
12398 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
12399 // measurement). The plane is still coded -- `decode_token_recon_block`
12400 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
12401 // 4x8 rect units, plane-major.
12402 let chroma_422_oob = ss_x(fctx) == 1
12403 && ss_y(fctx) == 0
12404 && matches!(
12405 (bw, bh),
12406 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
12407 );
12408 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
12409 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
12410 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
12411 // plane is then `(4, chroma_h)` written at the FLOORED cell
12412 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
12413 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
12414 // the same walk the (8, 32) class takes). The lossless raster arm keeps
12415 // the strip's own geometry: no caller of this function can present a
12416 // 4-wide strip yet (the enumeration test pins the five callers at
12417 // `8 <= min`), and the skip/tiled arms are the routes a future caller
12418 // needs.
12419 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
12420 let chroma_422_pair_wide = chroma422_pair.is_some();
12421 let (chroma_block_w, chroma_block_h, chroma_x) =
12422 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
12423 // The chroma transform is picked before any symbol is read, so an
12424 // unsupported chroma shape refuses before this strip desyncs the tile.
12425 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
12426 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
12427 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
12428 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
12429 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
12430 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
12431 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
12432 // squares a rect transform down to a CDF set by
12433 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
12434 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
12435 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
12436 // paths already prove for these same shapes.
12437 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
12438 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
12439 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
12440 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
12441 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
12442 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
12443 _ => None,
12444 };
12445 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
12446 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
12447 // below; everything else still needs a single-unit table.
12448 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
12449 // halves only the width, so a rect luma strip codes a SQUARE chroma block
12450 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
12451 // rect strip's chroma is itself rect, so the square rows are unreachable
12452 // there and cannot change their results.
12453 // lane-av1-422blockhalf: the tiled arms below handle every shape this
12454 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
12455 // diagnostic names only the shapes that would actually refuse -- it used
12456 // to fire for every tiled square too (the parent lane's `chroma=8x8`
12457 // rows) and sent the next lane chasing handled shapes.
12458 let chroma_tiled = chroma_422_pair_wide
12459 || chroma_422_oob
12460 || matches!(
12461 (chroma_w, chroma_h),
12462 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
12463 );
12464 if !m.skip {
12465 if let Some(i) = match (chroma_w, chroma_h) {
12466 (32, 8) => Some(0),
12467 (8, 32) => Some(1),
12468 (8, 4) => Some(2),
12469 (4, 8) => Some(3),
12470 _ => None,
12471 } {
12472 hit_do! {
12473 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
12474 let mut hits = c.get();
12475 hits[i] += 1;
12476 c.set(hits);
12477 });
12478 }
12479 }
12480 if !m.skip && chroma.is_none() && !chroma_tiled {
12481 // Diagnostic for the next caller that lands here (class
12482 // refusal-names-a-correlate: the message names the tool, not the
12483 // shape); the refusal below keeps its inventory-pinned wording.
12484 eprintln!(
12485 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
12486 chroma={chroma_w}x{chroma_h}"
12487 );
12488 }
12489 }
12490 // lane-rectsplit r2 (verifier finding): with both callers wired
12491 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
12492 // 64x32/32x64) every shape that reaches here has a table above, so this
12493 // arm is UNREACHABLE today. It stays as the shape guard for the next
12494 // caller -- a new strip size would otherwise hit the `expect` below and
12495 // panic instead of refusing by name -- and so stays in
12496 // `refusal_inventory::REFUSALS`.
12497 if !m.skip && chroma.is_none() && !chroma_tiled {
12498 return Err(unsupported(
12499 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
12500 ));
12501 }
12502 hit!(RECT_SPLIT_TX_HITS);
12503 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
12504 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
12505 }
12506 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
12507 // A square unit reads through the ordinary square [`read_plane`]; a rect
12508 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
12509 // the very tables the unsplit 16x8/32x16 paths use.
12510 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
12511 (w, h) if w == h => None,
12512 (16, 8) | (8, 16) => Some((
12513 if reduced_tx_set {
12514 TxbSet::LumaRect16x8
12515 } else {
12516 TxbSet::LumaRect16x8Set1
12517 },
12518 if tx_w == 16 {
12519 &SCAN_16X8[..]
12520 } else {
12521 &SCAN_8X16[..]
12522 },
12523 )),
12524 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
12525 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
12526 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
12527 // strip, read through the `luma_64corner` arm below instead of a rect
12528 // table -- a 64-length axis codes only its low 32 coefficients
12529 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
12530 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
12531 // depth-0 arm already reads on the key-frame path.
12532 //
12533 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
12534 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
12535 // sub-8x8 intra leaves still refused: with those lifted (r2) the
12536 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
12537 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
12538 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
12539 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
12540 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
12541 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
12542 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
12543 (64, 32) | (32, 64) => None,
12544 _ => {
12545 return Err(unsupported(format!(
12546 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
12547 coefficient tables for that shape here)"
12548 )));
12549 }
12550 };
12551 // The `None` above that is NOT the square arm.
12552 let luma_64corner = tx_w != tx_h;
12553 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
12554 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
12555 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
12556 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
12557 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
12558 // per-unit rect walk stay wired above/below; the round that finds that
12559 // defect deletes this refusal and nothing else.
12560 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
12561 let luma_scan = default_scan(tx_w.min(tx_h));
12562 let zero_tu = vec![0i32; tx_w * tx_h];
12563 // The strip's OWN edge availability, the fallback for a transform unit
12564 // whose top-right/bottom-left pixels fall outside the strip.
12565 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12566 for tu_row in 0..bh / tx_h {
12567 for tu_col in 0..bw / tx_w {
12568 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
12569 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12570 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
12571 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
12572 // libaom clips `av1_foreach_transformed_block_in_plane` to
12573 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
12574 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
12575 // TOP-LEFT sample falls outside the frame is never coded. We read
12576 // coefficients for those phantom units and desynced the stream at
12577 // the very next symbol.
12578 if tu_px >= y.true_width || tu_py >= y.true_height {
12579 continue;
12580 }
12581 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
12582 // transform unit INSIDE a block, which is a different rule from
12583 // the standalone-block table [`Reach::of`] applies -- and the
12584 // reason a depth-2 superblock strip came out one sample off
12585 // before this: `Reach::of(tx, ..)` answered as if the unit were
12586 // its own block at that superblock position.
12587 // * top-right: if the unit's right neighbour is still inside the
12588 // strip the pixels are already reconstructed (`col_off +
12589 // tx_wide < plane_bw`); otherwise only the strip's own top row
12590 // of units can reach past it, through the block-level answer.
12591 // * bottom-left: a unit that is not in the strip's left column
12592 // has none (`col_off > 0` returns 0); inside the strip
12593 // (`row_off + tx_high < plane_bh`) they are the left
12594 // neighbour's, already reconstructed; the last row falls back
12595 // to the block-level answer.
12596 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
12597 // The unit's own window on the block's palette prediction.
12598 if let Some(buf) = &m.palette_y {
12599 let tu_buf: Vec<u16> = (0..tx_h)
12600 .flat_map(|i| {
12601 let base = (row_off + i) * bw + col_off;
12602 buf[base..base + tx_w].iter().copied()
12603 })
12604 .collect();
12605 set_palette_pred(tu_buf, fctx);
12606 }
12607 if m.skip {
12608 push_intra_rect(
12609 0,
12610 tu_px,
12611 tu_py,
12612 tx_w,
12613 tx_h,
12614 m.mode,
12615 m.angle_delta_y,
12616 tu_reach,
12617 &zero_tu,
12618 None,
12619 m.filter_intra,
12620 m.smooth_neighbor,
12621 fctx,
12622 );
12623 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12624 } else if luma_64corner && luma_rect.is_none() {
12625 // The un-split 64-level luma transform: `read_coeffs` on the
12626 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
12627 // and the real rect shape passed through for
12628 // `av1_nz_map_ctx_offset` -- byte for byte
12629 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
12630 // 64-level strip gate already proves. `tx_type` is not coded
12631 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
12632 // the square-up size is TX_64X64), and this unit covers its
12633 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
12634 if crate::envflags::env_flag!("EC_RECT64TU") {
12635 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
12636 }
12637 hit_do! {
12638 RECT64_CORNER_TU_HITS.with(|c| {
12639 let mut v = c.get();
12640 v[usize::from(tx_h > tx_w)] += 1;
12641 c.set(v);
12642 });
12643 }
12644 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12645 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
12646 let (corner, tu_tx_type) = read_coeffs(
12647 dec,
12648 &mut coding,
12649 default_scan(TX32),
12650 0,
12651 dc_sign_ctx(tu_around.2),
12652 TxType::DctDct,
12653 Some((tx_w, tx_h)),
12654 )?;
12655 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
12656 let mut tu_grid = vec![0i32; tx_w * tx_h];
12657 for row in 0..ch {
12658 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
12659 }
12660 let residual = dequant_and_inverse_typed_wh(
12661 &tu_grid,
12662 tx_w,
12663 tx_h,
12664 crate::decode::bit_depth(fctx),
12665 block_q_idx(fctx),
12666 plane_q_delta(0, fctx).0,
12667 plane_q_delta(0, fctx).1,
12668 tu_tx_type,
12669 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12670 );
12671 push_intra_rect(
12672 0,
12673 tu_px,
12674 tu_py,
12675 tx_w,
12676 tx_h,
12677 m.mode,
12678 m.angle_delta_y,
12679 tu_reach,
12680 &residual,
12681 None,
12682 m.filter_intra,
12683 m.smooth_neighbor,
12684 fctx,
12685 );
12686 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12687 } else if let Some((rect_set, rect_scan)) = luma_rect {
12688 // The rect-unit twin of the square arm below: same contexts,
12689 // same order, through the rect coefficient reader. The
12690 // `tx_type` CDF row of a filter-intra block is
12691 // `fimode_to_intradir[filter_intra_mode]`, never the block's
12692 // own (always DC_PRED) mode -- [`read_plane`] applies that
12693 // for the square arm, so this one must too.
12694 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12695 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
12696 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
12697 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
12698 // neighbour-magnitude table is for a unit SMALLER than its
12699 // block. [`decode_block_rect`]'s own unsplit read passes a
12700 // literal 0 for the same reason; this arm applied the table
12701 // unconditionally and desynced every depth-0 rect strip that
12702 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
12703 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
12704 0
12705 } else {
12706 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
12707 };
12708 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
12709 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12710 dec,
12711 &mut coding,
12712 rect_scan,
12713 tx_w,
12714 tx_h,
12715 tu_skip_ctx,
12716 dc_sign_ctx(tu_around.2),
12717 TxType::DctDct,
12718 0,
12719 )?;
12720 let residual = dequant_and_inverse_typed_wh(
12721 &tu_grid,
12722 tx_w,
12723 tx_h,
12724 crate::decode::bit_depth(fctx),
12725 block_q_idx(fctx),
12726 plane_q_delta(0, fctx).0,
12727 plane_q_delta(0, fctx).1,
12728 tu_tx_type,
12729 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12730 );
12731 push_intra_rect(
12732 0,
12733 tu_px,
12734 tu_py,
12735 tx_w,
12736 tx_h,
12737 m.mode,
12738 m.angle_delta_y,
12739 tu_reach,
12740 &residual,
12741 None,
12742 m.filter_intra,
12743 m.smooth_neighbor,
12744 fctx,
12745 );
12746 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12747 } else {
12748 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12749 // This unit is smaller than the block it sits in, so
12750 // `txb_skip_ctx` is the neighbour-magnitude table, not the
12751 // lone-TU 0 (spec `get_txb_ctx_general`).
12752 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12753 let tu_grid = read_plane(
12754 dec,
12755 cdfs,
12756 luma_set,
12757 &luma_scan,
12758 0,
12759 tu_around,
12760 m.mode,
12761 m.mode,
12762 m.angle_delta_y,
12763 tu_reach,
12764 y,
12765 tu_px,
12766 tu_py,
12767 tx_w,
12768 tx_w,
12769 base_q_idx,
12770 None,
12771 m.filter_intra,
12772 Some(tu_skip_ctx),
12773 m.smooth_neighbor,
12774 fctx,
12775 )?;
12776 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12777 }
12778 }
12779 }
12780 // CHROMA: one un-split rect transform for the whole strip.
12781 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
12782 // units -- each stamps its own neighbour context as it is read, and the
12783 // whole-block `record_split_luma_rect_mi` below would overwrite all of
12784 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
12785 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
12786 // collected here and replayed after that record.
12787 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12788 // The chroma_tiled arm below stamps each unit's coefficient context
12789 // immediately (so the NEXT unit reads it), then the whole-strip
12790 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
12791 // whole-strip state and the per-unit DC signs and levels are lost
12792 // (class `override-slot-on-one-arm`). The units are collected here and
12793 // replayed after that record, the way the lossless arm's
12794 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
12795 // already do.
12796 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12797 let ac = m.alpha.map(|_| {
12798 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
12799 // luma -- the 8-px-wide region the floored 4-px chroma block covers
12800 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
12801 if chroma_422_pair_wide {
12802 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
12803 } else {
12804 cfl_src_rect(px, py, bw, bh)
12805 }
12806 });
12807 let reach = if chroma_422_pair_wide {
12808 // The chroma units predict off the PAIR block's edges: an odd-column
12809 // strip's pair starts 4 luma px to the strip's left, so the strip's
12810 // own answer names the wrong above/right samples (the pair16 arm's
12811 // `pair_reach`, one partition level up).
12812 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12813 } else {
12814 block_reach
12815 };
12816 let (u_grid, v_grid) = if mono(fctx) {
12817 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12818 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12819 // section -- the skipped-strip pushes, the lossless raster and the
12820 // un-split `read_coeffs_rect` below -- is bypassed.
12821 let zero = Grid::Zero(chroma_w * chroma_h);
12822 (zero.clone(), zero)
12823 } else if m.skip {
12824 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12825 if chroma_422_pair_wide || chroma_422_oob {
12826 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12827 // per transform unit even when the strip is skipped
12828 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12829 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12830 // units -- one whole-plane push here would ask the intra
12831 // predictor for a 1:8 rect it never needs.
12832 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12833 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12834 // grid at the floored anchor `chroma_x`.
12835 let (uw, uh) = (4usize, 8usize);
12836 for plane_idx in 1..=2 {
12837 if let Some((ub, vb)) = &m.palette_uv {
12838 let buf = if plane_idx == 1 { ub } else { vb };
12839 set_palette_pred(buf.clone(), fctx);
12840 }
12841 for cu_row in 0..chroma_block_h / uh {
12842 for cu_col in 0..chroma_block_w / uw {
12843 push_intra_rect(
12844 plane_idx,
12845 chroma_x + cu_col * uw,
12846 cpy + cu_row * uh,
12847 uw,
12848 uh,
12849 m.uv_predict_mode,
12850 m.angle_delta_uv,
12851 reach,
12852 &ZERO_RESIDUAL[..uw * uh],
12853 m.alpha
12854 .zip(ac.clone())
12855 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12856 None,
12857 m.smooth_neighbor_uv,
12858 fctx,
12859 );
12860 }
12861 }
12862 }
12863 } else {
12864 if let Some((ub, _)) = &m.palette_uv {
12865 set_palette_pred(ub.clone(), fctx);
12866 }
12867 push_intra_rect(
12868 1,
12869 cpx,
12870 cpy,
12871 chroma_w,
12872 chroma_h,
12873 m.uv_predict_mode,
12874 m.angle_delta_uv,
12875 reach,
12876 &zero,
12877 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12878 None,
12879 m.smooth_neighbor_uv,
12880 fctx,
12881 );
12882 if let Some((_, vb)) = &m.palette_uv {
12883 set_palette_pred(vb.clone(), fctx);
12884 }
12885 push_intra_rect(
12886 2,
12887 cpx,
12888 cpy,
12889 chroma_w,
12890 chroma_h,
12891 m.uv_predict_mode,
12892 m.angle_delta_uv,
12893 reach,
12894 &zero,
12895 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12896 None,
12897 m.smooth_neighbor_uv,
12898 fctx,
12899 );
12900 }
12901 (zero.clone(), zero)
12902 } else if lossless(fctx) {
12903 // lane-lossless: the strip's chroma plane block is coded as 4x4
12904 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12905 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12906 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12907 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12908 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12909 // offset (our `+3` row base) whenever the plane block is bigger than
12910 // the transform.
12911 let scan4 = default_scan(4);
12912 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12913 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12914 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12915 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12916 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12917 // cell), and the 8-px step made every unit past the first column/row
12918 // read its `txb_skip` context at the WRONG mi (two cells over) and
12919 // stamp a 2-cell span with one unit's state -- the polluted above-band
12920 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12921 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12922 // ours read `above[28..29]` where the oracle read `above[26]`).
12923 let span_x = 4 << ss_x(fctx);
12924 let span_y = 4 << ss_y(fctx);
12925 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12926 for plane_idx in 1..=2 {
12927 for cu_row in 0..ch_n {
12928 for cu_col in 0..cw_n {
12929 // lane-av1offtile: the CHROMA twin of the luma walk's
12930 // `max_blocks_wide/high` clip (decode.rs:12516, lane-hgkf
12931 // r1). libaom computes those bounds per PLANE
12932 // (`max_block_wide(xd, plane_bsize, plane)`,
12933 // av1_common_int.h:1565 -- `mb_to_right_edge >>
12934 // (3 + pd->subsampling_x)`, then `>> MI_SIZE_LOG2`), so a
12935 // chroma unit whose top-left sample falls outside the
12936 // CHROMA plane is never coded. This walk counted
12937 // `chroma_w / 4` x `chroma_h / 4` units off the BLOCK's
12938 // own extent instead.
12939 //
12940 // MEASURED on `mix_176x144_6.obu` (4:2:0 8-bit,
12941 // --cq-level=0 --aq-mode=1 altref; the 48x16 bottom-right
12942 // sliver, block mi=(32,32) px=(128,128) bw=64 bh=32):
12943 // the chroma plane is 88x72, so `cw_n` must be
12944 // `(88 - 64) / 4 = 6` and `ch_n` `(72 - 64) / 4 = 2` --
12945 // the oracle's own `EC_ECDUMP_IN` for that block is
12946 // exactly 12 units per plane (bc 0..5 x br 0..1). Ours
12947 // walked 8 x 4 = 32 per plane: 20 phantom units x 2
12948 // planes = the 40 extra `txb_skip` reads after SYMR
12949 // 25791, all at `mi=(32,32)`, all `all_zero`, all with
12950 // the bit position FROZEN at 36288 -- reads out of a
12951 // tile already exhausted, which is what turned the
12952 // desync 11 970 reads later into a hard
12953 // `REFUSED: unsupported: AV1 tile (a Golomb tail longer
12954 // than this decoder reads)`.
12955 if cpx + cu_col * 4 >= u.true_width || cpy + cu_row * 4 >= u.true_height {
12956 hit!(RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS);
12957 continue;
12958 }
12959 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12960 // lane-av1422llintra: at ss (1, 0) one chroma column
12961 // spans TWO luma mi columns, so the plain rect walk sums
12962 // its whole-unit dc sign TWICE where libaom's
12963 // `get_txb_ctx_general` reads `txb_w_unit` chroma cells
12964 // -- one per column. `dc_sign_ctx` only sees the vote's
12965 // SIGNUM, so a doubled above vote flips the row exactly
12966 // when above and left cancel (a+l = 0 -> ctx 0 becomes
12967 // 2a+l = +a). Measured on the pinned 4:2:2 all-intra
12968 // lossless control `ll422_allintra.obu`: the V 4x4 unit
12969 // at chroma (24, 8) of the BLOCK_32X8 at mi(2,8) --
12970 // oracle `EC_DBGCTX above0=23 left0=13` sums to dc 0 and
12971 // reads `dc_sign_cdf[0]`; ours summed the above column
12972 // twice, got vote +1, and read `dc_sign_cdf[2]`, so the
12973 // DC sign symbol came out inverted and the whole tile
12974 // desynced from there. Identical to the guard one arm up
12975 // at 12865.
12976 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12977 neighbours.around_mi_422_chroma(cu_mi, span_x, span_y)
12978 } else {
12979 neighbours.around_mi_rect(cu_mi, span_x, span_y)
12980 };
12981 let cu_reach = tu_reach(
12982 bw,
12983 bh,
12984 cu_col * span_x,
12985 cu_row * span_y,
12986 span_x,
12987 block_reach,
12988 px,
12989 py,
12990 y.width,
12991 y.height,
12992 fctx,
12993 );
12994 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12995 if let Some((ub, vb)) = &m.palette_uv {
12996 let pbuf = if plane_idx == 1 { ub } else { vb };
12997 set_palette_pred(
12998 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12999 fctx,
13000 );
13001 }
13002 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
13003 let grid = read_plane(
13004 dec,
13005 cdfs,
13006 TxbSet::Chroma4,
13007 &scan4,
13008 plane_idx,
13009 cu_around[plane_idx],
13010 m.mode,
13011 m.uv_predict_mode,
13012 m.angle_delta_uv,
13013 cu_reach,
13014 plane,
13015 cu_x,
13016 cu_y,
13017 4,
13018 4,
13019 base_q_idx,
13020 m.alpha
13021 .zip(ac)
13022 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
13023 None,
13024 offset,
13025 m.smooth_neighbor_uv,
13026 fctx,
13027 )?;
13028 if span_x == 4 && span_y == 4 {
13029 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
13030 }
13031 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
13032 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
13033 last[plane_idx - 1] = grid;
13034 }
13035 }
13036 }
13037 let [ug, vg] = last;
13038 (ug, vg)
13039 } else if chroma_tiled {
13040 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
13041 if chroma_422_pair_wide || chroma_422_oob {
13042 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
13043 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
13044 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
13045 // see above). For the 4-wide strip the units tile the PAIR's
13046 // plane, stepping from the floored anchor.
13047 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
13048 } else {
13049 match (chroma_w, chroma_h) {
13050 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
13051 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
13052 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
13053 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
13054 // through the square reader like every other square chroma unit.
13055 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
13056 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
13057 _ => unreachable!("chroma_tiled"),
13058 }
13059 };
13060 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
13061 // frame's square chroma units count it.
13062 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13063 hit!(CHROMA422_SQUARE_HITS);
13064 }
13065 if chroma_422_pair_wide {
13066 hit!(CHROMA422_PAIR_WIDE_HITS);
13067 }
13068 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
13069 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
13070 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
13071 // the pinned Release oracle), so its txb_skip rows always carry the
13072 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
13073 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
13074 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
13075 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
13076 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
13077 // mode-indexed default, the same rule the unsplit arm below applies.
13078 let default_tx = if uw.max(uh) >= 32 {
13079 TxType::DctDct
13080 } else {
13081 default_intra_tx_type(m.uv_predict_mode as u8)
13082 };
13083 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
13084 for plane_idx in 1..=2 {
13085 for cu_row in 0..nh {
13086 for cu_col in 0..nw {
13087 let luma_span_x = uw << ss_x(fctx);
13088 let luma_span_y = uh << ss_y(fctx);
13089 let cu_mi = (
13090 mi_r + cu_row * (luma_span_y / MI),
13091 if chroma_422_pair_wide {
13092 mi_c & !1
13093 } else {
13094 mi_c
13095 } + cu_col * (luma_span_x / MI),
13096 );
13097 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
13098 // chroma context per chroma cell
13099 // ([`Neighbours::around_mi_422_chroma`], the block-8
13100 // rule) -- the plain rect walk samples one chroma cell
13101 // twice at ss_x 1. Every pre-existing shape keeps its own
13102 // walk.
13103 // lane-av1422mi24: the plain rect walk's double-count
13104 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
13105 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
13106 // read its above dc votes twice and its U dc_sign one
13107 // ctx row high (t422 frame 1). Route every ss (1,0)
13108 // unit through the every-second-above-cell sampling;
13109 // 4:2:0/4:4:4 keep the plain walk verbatim.
13110 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
13111 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
13112 } else {
13113 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
13114 };
13115 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
13116 let cfl = m.alpha.map(|(au, av)| {
13117 let alpha = if plane_idx == 1 { au } else { av };
13118 (
13119 alpha,
13120 if chroma_422_pair_wide {
13121 // The unit's co-located luma is the PAIR's
13122 // 8-px-wide band at the floored mi column.
13123 cfl_src_rect(
13124 (mi_c & !1) * MI + cu_col * luma_span_x,
13125 py + cu_row * luma_span_y,
13126 luma_span_x,
13127 luma_span_y,
13128 )
13129 } else {
13130 cfl_src_rect(
13131 px + cu_col * luma_span_x,
13132 py + cu_row * luma_span_y,
13133 luma_span_x,
13134 luma_span_y,
13135 )
13136 },
13137 )
13138 });
13139 // lane-av1-422kf: the palette colour map is consumed per
13140 // unit here like every other chroma arm (`av1_visit_palette`
13141 // feeds the whole plane block; window it to this unit).
13142 // Without this the square chroma rows decoded a uv-palette
13143 // strip's chroma as plain DC (class same-symbols-silent-
13144 // prediction: the rng stayed in sync, only the prediction
13145 // was dropped).
13146 if let Some((ub, vb)) = &m.palette_uv {
13147 let buf = if plane_idx == 1 { ub } else { vb };
13148 set_palette_pred(
13149 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
13150 fctx,
13151 );
13152 }
13153 // libaom computes `has_top_right` PER TRANSFORM UNIT (defined
13154 // reconintra.c:196, called from `av1_build_intra_predictors` at
13155 // reconintra.c:1847 with the txb walk's own
13156 // `blk_col`/`blk_row`), never per block: the
13157 // `row_off == 0` arm asks `col_off + top_right_count_unit
13158 // < plane_bw_unit`, so the FIRST unit of a 2-wide chroma
13159 // grid reads its above-right out of the already-reconstructed
13160 // block ABOVE even when the block's own right edge is the
13161 // frame's. Passing this walk's block-level `reach` gave
13162 // every unit the same answer, and `PlaneBuf::edges`
13163 // (decode.rs:20840) truncates the above row at
13164 // `own_across` when `above_right` is false -- so a
13165 // directional unit whose angle is below 90
13166 // (`need_right`, intra.rs:546) predicted with a 32-sample
13167 // above row where libaom used 64.
13168 // MEASURED on `fixtures/r512_rect2x1_1x2_444.obu`
13169 // (4:4:4 8-bit 256x256, one frame): frame 0 plane U 130
13170 // samples and plane V 30 samples wrong, every one of them
13171 // in the right 6 columns of the `cu=(0,0)` unit at
13172 // `mi=(48,48)` `px=(192,192)` -- the unit whose above-right
13173 // the block reach denied. Row0 and col0 of the prediction
13174 // matched the oracle exactly and the prediction SUM did
13175 // not (172662 vs 171512 on U, 125978 vs 126008 on V), so
13176 // the residual read is bit-identical and the divergence is
13177 // prediction-side, not entropy. Gate:
13178 // `a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach`.
13179 let cu_reach = tu_reach_rect(
13180 bw,
13181 bh,
13182 (cu_col * uw) << ss_x(fctx),
13183 (cu_row * uh) << ss_y(fctx),
13184 uw << ss_x(fctx),
13185 uh << ss_y(fctx),
13186 reach,
13187 px,
13188 py,
13189 y.width,
13190 y.height,
13191 fctx,
13192 );
13193 if cu_reach.above_right != reach.above_right
13194 || cu_reach.below_left != reach.below_left
13195 {
13196 hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS);
13197 }
13198 if nw * nh > 1 {
13199 match (nw, nh) {
13200 (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS),
13201 (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS),
13202 _ => hit!(RECT_TILED_CHROMA_NXN_HITS),
13203 }
13204 }
13205 // 32x32 does not fit read_coeffs_rect's scratch (768). The
13206 // square reader is the path every other 32x32 chroma unit uses.
13207 let levels = if uw == uh {
13208 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
13209 read_plane(
13210 dec,
13211 cdfs,
13212 set,
13213 scan,
13214 plane_idx,
13215 cu_around[plane_idx],
13216 m.mode,
13217 m.uv_predict_mode,
13218 m.angle_delta_uv,
13219 cu_reach,
13220 plane,
13221 cu_x,
13222 cu_y,
13223 uw,
13224 uw,
13225 base_q_idx,
13226 cfl,
13227 None,
13228 bigger.then_some(3),
13229 m.smooth_neighbor_uv,
13230 fctx,
13231 )?
13232 } else {
13233 let skip_ctx = usize::from(cu_around[plane_idx].0)
13234 + usize::from(cu_around[plane_idx].1)
13235 + usize::from(bigger) * 3;
13236 let mut coding = cdfs.txb(set, m.uv_predict_mode);
13237 let (levels, tx_type) = read_coeffs_rect(
13238 dec,
13239 &mut coding,
13240 scan,
13241 uw,
13242 uh,
13243 skip_ctx,
13244 dc_sign_ctx(cu_around[plane_idx].2),
13245 default_tx,
13246 plane_idx,
13247 )?;
13248 let residual = dequant_and_inverse_typed_wh(
13249 &levels,
13250 uw,
13251 uh,
13252 crate::decode::bit_depth(fctx),
13253 block_q_idx(fctx),
13254 plane_q_delta(plane_idx, fctx).0,
13255 plane_q_delta(plane_idx, fctx).1,
13256 tx_type,
13257 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
13258 );
13259 push_intra_rect(
13260 plane_idx,
13261 cu_x,
13262 cu_y,
13263 uw,
13264 uh,
13265 m.uv_predict_mode,
13266 m.angle_delta_uv,
13267 cu_reach,
13268 &residual,
13269 cfl,
13270 None,
13271 m.smooth_neighbor_uv,
13272 fctx,
13273 );
13274 levels
13275 };
13276 neighbours.record_mi_chroma(
13277 cu_mi,
13278 luma_span_x,
13279 luma_span_y,
13280 plane_idx,
13281 &levels,
13282 );
13283 tiled_chroma_units.push((
13284 cu_mi,
13285 plane_idx,
13286 levels.clone(),
13287 luma_span_x,
13288 luma_span_y,
13289 ));
13290 last[plane_idx - 1] = levels;
13291 }
13292 }
13293 }
13294 (last[0].clone(), last[1].clone())
13295 } else {
13296 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
13297 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
13298 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
13299 // so only the 16x8/8x16 pair takes the mode-indexed default.
13300 let default_tx = if chroma_w.max(chroma_h) >= 32 {
13301 TxType::DctDct
13302 } else {
13303 default_intra_tx_type(m.uv_predict_mode as u8)
13304 };
13305 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
13306 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
13307 // counts every chroma column's whole-unit dc sign twice (the t422
13308 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
13309 // row high). Luma keeps the per-mi gather; the two chroma planes
13310 // take [`Neighbours::around_mi_422_chroma`]'s every-second
13311 // above-cell sampling, like every other 4:2:2 chroma gather.
13312 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
13313 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13314 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
13315 around[1] = c[1];
13316 around[2] = c[2];
13317 }
13318 let mut grids: Vec<Grid> = Vec::with_capacity(2);
13319 for plane_idx in 1..=2 {
13320 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
13321 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
13322 let (levels, tx_type) = read_coeffs_rect(
13323 dec,
13324 &mut coding,
13325 chroma_scan,
13326 chroma_w,
13327 chroma_h,
13328 skip_ctx,
13329 dc_sign_ctx(around[plane_idx].2),
13330 default_tx,
13331 plane_idx,
13332 )?;
13333 // The same delta_q proof the unsplit rect64 path records
13334 // (lane-rectsplit r4: lifting the split-transform refusal moved
13335 // superblock strips onto this path, so only counting there would
13336 // leave the delta_q gate's counter silent for them).
13337 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
13338 hit!(RECT64_QIDX_DRIFT_HITS);
13339 }
13340 let residual = dequant_and_inverse_typed_wh(
13341 &levels,
13342 chroma_w,
13343 chroma_h,
13344 crate::decode::bit_depth(fctx),
13345 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
13346 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
13347 // reading `current_q_idx` here dropped the segment feature
13348 // that every other dequant site applies (class
13349 // `parsed-then-discarded`).
13350 block_q_idx(fctx),
13351 plane_q_delta(plane_idx, fctx).0,
13352 plane_q_delta(plane_idx, fctx).1,
13353 tx_type,
13354 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
13355 );
13356 let cfl = m
13357 .alpha
13358 .zip(ac)
13359 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
13360 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
13361 if let Some((ub, vb)) = &m.palette_uv {
13362 let buf = if plane_idx == 1 { ub } else { vb };
13363 set_palette_pred(buf.clone(), fctx);
13364 }
13365 push_intra_rect(
13366 plane_idx,
13367 cpx,
13368 cpy,
13369 chroma_w,
13370 chroma_h,
13371 m.uv_predict_mode,
13372 m.angle_delta_uv,
13373 reach,
13374 &residual,
13375 cfl,
13376 None,
13377 m.smooth_neighbor_uv,
13378 fctx,
13379 );
13380 grids.push(levels);
13381 }
13382 let mut it = grids.into_iter();
13383 (it.next().unwrap(), it.next().unwrap())
13384 };
13385 neighbours.record_split_luma_rect_mi(
13386 at_mi,
13387 bw,
13388 bh,
13389 m.mode,
13390 m.uv_predict_mode,
13391 [&u_grid, &v_grid],
13392 );
13393 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
13394 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
13395 }
13396 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
13397 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
13398 }
13399 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
13400 neighbours.fill_lf_grid_rect(
13401 (mi_r, mi_c),
13402 bw / MI,
13403 bh / MI,
13404 tx_w as u8,
13405 tx_h as u8,
13406 0,
13407 fctx,
13408 );
13409 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13410 let (rng, _) = dec.debug_state();
13411 eprintln!(
13412 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
13413 tx={tx_w}x{tx_h} rng={rng}"
13414 );
13415 }
13416 Ok(())
13417}
13418
13419/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
13420/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
13421/// because it predicts squares only. Every pixel here goes through the rect
13422/// machinery the key-frame paths already prove: [`decode_rect_split`], which
13423/// at `depth == 0` is the unsplit strip as a single transform unit and
13424/// beyond it the per-unit walk of [`depth_to_tx_wh`].
13425///
13426/// What is genuinely different from [`decode_block_rect`] is the mode
13427/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
13428/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
13429/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
13430/// intra-in-inter arm's own reads at the rect footprint, including its
13431/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
13432/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
13433/// square and this arm) and a nonzero luma angle delta refused by name.
13434///
13435/// The strip's own neighbour records (luma per transform unit, chroma, skip
13436/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
13437/// inter-side bands and the mi map.
13438#[allow(clippy::too_many_arguments)]
13439/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
13440/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
13441/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
13442/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
13443/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
13444/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
13445/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
13446/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
13447/// table here rather than a shift of `bw.min(bh)`.
13448fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
13449 Some(match (bw.min(bh), bw.max(bh)) {
13450 (8, 16) => (1usize, 1usize),
13451 (16, 32) => (2, 2),
13452 (32, 64) => (3, 3),
13453 (8, 32) => (1, 2),
13454 (16, 64) => (2, 3),
13455 _ => return None,
13456 })
13457}
13458
13459/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
13460/// block path"): the shapes that can reach that arm, enumerated against the
13461/// MEASURED domain of the inter block path
13462/// ([`INTER_BLOCK_SHAPES`], the census the gate
13463/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
13464/// fills from three real streams).
13465///
13466/// [`decode_intra_rect_in_inter`] is called from one site, under
13467/// `write_w != side || write_h != side`, and only after two earlier arms have
13468/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
13469/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
13470/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
13471/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
13472/// and each of those has a row, so the refusal names a shape no measured
13473/// stream can present.
13474#[test]
13475fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
13476 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
13477 // names that string exactly (placeholders included) and pins its guard
13478 // site. The enumeration below establishes the shape domain; on its own it
13479 // never said WHICH string the domain was about, so under a real function
13480 // boundary -- rather than a window that ran into the next test -- the row
13481 // read as unanchored.
13482 const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)";
13483 assert!(
13484 include_str!("decode.rs").contains(REFUSAL),
13485 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
13486 );
13487 let mut checked = 0;
13488 for &(side, w, h) in &INTER_BLOCK_SHAPES {
13489 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
13490 continue;
13491 }
13492 assert!(
13493 intra_in_inter_size_row(w, h).is_some(),
13494 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
13495 the \"no size-group/tx-category row\" refusal"
13496 );
13497 checked += 1;
13498 }
13499 assert_eq!(
13500 checked, 10,
13501 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
13502 lookup, not the 10 this claim was measured over"
13503 );
13504}
13505
13506/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
13507/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
13508/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
13509/// matched before the square arm's `log2` shortcut).
13510///
13511/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
13512/// row here"; the enumeration below is what proves no conformant block can
13513/// reach it.
13514pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
13515 Some(match (write_w, write_h) {
13516 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
13517 // below maps 128 to row 4 (BLOCK_16X32).
13518 (64, 128) => 14,
13519 (128, 64) => 15,
13520 (128, 128) => 16,
13521 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
13522 (16, 32) => 4,
13523 (32, 16) => 5,
13524 (32, 64) => 6,
13525 (64, 32) => 7,
13526 (8, 32) => 8,
13527 (32, 8) => 9,
13528 (16, 64) => 10,
13529 (64, 16) => 11,
13530 // lane-inter4 r3: the 16x16-level rect inter leaves.
13531 (8, 16) => 12,
13532 (16, 8) => 13,
13533 _ => return None,
13534 })
13535}
13536
13537/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
13538/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
13539/// `block_size_wide`/`block_size_high`).
13540#[cfg(test)]
13541const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
13542 (4, 4),
13543 (4, 8),
13544 (8, 4),
13545 (8, 8),
13546 (8, 16),
13547 (16, 8),
13548 (16, 16),
13549 (16, 32),
13550 (32, 16),
13551 (32, 32),
13552 (32, 64),
13553 (64, 32),
13554 (64, 64),
13555 (64, 128),
13556 (128, 64),
13557 (128, 128),
13558 (4, 16),
13559 (16, 4),
13560 (8, 32),
13561 (32, 8),
13562 (16, 64),
13563 (64, 16),
13564];
13565
13566/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
13567/// shape with no CDF row here" names a shape no conformant stream can present.
13568///
13569/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
13570/// whose `write_w.min(write_h) >= 8` clause is libaom's
13571/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
13572/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
13573/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
13574/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
13575/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
13576/// clause rejects before the lookup.
13577#[test]
13578fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
13579 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
13580 // names it and pins its guard site.
13581 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
13582 assert!(
13583 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
13584 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
13585 );
13586 let mut rows = std::collections::BTreeSet::new();
13587 let mut excluded = 0;
13588 for (w, h) in BLOCK_SIZES_ALL_WH {
13589 if w.min(h) < 8 {
13590 excluded += 1;
13591 assert!(
13592 w == 4 || h == 4,
13593 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
13594 );
13595 continue;
13596 }
13597 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
13598 panic!(
13599 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
13600 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
13601 )
13602 });
13603 assert!(
13604 row < 17,
13605 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
13606 );
13607 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
13608 }
13609 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
13610 assert_eq!(
13611 rows.len(),
13612 17,
13613 "17 eligible footprints must fill all 17 rows of the motion_mode table"
13614 );
13615}
13616
13617/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
13618/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
13619/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
13620/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
13621/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
13622/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
13623/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
13624/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
13625#[test]
13626fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
13627 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
13628 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
13629 let ss10_invalid: &[(&str, bool)] = &[
13630 ("4x4", false),
13631 ("4x8", true),
13632 ("8x4", false),
13633 ("8x8", false),
13634 ("8x16", true),
13635 ("16x8", false),
13636 ("16x16", false),
13637 ("16x32", true),
13638 ("32x16", false),
13639 ("32x32", false),
13640 ("32x64", true),
13641 ("64x32", false),
13642 ("64x64", false),
13643 ("64x128", true),
13644 ("128x64", false),
13645 ("128x128", false),
13646 ("4x16", true),
13647 ("16x4", false),
13648 ("8x32", true),
13649 ("32x8", false),
13650 ("16x64", true),
13651 ("64x16", false),
13652 ];
13653 for (footprint, invalid10) in ss10_invalid {
13654 let (w, h) = footprint.split_once('x').unwrap();
13655 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
13656 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
13657 // valid because a (2, 4) plane area rounds UP to the 4x4 read
13658 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
13659 // [`decode_rect_split`] at all.
13660 if (bw, bh) == (4, 4) {
13661 continue;
13662 }
13663 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
13664 for (ss_x, ss_y) in [(false, false), (true, true)] {
13665 assert!(
13666 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
13667 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
13668 );
13669 }
13670 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
13671 // BLOCK_INVALID column, anchored at the floored mi column.
13672 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
13673 assert_eq!(
13674 pair.is_some(),
13675 *invalid10 && bw == 4,
13676 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
13677 );
13678 if let Some((block_w, block_h, x, ctx_col)) = pair {
13679 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
13680 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
13681 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
13682 // An even-column strip anchors at its own cell.
13683 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
13684 Some((_, _, x, c)) => (x, c),
13685 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
13686 };
13687 assert_eq!(
13688 (x_even, col_even),
13689 (12, 6),
13690 "even column keeps its own cell"
13691 );
13692 }
13693 }
13694 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
13695 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
13696 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
13697 for (bw, bh) in [
13698 (8usize, 16),
13699 (16, 32),
13700 (32, 64),
13701 (64, 128),
13702 (8, 32),
13703 (16, 64),
13704 ] {
13705 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
13706 }
13707}
13708
13709fn decode_intra_rect_in_inter(
13710 dec: &mut SymbolDecoder,
13711 cdfs: &mut Cdfs,
13712 neighbours: &mut Neighbours,
13713 at: (usize, usize),
13714 bw: usize,
13715 bh: usize,
13716 skip: bool,
13717 allow_screen_content_tools: bool,
13718 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
13719 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
13720 strip16: Option<(bool, bool)>,
13721 y: &mut PlaneBuf<'static>,
13722 u: &mut PlaneBuf<'static>,
13723 v: &mut PlaneBuf<'static>,
13724 base_q_idx: u8,
13725 fctx: &crate::decode::FrameCtx,
13726) -> Result<()> {
13727 // `at` is in MI units (the inter path's own unit since lane-inter4);
13728 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
13729 // below are still keyed by.
13730 let (mi_r, mi_c) = at;
13731 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
13732 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
13733 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
13734 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
13735 // finding -- the category is NOT the same for every strip size).
13736 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
13737 // it is refused by name rather than read from the wrong CDF row.
13738 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
13739 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
13740 // tx-depth category is 1 -- but nothing here has to know either, because
13741 // the strip decodes through the very body the KEY FRAME path proves for
13742 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
13743 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
13744 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
13745 // inter-frame difference is the mode-info read, which
13746 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
13747 // `y_mode[0]` plus the `skip` this caller already read.
13748 if let Some((horz, has_chroma)) = strip16 {
13749 // lane-t900 r22: the screen-content refusal here was STALE (class
13750 // stale-premise): [`decode_rect4_16_strip`] takes
13751 // `allow_screen_content_tools` and reads the whole palette syntax
13752 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
13753 // pair) -- the key frame proves that body. Lifted with the 10-bit
13754 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
13755 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
13756 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
13757 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
13758 let res = decode_rect4_16_strip(
13759 dec,
13760 cdfs,
13761 neighbours,
13762 (mi_r, mi_c),
13763 horz,
13764 has_chroma,
13765 // The inter strips of the same partition publish their own
13766 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
13767 // has nothing to add here.
13768 None,
13769 y,
13770 u,
13771 v,
13772 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13773 allow_screen_content_tools,
13774 base_q_idx,
13775 fctx.tx_select_inter.with(std::cell::Cell::get),
13776 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13777 fctx,
13778 );
13779 fctx.intra_in_inter_mode.with(|c| c.set(None));
13780 let (mode, uv, (tx_w, tx_h)) = res?;
13781 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
13782 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
13783 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
13784 // block of an inter frame, intra ones included, and
13785 // `txfm_partition_update` for the var-tx context. The key-frame body
13786 // writes neither (a key frame has no var-tx tree and its own readers
13787 // use the deblock grid), so the block AFTER this strip read a stale
13788 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
13789 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
13790 // 16x16 row.
13791 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13792 for i in 0..bw / MI {
13793 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13794 *cell = tx_w as u8;
13795 }
13796 }
13797 for i in 0..bh / MI {
13798 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13799 *cell = tx_h as u8;
13800 }
13801 }
13802 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
13803 // coarse 16-px cell holds one entry for the whole 16x16 and the last
13804 // block to write it wins).
13805 neighbours.above_mode[c] = mode;
13806 neighbours.left_mode[r] = mode;
13807 if let Some(uvm) = uv {
13808 neighbours.above_uv_mode[c] = uvm;
13809 neighbours.left_uv_mode[r] = uvm;
13810 }
13811 neighbours.above_side[c] = bw;
13812 neighbours.left_side[r] = bh;
13813 if crate::envflags::env_flag!("EC_INTRA16X4") {
13814 eprintln!(
13815 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
13816 mi_c * MI,
13817 mi_r * MI
13818 );
13819 }
13820 hit_do! {
13821 INTRA16X4_IN_INTER_HITS.with(|h| {
13822 let mut v = h.get();
13823 v[usize::from(!horz)] += 1;
13824 v[2] += usize::from(has_chroma);
13825 h.set(v);
13826 });
13827 }
13828 return Ok(());
13829 }
13830 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
13831 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
13832 // puts BLOCK_128X64/64X128/128X128 in group 3 and
13833 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
13834 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
13835 // block decodes through the very body the KEY FRAME path proves for this
13836 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
13837 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
13838 // `Reach` rule and the frame-edge write clip). The only inter-frame
13839 // differences live inside that body: the mode-info read
13840 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
13841 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
13842 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
13843 // palette (>64) do not exist at this size and are refused by name there.
13844 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
13845 // `intra128_in_inter_witness2.obu` (gate
13846 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
13847 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
13848 // all 15 frames, so the hits are counted out of exact frames (class
13849 // `counter-from-refused-stream`). What r16/r17 could not find, and what
13850 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
13851 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
13852 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
13853 // where the frame EDGE forces it: a partial last superblock row has
13854 // `has_rows128 == false`, so the 128x64 top half is implied, and a
13855 // partial last column implies the 64x128 left half. Put content no
13856 // reference holds (a fresh smooth ramp) in exactly those two bands of an
13857 // inter frame and the encoder codes those forced halves INTRA.
13858 if bw.max(bh) == 128 {
13859 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
13860 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
13861 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
13862 // palette_syntax`), so a 128-root half consumes no palette syntax and
13863 // a screen-content frame's half is syntactically identical to the
13864 // non-screen one this arm already decodes byte-exact.
13865 if coeff_trace_on() {
13866 // lane-t900 r16: which decode-order frame this arm fires in --
13867 // interleaved with the `EC_COEFF_FRAME` markers, this is what
13868 // proves the hit is counted out of a frame that compares exact
13869 // (class `counter-from-refused-stream`).
13870 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
13871 }
13872 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
13873 let res = decode_block_128rect(
13874 dec,
13875 cdfs,
13876 neighbours,
13877 (r, c),
13878 bw,
13879 bh,
13880 y,
13881 u,
13882 v,
13883 base_q_idx,
13884 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13885 allow_screen_content_tools,
13886 fctx.tx_select_inter.with(std::cell::Cell::get),
13887 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13888 fctx,
13889 );
13890 fctx.intra_in_inter_mode.with(|c| c.set(None));
13891 return res;
13892 }
13893 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
13894 if crate::envflags::env_flag!("EC_OBMCREC") {
13895 eprintln!(
13896 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
13897 );
13898 }
13899 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
13900 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
13901 // can arrive here are enumerated against the measured block-shape
13902 // census ([`INTER_BLOCK_SHAPES`]) by
13903 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
13904 // -- every one of them has a row, so this arm names a shape no stream
13905 // has been able to present.
13906 return Err(unsupported(format!(
13907 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13908 )));
13909 };
13910 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13911 // screen-content frame ("palette syntax is consumed for square blocks
13912 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13913 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13914 // it, while the 2:1 reader inlined further down now codes the same syntax
13915 // itself. A real `--tune-content=screen` inter stream reached this refusal
13916 // on 8x16 / 16x8 strips (gate
13917 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13918 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13919 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13920 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13921 // luma/chroma transform tables, the per-unit split walk and the strip's
13922 // own neighbour records). The ONLY difference on an inter frame is the
13923 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13924 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13925 // this caller already read. `tx_cat` above is the same category those
13926 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13927 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13928 if bw.max(bh) == 4 * bw.min(bh) {
13929 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13930 fctx.intra_in_inter_mode
13931 .with(|c| c.set(Some((size_group, skip))));
13932 let res = if bw.max(bh) == 64 {
13933 decode_block_rect64(
13934 dec,
13935 cdfs,
13936 neighbours,
13937 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13938 bw,
13939 bh,
13940 y,
13941 u,
13942 v,
13943 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13944 allow_screen_content_tools,
13945 base_q_idx,
13946 fctx.tx_select_inter.with(std::cell::Cell::get),
13947 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13948 fctx,
13949 )
13950 } else {
13951 decode_block_rect4(
13952 dec,
13953 cdfs,
13954 neighbours,
13955 (mi_r, mi_c),
13956 bw,
13957 bh,
13958 None,
13959 y,
13960 u,
13961 v,
13962 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13963 allow_screen_content_tools,
13964 base_q_idx,
13965 fctx.tx_select_inter.with(std::cell::Cell::get),
13966 fctx,
13967 )
13968 .map(|_| ())
13969 };
13970 fctx.intra_in_inter_mode.with(|c| c.set(None));
13971 res?;
13972 let shape = match (bw, bh) {
13973 (64, 16) => 0,
13974 (16, 64) => 1,
13975 (32, 8) => 2,
13976 _ => 3,
13977 };
13978 hit_do! {
13979 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13980 let mut v = h.get();
13981 v[shape] += 1;
13982 h.set(v);
13983 });
13984 }
13985 return Ok(());
13986 }
13987 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13988 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13989 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13990 // own, so a cross-decoder bisection could only see the block's first
13991 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13992 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13993 if step_trace {
13994 eprintln!(
13995 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13996 dec.debug_state().0
13997 );
13998 }
13999 if mode >= 13 {
14000 return Err(unsupported(
14001 "an intra mode this decoder does not code (round 2)",
14002 ));
14003 }
14004 // lane-angleinter (merged on main for the square intra-in-inter arm):
14005 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
14006 // directional predictor; this arm refused a nonzero one before the merge.
14007 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
14008 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
14009 } else {
14010 0
14011 };
14012 if angle_delta_y != 0 {
14013 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
14014 }
14015 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
14016 // superblock-level strip reads the no-CFL alphabet -- the same split
14017 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
14018 //
14019 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
14020 // (libaom `decodemv.c:933`).
14021 let has_chroma = !mono(fctx);
14022 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
14023 let uv_mode = if !has_chroma {
14024 DC_PRED
14025 } else if cfl_allowed {
14026 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
14027 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
14028 } else {
14029 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
14030 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
14031 };
14032 if step_trace {
14033 eprintln!(
14034 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
14035 u8::from(cfl_allowed),
14036 dec.debug_state().0
14037 );
14038 }
14039 if (9..=12).contains(&uv_mode) {
14040 hit!(SMOOTH_UV_HITS);
14041 }
14042 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
14043 Some(read_cfl_alphas(dec, cdfs))
14044 } else {
14045 None
14046 };
14047 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14048 DC_PRED
14049 } else {
14050 uv_mode
14051 };
14052 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
14053 hit!(DIRECTIONAL_UV_HITS);
14054 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
14055 } else {
14056 0
14057 };
14058 if angle_delta_uv != 0 {
14059 hit!(UV_ANGLE_DELTA_HITS);
14060 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
14061 }
14062 // `read_palette_mode_info` (spec 5.11.13), in the position
14063 // `read_intra_block_mode_info` writes it: after the chroma mode and
14064 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
14065 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
14066 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
14067 // skipping the syntax here desynced the tile at the strip's own symbol.
14068 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
14069 // context and colour cache at its own mi position, and the two
14070 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
14071 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
14072 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
14073 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
14074 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
14075 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
14076 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
14077 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
14078 let use_palette_y =
14079 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
14080 if use_palette_y {
14081 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
14082 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
14083 }
14084 // A 2:1 strip of at least 8x8 is always a chroma reference, so
14085 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
14086 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
14087 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
14088 let use_palette_uv = has_chroma
14089 && uv_mode == DC_PRED
14090 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
14091 if crate::envflags::env_flag!("EC_PALSYN") {
14092 eprintln!(
14093 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
14094 use_palette_y as i32,
14095 use_palette_uv as i32,
14096 dec.debug_state().0
14097 );
14098 }
14099 if use_palette_uv {
14100 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
14101 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
14102 palette_uv_pending = Some((n, u_colors, v_colors));
14103 }
14104 }
14105 // lane-fiinter (merged on main for the square intra-in-inter arm):
14106 // `read_filter_intra_mode_info` is the tail of
14107 // `read_intra_block_mode_info`, after the palette syntax (refused whole
14108 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
14109 // 2:1 strips with both sides <= 32 -- their own CDF rows
14110 // ([`filter_intra_size_class_rect`]).
14111 let mut filter_intra = None;
14112 if mode == DC_PRED
14113 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
14114 // `av1_filter_intra_allowed` excludes a palette-Y block.
14115 && palette_y_pending.is_none()
14116 && let Some(class) = filter_intra_size_class_rect(bw, bh)
14117 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
14118 {
14119 hit!(FILTER_INTRA_HITS);
14120 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
14121 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
14122 }
14123 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
14124 let palette_y = palette_y_pending.map(|(n, colors)| {
14125 let map = decode_color_index_map_wh(
14126 dec,
14127 cdfs,
14128 n,
14129 bw,
14130 bh,
14131 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
14132 false,
14133 );
14134 hit!(PALETTE_HITS);
14135 hit!(PALETTE_RECT_HITS);
14136 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
14137 PaletteY {
14138 size: n,
14139 colors,
14140 map,
14141 }
14142 });
14143 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
14144 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
14145 let on = palette_onscreen_uv(
14146 (bw, bh),
14147 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
14148 (cw, ch),
14149 (ss_x(fctx), ss_y(fctx)),
14150 );
14151 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
14152 hit!(PALETTE_UV_HITS);
14153 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
14154 PaletteUv {
14155 size: n,
14156 u_colors,
14157 v_colors,
14158 map,
14159 }
14160 });
14161 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
14162 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
14163 // chroma ones -- [`decode_block_rect`]'s own pair.
14164 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
14165 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
14166 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
14167 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
14168 // one exactly as [`decode_leaf8`] already does (class
14169 // context-read-from-one-cell).
14170 let coarse_pair = neighbours.modes_above_left(r, c);
14171 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
14172 if (nb_above_mode, nb_left_mode) != coarse_pair {
14173 hit!(EDGE_FILTER_MI_FIX_HITS);
14174 }
14175 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14176 if smooth_neighbor {
14177 hit!(SMOOTH_LUMA_HITS);
14178 }
14179 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
14180 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
14181 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
14182 // an inter frame codes no depth symbol either (`xd->lossless` is per
14183 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
14184 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
14185 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
14186 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
14187 let d = match tx_cat {
14188 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
14189 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
14190 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
14191 };
14192 if step_trace {
14193 eprintln!(
14194 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
14195 dec.debug_state().0
14196 );
14197 }
14198 d
14199 } else {
14200 0
14201 };
14202 if depth != 0 || lossless(fctx) {
14203 hit!(TX_DEPTH_HITS);
14204 // lane-intrasplit r1: a split intra strip in an inter frame walks the
14205 // key frame's own per-TU path ([`decode_rect_split`] below); what was
14206 // wrong when this refusal was written was the depth SYMBOL, not the walk.
14207 hit_do! {
14208 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
14209 let mut v = h.get();
14210 v[depth.min(2)] += 1;
14211 h.set(v);
14212 });
14213 }
14214 }
14215 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
14216 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
14217 // the two are indistinguishable when the diagnostic fires on splits alone.
14218 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
14219 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
14220 }
14221 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14222 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
14223 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
14224 // of an inter frame, intra ones included -- with the skip term 0 it
14225 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
14226 // and `left_txfm_context` to `tx_size_high` over its height. This strip
14227 // wrote neither, so the next block's var-tx `txfm_partition` context read
14228 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
14229 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
14230 // mi(16,0) and desyncing the tile at that symbol.
14231 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
14232 let modes = RectStripModes {
14233 skip,
14234 mode,
14235 angle_delta_y,
14236 uv_predict_mode,
14237 angle_delta_uv,
14238 alpha,
14239 filter_intra,
14240 smooth_neighbor,
14241 smooth_neighbor_uv,
14242 palette_y: palette_y
14243 .as_ref()
14244 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
14245 palette_uv: palette_uv.as_ref().map(|p| {
14246 (
14247 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14248 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14249 )
14250 }),
14251 };
14252 decode_rect_split(
14253 dec,
14254 cdfs,
14255 neighbours,
14256 (mi_r, mi_c),
14257 bw,
14258 bh,
14259 tx_w,
14260 tx_h,
14261 &modes,
14262 y,
14263 u,
14264 v,
14265 base_q_idx,
14266 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
14267 fctx,
14268 )?;
14269 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
14270 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
14271 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
14272 // left column over its height. This arm wrote neither before lane-intrasplit
14273 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
14274 // context across the strip's footprint.
14275 for i in 0..bw / MI {
14276 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
14277 *cell = tx_w as u8;
14278 }
14279 }
14280 for i in 0..bh / MI {
14281 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
14282 *cell = tx_h as u8;
14283 }
14284 }
14285 // The strip's own palette state into the mi-granular neighbour bands, so
14286 // the next block's colour cache and `palette_y_mode` context are libaom's.
14287 record_strip_palette(
14288 neighbours,
14289 (mi_r, mi_c),
14290 bw,
14291 bh,
14292 palette_y.as_ref().map_or(0, |p| p.size),
14293 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
14294 palette_uv.as_ref().map_or(0, |p| p.size),
14295 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
14296 );
14297 let class = match bw.max(bh) {
14298 64 => 0,
14299 32 => 1,
14300 _ => 2,
14301 };
14302 hit_do! {
14303 INTRA_RECT_IN_INTER_HITS.with(|h| {
14304 let mut v = h.get();
14305 v[class] += 1;
14306 h.set(v);
14307 });
14308 }
14309 Ok(())
14310}
14311
14312/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
14313/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
14314///
14315/// libaom treats an intrabc block as INTER for everything except the mode-info
14316/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
14317/// (`blockd.h:373`), so
14318///
14319/// * `parse_decode_block` reads the transform size through the INTER var-tx
14320/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
14321/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
14322/// whose leaves publish their own resolved size back;
14323/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
14324/// frame's own pre-loop-filter reconstruction, at the coded block vector
14325/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
14326/// * `decode_token_recon_block`'s inter branch then reads one residual per
14327/// transform unit, through the INTER coefficient sets
14328/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
14329/// inheriting the colocated luma unit's coded `tx_type`.
14330///
14331/// Text order is libaom's: transform tree, prediction, luma residual, chroma
14332/// residual, bookkeeping. A skipped block codes no residual at all -- the
14333/// prediction is the reconstruction.
14334#[allow(clippy::too_many_arguments)]
14335fn decode_intrabc_rect(
14336 dec: &mut SymbolDecoder,
14337 cdfs: &mut Cdfs,
14338 neighbours: &mut Neighbours,
14339 (mi_r, mi_c): (usize, usize),
14340 (bw, bh): (usize, usize),
14341 skip: bool,
14342 (dv_row, dv_col): (i32, i32),
14343 y: &mut PlaneBuf<'static>,
14344 u: &mut PlaneBuf<'static>,
14345 v: &mut PlaneBuf<'static>,
14346 base_q_idx: u8,
14347 fctx: &crate::decode::FrameCtx,
14348) -> Result<()> {
14349 hit!(INTRABC_RECT_HITS);
14350 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
14351 let idx = usize::from(bh > bw);
14352 if skip {
14353 INTRABC_RECT_SKIPPED_HITS.with(|c| {
14354 let mut seen = c.get();
14355 seen[idx] += 1;
14356 c.set(seen);
14357 });
14358 } else {
14359 INTRABC_RECT_CODED_HITS.with(|c| {
14360 let mut seen = c.get();
14361 seen[idx] += 1;
14362 c.set(seen);
14363 });
14364 }
14365 let (px, py) = (mi_c * MI, mi_r * MI);
14366 // lane-whtshape: a LOSSLESS block's chroma plane block is
14367 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
14368 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
14369 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
14370 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
14371 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
14372 // walk below coded 2 units per plane where libaom codes 8.
14373 //
14374 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
14375 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
14376 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
14377 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
14378 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
14379 // the block at mi (92, 104) read all_zero=0 here against the oracle's
14380 // all_zero=1 -- the bit position forks there. Identical arithmetic at
14381 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
14382 // witness is the identity arm of this lane's gate.
14383 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14384 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
14385 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
14386 // shape this helper is called at, so the uv plane block is ONE unit --
14387 // the same call `decode_token_recon_block`'s own chroma loop makes.
14388 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14389 // lane-av1-intrabc r2: the square stride the proven INTER path uses
14390 // (`side`). The residual grids, the prediction windows AND
14391 // `TxParams::stride` are all laid out at it -- the block's own width
14392 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
14393 // exceeds the stride).
14394 let side = bw.max(bh);
14395 let cside = cw.max(ch);
14396 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
14397 // or bottom frame edge reads no transform-tree symbol for the units
14398 // outside it.
14399 let mi_cols = 2 * y.true_width.div_ceil(8);
14400 let mi_rows = 2 * y.true_height.div_ceil(8);
14401 let leaves = read_block_tx_size_rect(
14402 dec,
14403 cdfs,
14404 neighbours,
14405 (mi_r, mi_c),
14406 (bw, bh),
14407 (mi_cols, mi_rows),
14408 skip,
14409 fctx,
14410 )?;
14411 if leaves.is_some() {
14412 hit!(INTRABC_RECT_VARTX_HITS);
14413 }
14414 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
14415 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
14416 }
14417 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
14418 if crate::envflags::env_flag!("EC_IBCBLOCK") {
14419 eprintln!(
14420 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
14421 cw={cw} ch={ch} cside={cside} skip={skip}"
14422 );
14423 }
14424 // The whole-block prediction: `predict_inter_block` runs once, before any
14425 // coefficient is read. `flush_recon` first -- the source is this frame's
14426 // own reconstruction, including the writes this superblock has queued.
14427 flush_recon(fctx, y, u, v);
14428 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
14429 // reads it at the square stride, so re-lay it -- the same step the inter
14430 // path takes for its own square prediction buffer.
14431 let mut pred_y_dense = vec![0u16; bw * bh];
14432 mc::predict_with_filter(
14433 &y.data,
14434 y.width,
14435 y.true_width,
14436 y.true_height,
14437 mv_to_q4(px, dv_col, 0),
14438 mv_to_q4(py, dv_row, 0),
14439 bw,
14440 bh,
14441 mc::InterpFilterKind::Bilinear,
14442 &mut pred_y_dense,
14443 fctx,
14444 );
14445 let mut pred_y = vec![0u16; side * side];
14446 for row in 0..bh {
14447 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14448 }
14449 let mut pred_u_dense = vec![0u16; cw * ch];
14450 mc::predict_with_filter(
14451 &u.data,
14452 u.width,
14453 u.true_width,
14454 u.true_height,
14455 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14456 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14457 cw,
14458 ch,
14459 mc::InterpFilterKind::Bilinear,
14460 &mut pred_u_dense,
14461 fctx,
14462 );
14463 let mut pred_u = vec![0u16; cside * cside];
14464 for row in 0..ch {
14465 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14466 }
14467 let mut pred_v_dense = vec![0u16; cw * ch];
14468 mc::predict_with_filter(
14469 &v.data,
14470 v.width,
14471 v.true_width,
14472 v.true_height,
14473 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14474 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14475 cw,
14476 ch,
14477 mc::InterpFilterKind::Bilinear,
14478 &mut pred_v_dense,
14479 fctx,
14480 );
14481 let mut pred_v = vec![0u16; cside * cside];
14482 for row in 0..ch {
14483 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14484 }
14485 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14486 let luma_tx_type: TxType;
14487 let (luma_grid, u_grid, v_grid);
14488 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
14489 // kept so their per-4x4 slices can be re-stamped over the whole-block
14490 // record in the tail. `None` on every other arm.
14491 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
14492 if skip {
14493 // No residual syntax at all: the prediction IS the block.
14494 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
14495 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
14496 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
14497 push_mc_rect(
14498 0,
14499 px,
14500 py,
14501 side,
14502 bw,
14503 bh,
14504 Pred::Inline(&pred_y, side),
14505 &ZERO_RESIDUAL[..side * side],
14506 fctx,
14507 );
14508 push_mc_rect(
14509 1,
14510 cpx,
14511 cpy,
14512 cside,
14513 cw,
14514 ch,
14515 Pred::Inline(&pred_u, cside),
14516 &ZERO_RESIDUAL[..cside * cside],
14517 fctx,
14518 );
14519 push_mc_rect(
14520 2,
14521 cpx,
14522 cpy,
14523 cside,
14524 cw,
14525 ch,
14526 Pred::Inline(&pred_v, cside),
14527 &ZERO_RESIDUAL[..cside * cside],
14528 fctx,
14529 );
14530 if let Some(ls) = leaves.as_ref() {
14531 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
14532 // skip arm performs -- libaom `av1_reset_entropy_context`
14533 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
14534 // SKIPPED block zeroes its whole entropy-band footprint. This
14535 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
14536 // so a skipped lossless strip whose `leaves` resolved (every
14537 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
14538 // returns the 4x4 grid before it looks at `skip`) left the
14539 // PREVIOUS occupant's luma bands standing and the NEXT block's
14540 // partition parse diverged from libaom's: the 320x242 lossless
14541 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
14542 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
14543 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14544 for &(row, col, tw, th) in ls {
14545 neighbours.record_mi_luma_rect(
14546 (mi_r + row, mi_c + col),
14547 tw,
14548 th,
14549 &ZERO_RESIDUAL[..tw * th],
14550 );
14551 }
14552 }
14553 luma_tx_type = TxType::DctDct;
14554 luma_grid = Grid::Zero(side * side);
14555 u_grid = Grid::Zero(cside * cside);
14556 v_grid = Grid::Zero(cside * cside);
14557 } else {
14558 match leaves.as_ref() {
14559 None => {
14560 // One whole-block rectangular transform unit.
14561 // lane-av1422mi24: at ss (1,0) the chroma above span is
14562 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
14563 // the per-mi gather counts every chroma column's whole-unit
14564 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
14565 // strip's U dc_sign read ctx 1 where the oracle's cell sum
14566 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
14567 // chroma planes take
14568 // [`Neighbours::around_mi_422_chroma`]'s every-second
14569 // above-cell sampling, like every other 4:2:2 chroma gather.
14570 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14571 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14572 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14573 around[1] = c[1];
14574 around[2] = c[2];
14575 }
14576 let (grid, tx_type) = read_inter_plane_rect(
14577 dec,
14578 cdfs,
14579 rect_inter_luma_set(bw, bh, fctx)?,
14580 (bw, bh),
14581 side,
14582 0,
14583 around[0],
14584 0,
14585 y,
14586 px,
14587 py,
14588 Pred::Inline(&pred_y, side),
14589 None,
14590 None,
14591 fctx,
14592 )?;
14593 luma_tx_type = tx_type;
14594 luma_grid = embed_grid_stride(&grid, bw, bh, side);
14595 let (ug, _) = read_inter_plane_rect(
14596 dec,
14597 cdfs,
14598 rect_inter_chroma_set(cw, ch)?,
14599 (cw, ch),
14600 cside,
14601 1,
14602 around[1],
14603 0,
14604 u,
14605 cpx,
14606 cpy,
14607 Pred::Inline(&pred_u, cside),
14608 Some(luma_tx_type),
14609 None,
14610 fctx,
14611 )?;
14612 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14613 let (vg, _) = read_inter_plane_rect(
14614 dec,
14615 cdfs,
14616 rect_inter_chroma_set(cw, ch)?,
14617 (cw, ch),
14618 cside,
14619 2,
14620 around[2],
14621 0,
14622 v,
14623 cpx,
14624 cpy,
14625 Pred::Inline(&pred_v, cside),
14626 Some(luma_tx_type),
14627 None,
14628 fctx,
14629 )?;
14630 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14631 }
14632 Some(leaves) => {
14633 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
14634 // the split override to LUMA only, per leaf -- the step the
14635 // proven inter var-tx path applies right after its own residual
14636 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
14637 // leaf's own transform edges are never filtered.
14638 for &(row, col, tw, th) in leaves.iter() {
14639 neighbours.fill_lf_grid_leaf_luma(
14640 (mi_r + row, mi_c + col),
14641 tw / MI,
14642 th / MI,
14643 tw as u8,
14644 th as u8,
14645 );
14646 }
14647 // One residual per transform unit, in the order the tree coded
14648 // them; each unit reads its own neighbour-magnitude context off
14649 // the units already decoded before it, and every unit adds onto
14650 // its own window of the block's single prediction.
14651 let mut first_tx_type = TxType::DctDct;
14652 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
14653 let tu_mi = (mi_r + row, mi_c + col);
14654 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14655 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14656 let (tu_grid, tu_tx_type) = if tw == th {
14657 let scan = default_scan(tw.min(32));
14658 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14659 read_inter_plane(
14660 dec,
14661 cdfs,
14662 inter_txbset_for(tw, reduced),
14663 scan,
14664 0,
14665 neighbours.around_mi(tu_mi, tw)[0],
14666 0,
14667 y,
14668 tu_px,
14669 tu_py,
14670 tw,
14671 base_q_idx,
14672 tu_pred,
14673 None,
14674 Some(tu_skip_ctx),
14675 fctx,
14676 )?
14677 } else {
14678 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
14679 read_inter_plane_rect(
14680 dec,
14681 cdfs,
14682 rect_inter_luma_set(tw, th, fctx)?,
14683 (tw, th),
14684 side,
14685 0,
14686 neighbours.around_mi_rect(tu_mi, tw, th)[0],
14687 0,
14688 y,
14689 tu_px,
14690 tu_py,
14691 tu_pred,
14692 None,
14693 Some(tu_skip_ctx),
14694 fctx,
14695 )?
14696 };
14697 if idx == 0 {
14698 first_tx_type = tu_tx_type;
14699 }
14700 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14701 }
14702 // `av1_get_tx_type`'s chroma lookup lands on the colocated
14703 // LUMA unit, which for a split block is the top-left one.
14704 luma_tx_type = first_tx_type;
14705 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
14706 // `None` arm above -- the per-mi rect gather double-counts
14707 // each chroma column's whole-unit dc sign at ss (1,0).
14708 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14709 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14710 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14711 around[1] = c[1];
14712 around[2] = c[2];
14713 }
14714 if lossless(fctx) {
14715 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
14716 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
14717 // lossless block before it looks at a tree, `read_tx_mode`
14718 // already forced `ONLY_4X4` for the frame, and
14719 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
14720 // -- so this block's chroma plane block is a
14721 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
14722 // (`decode_token_recon_block`: every U unit, then every V
14723 // unit), not the single rect unit the two
14724 // `read_inter_plane_rect` calls below read. That single
14725 // 8x4 unit is what reached the lossless WHT with the wrong
14726 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
14727 // replaced). Same helper, same walk, as the inter 8x8 and
14728 // 128 paths.
14729 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
14730 let mut uo = vec![0i32; cside * cside];
14731 let mut vo = vec![0i32; cside * cside];
14732 read_inter_chroma_lossless(
14733 dec,
14734 cdfs,
14735 neighbours,
14736 u,
14737 v,
14738 Pred::Inline(&pred_u, cside),
14739 Pred::Inline(&pred_v, cside),
14740 (mi_r, mi_c),
14741 (cpx, cpy),
14742 (0, 0),
14743 (cw, ch),
14744 (cw, ch),
14745 cside,
14746 0,
14747 base_q_idx,
14748 &mut uo,
14749 &mut vo,
14750 fctx,
14751 )?;
14752 // The per-unit walk stamped every unit's own coefficient
14753 // context, but the whole-block `record_split_luma_rect_mi`
14754 // in the tail rewrites every chroma cell with ONE composed
14755 // state, which drops the per-unit DC signs and levels (class
14756 // `override-slot-on-one-arm` -- the same one
14757 // `decode_rect_split`'s `ll_chroma_units` replay exists
14758 // for). The grids are kept here and replayed AFTER that
14759 // record, from the same 4x4 slices, so the same states.
14760 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
14761 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
14762 ll_chroma = Some((uo, vo));
14763 luma_grid = Grid::Zero(side * side);
14764 } else {
14765 let (ug, _) = read_inter_plane_rect(
14766 dec,
14767 cdfs,
14768 rect_inter_chroma_set(cw, ch)?,
14769 (cw, ch),
14770 cside,
14771 1,
14772 around[1],
14773 0,
14774 u,
14775 cpx,
14776 cpy,
14777 Pred::Inline(&pred_u, cside),
14778 Some(luma_tx_type),
14779 None,
14780 fctx,
14781 )?;
14782 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14783 let (vg, _) = read_inter_plane_rect(
14784 dec,
14785 cdfs,
14786 rect_inter_chroma_set(cw, ch)?,
14787 (cw, ch),
14788 cside,
14789 2,
14790 around[2],
14791 0,
14792 v,
14793 cpx,
14794 cpy,
14795 Pred::Inline(&pred_v, cside),
14796 Some(luma_tx_type),
14797 None,
14798 fctx,
14799 )?;
14800 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14801 luma_grid = Grid::Zero(side * side);
14802 }
14803 }
14804 }
14805 }
14806 let _ = luma_tx_type;
14807 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
14808 // next block reads a neighbour mode, its own block size in both `TXFM`
14809 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
14810 // state (a stale entry would feed the next block's colour cache), and its
14811 // DV into the intrabc mi grid the next block's DV predictor reads.
14812 if leaves.is_some() {
14813 neighbours.record_split_luma_rect_mi(
14814 (mi_r, mi_c),
14815 bw,
14816 bh,
14817 DC_PRED,
14818 DC_PRED,
14819 [&u_grid, &v_grid],
14820 );
14821 } else {
14822 neighbours.record_rect_mi(
14823 (mi_r, mi_c),
14824 bw,
14825 bh,
14826 DC_PRED,
14827 DC_PRED,
14828 &[&luma_grid, &u_grid, &v_grid],
14829 );
14830 }
14831 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
14832 // the whole-block record above, so the NEXT block reads the per-unit DC
14833 // signs and levels libaom's plane-major walk left behind instead of one
14834 // composed state for the whole plane block.
14835 if let Some((uo, vo)) = ll_chroma {
14836 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
14837 for ur in 0..ch / 4 {
14838 for uc in 0..cw / 4 {
14839 let mut unit = Vec::with_capacity(16);
14840 for r in 0..4 {
14841 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
14842 }
14843 neighbours.record_mi_chroma(
14844 // lane-av1lm444loss-corr: the MI STEP between chroma
14845 // units is that same footprint expressed in luma mi
14846 // cells, `(4 << ss) / MI` -- which is exactly what
14847 // `decode_inter_block`'s reference `mu_chroma_units`
14848 // construction writes (decode.rs:43688,
14849 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
14850 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
14851 // this replaces is 4:2:0-only arithmetic that happens
14852 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
14853 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
14854 // SAME value, so 4:2:0 is unchanged by construction.
14855 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
14856 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
14857 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
14858 // The step therefore lands every replayed unit at 4x
14859 // its own mi row/column on a 4:4:4 lossless frame, and
14860 // the whole block's per-unit states are stamped over
14861 // cells that belong to other blocks (or to nothing).
14862 (
14863 mi_r + ur * ((4 << ss_y(fctx)) / MI),
14864 mi_c + uc * ((4 << ss_x(fctx)) / MI),
14865 ),
14866 4 << ss_x(fctx),
14867 4 << ss_y(fctx),
14868 plane_idx,
14869 &Grid::Own(unit),
14870 );
14871 }
14872 }
14873 }
14874 }
14875 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14876 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14877 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14878 // lane-av1oddheightfork3: `read_block_tx_size_rect` ran above, so the
14879 // bands are the tree's own per-leaf publication (libaom's var-tx branch
14880 // never calls `set_txfm_ctxs`) -- publishing the block's own size over
14881 // them here is the defect this call site carried.
14882 neighbours.fill_lf_grid_rect_after_vartx(
14883 (mi_r, mi_c),
14884 bw / MI,
14885 bh / MI,
14886 bw.min(64) as u8,
14887 bh.min(64) as u8,
14888 0,
14889 fctx,
14890 );
14891 record_intrabc_mi_rect(
14892 mi_r,
14893 mi_c,
14894 bw / MI,
14895 bh / MI,
14896 Some((dv_row, dv_col)),
14897 neighbours,
14898 fctx,
14899 );
14900 Ok(())
14901}
14902
14903/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
14904/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
14905/// `decode_block_128rect` refused by name before this port. libaom decodes
14906/// such a block through the INTER machinery (an intrabc block
14907/// `is_inter_block`): `predict_inter_block` copies the whole block from this
14908/// frame's own reconstruction at the integer block vector once, then
14909/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
14910/// per chunk every plane, luma units at the block's own resolved transform
14911/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
14912/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
14913/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
14914/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
14915/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14916/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14917#[allow(clippy::too_many_arguments)]
14918fn decode_intrabc_128rect(
14919 dec: &mut SymbolDecoder,
14920 cdfs: &mut Cdfs,
14921 neighbours: &mut Neighbours,
14922 (mi_r, mi_c): (usize, usize),
14923 (bw, bh): (usize, usize),
14924 skip: bool,
14925 (dv_row, dv_col): (i32, i32),
14926 y: &mut PlaneBuf<'static>,
14927 u: &mut PlaneBuf<'static>,
14928 v: &mut PlaneBuf<'static>,
14929 base_q_idx: u8,
14930 fctx: &crate::decode::FrameCtx,
14931) -> Result<()> {
14932 hit!(INTRABC_128RECT_HITS);
14933 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14934 let (rng, _) = dec.debug_state();
14935 eprintln!(
14936 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14937 );
14938 }
14939 let (px, py) = (mi_c * MI, mi_r * MI);
14940 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14941 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14942 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14943 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14944 // `/2` origin and extent made the prediction window half as tall as
14945 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14946 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14947 // `bw / 2, bh / 2` line-for-line.
14948 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14949 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14950 // The square strides the proven INTER path lays its residual grids,
14951 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14952 // note): 128/64 here.
14953 let side = bw.max(bh);
14954 let cside = cw.max(ch);
14955 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14956 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14957 let mi_cols = 2 * y.true_width.div_ceil(8);
14958 let mi_rows = 2 * y.true_height.div_ceil(8);
14959 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14960 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14961 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14962 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14963 // arms (lane-sb128c r7).
14964 let leaves = read_block_tx_size_rect(
14965 dec,
14966 cdfs,
14967 neighbours,
14968 (mi_r, mi_c),
14969 (bw, bh),
14970 (mi_cols, mi_rows),
14971 skip,
14972 fctx,
14973 )?;
14974 // Whole-block prediction, once, before any coefficient is read
14975 // (`predict_inter_block`); the source is this frame's own
14976 // reconstruction, including the writes this superblock has queued.
14977 flush_recon(fctx, y, u, v);
14978 let mut pred_y_dense = vec![0u16; bw * bh];
14979 mc::predict_with_filter(
14980 &y.data,
14981 y.width,
14982 y.true_width,
14983 y.true_height,
14984 mv_to_q4(px, dv_col, 0),
14985 mv_to_q4(py, dv_row, 0),
14986 bw,
14987 bh,
14988 mc::InterpFilterKind::Bilinear,
14989 &mut pred_y_dense,
14990 fctx,
14991 );
14992 let mut pred_y = vec![0u16; side * side];
14993 for row in 0..bh {
14994 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14995 }
14996 let mut pred_u_dense = vec![0u16; cw * ch];
14997 mc::predict_with_filter(
14998 &u.data,
14999 u.width,
15000 u.true_width,
15001 u.true_height,
15002 mv_to_q4(cpx, dv_col, ss_x(fctx)),
15003 mv_to_q4(cpy, dv_row, ss_y(fctx)),
15004 cw,
15005 ch,
15006 mc::InterpFilterKind::Bilinear,
15007 &mut pred_u_dense,
15008 fctx,
15009 );
15010 let mut pred_u = vec![0u16; cside * cside];
15011 for row in 0..ch {
15012 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
15013 }
15014 let mut pred_v_dense = vec![0u16; cw * ch];
15015 mc::predict_with_filter(
15016 &v.data,
15017 v.width,
15018 v.true_width,
15019 v.true_height,
15020 mv_to_q4(cpx, dv_col, ss_x(fctx)),
15021 mv_to_q4(cpy, dv_row, ss_y(fctx)),
15022 cw,
15023 ch,
15024 mc::InterpFilterKind::Bilinear,
15025 &mut pred_v_dense,
15026 fctx,
15027 );
15028 let mut pred_v = vec![0u16; cside * cside];
15029 for row in 0..ch {
15030 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
15031 }
15032 let (luma_grid, u_grid, v_grid);
15033 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
15034 // contexts per transform unit -- the replay after this fn's end-of-block
15035 // record restores them (the record itself re-stamps both planes with ONE
15036 // composed state, class `override-slot-on-one-arm`).
15037 let mut mu_chroma = false;
15038 if skip {
15039 // No residual syntax at all: the prediction IS the block. Strides are
15040 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
15041 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
15042 push_mc_rect(
15043 0,
15044 px,
15045 py,
15046 side,
15047 bw,
15048 bh,
15049 Pred::Inline(&pred_y, side),
15050 &ZERO_RESIDUAL[..side * side],
15051 fctx,
15052 );
15053 push_mc_rect(
15054 1,
15055 cpx,
15056 cpy,
15057 cside,
15058 cw,
15059 ch,
15060 Pred::Inline(&pred_u, cside),
15061 &ZERO_RESIDUAL[..cside * cside],
15062 fctx,
15063 );
15064 push_mc_rect(
15065 2,
15066 cpx,
15067 cpy,
15068 cside,
15069 cw,
15070 ch,
15071 Pred::Inline(&pred_v, cside),
15072 &ZERO_RESIDUAL[..cside * cside],
15073 fctx,
15074 );
15075 if let Some(ls) = leaves.as_ref() {
15076 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
15077 // grid before it looks at `skip`; the skipped block still zeroes
15078 // its entropy-band footprint over every unit (libaom
15079 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
15080 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
15081 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
15082 for &(row, col, tw, th) in ls {
15083 neighbours.record_mi_luma_rect(
15084 (mi_r + row, mi_c + col),
15085 tw,
15086 th,
15087 &ZERO_RESIDUAL[..tw * th],
15088 );
15089 }
15090 }
15091 luma_grid = Grid::Zero(side * side);
15092 u_grid = Grid::Zero(cside * cside);
15093 v_grid = Grid::Zero(cside * cside);
15094 } else {
15095 let leaves = leaves
15096 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
15097 // libaom `get_transform_size`'s split override applies to LUMA only,
15098 // per leaf -- each unit's own transform edges get filtered
15099 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
15100 for &(row, col, tw, th) in leaves.iter() {
15101 neighbours.fill_lf_grid_leaf_luma(
15102 (mi_r + row, mi_c + col),
15103 tw / MI,
15104 th / MI,
15105 tw as u8,
15106 th as u8,
15107 );
15108 }
15109 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
15110 let mut u_units: Vec<i32> = Vec::new();
15111 let mut v_units: Vec<i32> = Vec::new();
15112 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
15113 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
15114 // top-left sample is outside the frame codes nothing.
15115 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
15116 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
15117 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
15118 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
15119 for (pos, &idx) in order.iter().enumerate() {
15120 let (row, col, tw, th) = leaves[idx];
15121 debug_assert_eq!(
15122 tw, th,
15123 "a square TX_64X64 tree root only yields square leaves"
15124 );
15125 let tu_mi = (mi_r + row, mi_c + col);
15126 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
15127 if tu_px >= y.true_width || tu_py >= y.true_height {
15128 continue;
15129 }
15130 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
15131 let scan = default_scan(tw.min(32));
15132 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
15133 let (tu_grid, tu_tx_type) = read_inter_plane(
15134 dec,
15135 cdfs,
15136 inter_txbset_for(tw, reduced),
15137 &scan,
15138 0,
15139 neighbours.around_mi(tu_mi, tw)[0],
15140 0,
15141 y,
15142 tu_px,
15143 tu_py,
15144 tw,
15145 base_q_idx,
15146 tu_pred,
15147 None,
15148 Some(tu_skip_ctx),
15149 fctx,
15150 )?;
15151 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
15152 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
15153 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
15154 // mu chunk before the next one starts: once this chunk's leaves
15155 // are done, its chroma is read immediately (the inter 128 path's
15156 // interleave).
15157 let chunk = (row / 16, col / 16);
15158 let done = pos + 1 == order.len()
15159 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
15160 if done {
15161 let (cr, cc) = chunk;
15162 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
15163 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
15164 // within the chunk, plane-major inside the chunk.
15165 let cu_tx = 32usize;
15166 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
15167 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
15168 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
15169 // plane block is 32x64 there), four at 4:4:4. The old
15170 // `chunk_chroma = cside * 64 / side` walked a
15171 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
15172 // axes: at 4:2:2 it read HALF the chroma units of a chunk
15173 // (one 32x32 at the chunk's top-left instead of two), left
15174 // the chunk's lower 32 chroma rows with no residual at all,
15175 // and stamped every unit's entropy context over a 16x16-mi
15176 // luma span instead of 16x8. The same defect and the same
15177 // per-axis repair as `decode_inter_block`'s
15178 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
15179 // witnessed on `422_sb128_3f.obu`).
15180 let chunk_chroma_w = (64usize) >> ss_x(fctx);
15181 let chunk_chroma_h = (64usize) >> ss_y(fctx);
15182 // The unit's own footprint on the LUMA mi grid, per axis:
15183 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
15184 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
15185 // `record_mi_chroma` stamp exactly the unit's own cells.
15186 let unit_luma_w = cu_tx << ss_x(fctx);
15187 let unit_luma_h = cu_tx << ss_y(fctx);
15188 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
15189 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
15190 });
15191 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
15192 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
15193 let units_x = chunk_w_mi / (unit_luma_w / MI);
15194 let units_y = chunk_h_mi / (unit_luma_h / MI);
15195 if lossless(fctx) {
15196 // TX_4X4 chroma units over this chunk (lane-lossless2's
15197 // walk, shared with the inter 128 path).
15198 read_inter_chroma_lossless(
15199 dec,
15200 cdfs,
15201 neighbours,
15202 u,
15203 v,
15204 Pred::Inline(&pred_u, cside),
15205 Pred::Inline(&pred_v, cside),
15206 (mi_r, mi_c),
15207 (cpx, cpy),
15208 (cc * chunk_chroma_w, cr * chunk_chroma_h),
15209 (chunk_chroma_w, chunk_chroma_h),
15210 (cw, ch),
15211 cside,
15212 0,
15213 base_q_idx,
15214 &mut u_units,
15215 &mut v_units,
15216 fctx,
15217 )?;
15218 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
15219 // every TX_4X4 unit's own context (`record_mi_chroma`
15220 // inside the walk) -- the end-of-block record below must
15221 // not overwrite them with the composed grid (the inter
15222 // 128 path sets the same flag on this arm).
15223 mu_chroma = true;
15224 continue;
15225 }
15226 let cu_scan = default_scan(cu_tx);
15227 for plane_idx in 1..3 {
15228 let (src, buf) = if plane_idx == 1 {
15229 (Pred::Inline(&pred_u, cside), &mut *u)
15230 } else {
15231 (Pred::Inline(&pred_v, cside), &mut *v)
15232 };
15233 for ur in 0..units_y {
15234 for uc in 0..units_x {
15235 let unit_mi = (
15236 mi_r + cr * 16 + ur * (unit_luma_h / MI),
15237 mi_c + cc * 16 + uc * (unit_luma_w / MI),
15238 );
15239 // Per unit, AFTER the earlier units' stamps: this
15240 // unit's coefficient context must see them.
15241 let cu_around =
15242 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
15243 if crate::envflags::env_flag!("EC_ECDUMP") {
15244 for p in 1..3 {
15245 let ab: Vec<String> = (0..unit_luma_w / MI)
15246 .map(|k| {
15247 format!(
15248 "{:?}/{}",
15249 neighbours.above[unit_mi.1 + k][p].dc,
15250 neighbours.above[unit_mi.1 + k][p].level
15251 )
15252 })
15253 .collect();
15254 let lf: Vec<String> = (0..unit_luma_h / MI)
15255 .map(|k| {
15256 format!(
15257 "{:?}/{}",
15258 neighbours.left[unit_mi.0 + k][p].dc,
15259 neighbours.left[unit_mi.0 + k][p].level
15260 )
15261 })
15262 .collect();
15263 eprintln!(
15264 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
15265 cu_around[p].0,
15266 cu_around[p].1,
15267 cu_around[p].2,
15268 ab.join(","),
15269 lf.join(",")
15270 );
15271 }
15272 }
15273 let (cu_x, cu_y) = (
15274 cpx + cc * chunk_chroma_w + uc * cu_tx,
15275 cpy + cr * chunk_chroma_h + ur * cu_tx,
15276 );
15277 // `av1_get_tx_type` (blockd.h:1291): an inter
15278 // block's chroma unit never codes a tx_type; it
15279 // inherits the coded type of the luma leaf
15280 // covering its own quadrant (all of this chunk's
15281 // leaves are read by now).
15282 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
15283 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
15284 // The prediction window is the block's own square
15285 // `cside` buffer with the unit's true per-axis
15286 // position inside it.
15287 let cu_pred = src.offset(
15288 (cr * chunk_chroma_h + ur * cu_tx) * cside
15289 + cc * chunk_chroma_w
15290 + uc * cu_tx,
15291 );
15292 let cu_grid = read_inter_plane(
15293 dec,
15294 cdfs,
15295 TxbSet::Chroma32,
15296 &cu_scan,
15297 plane_idx,
15298 cu_around[plane_idx],
15299 0,
15300 buf,
15301 cu_x,
15302 cu_y,
15303 cu_tx,
15304 base_q_idx,
15305 cu_pred,
15306 Some(covering.unwrap_or(TxType::DctDct)),
15307 Some(3),
15308 fctx,
15309 )?
15310 .0;
15311 // Immediately, so the NEXT unit reads this one's
15312 // coefficient context.
15313 neighbours.record_mi_chroma(
15314 unit_mi,
15315 unit_luma_w,
15316 unit_luma_h,
15317 plane_idx,
15318 &cu_grid,
15319 );
15320 if crate::envflags::env_flag!("EC_ECDUMP") {
15321 let st = crate::decode::neighbour_state(&cu_grid);
15322 eprintln!(
15323 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
15324 st.dc, st.level
15325 );
15326 }
15327 hit!(CHROMA_SPLIT_TX_HITS);
15328 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
15329 // lane-av1-ibcrect: per-unit chroma context -- the
15330 // end-of-block record's composed-grid re-stamp
15331 // must not stand (replayed below).
15332 mu_chroma = true;
15333 let dst = mu_units(
15334 if plane_idx == 1 {
15335 &mut u_units
15336 } else {
15337 &mut v_units
15338 },
15339 cside * cside,
15340 );
15341 for rr in 0..cu_tx {
15342 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
15343 + cc * chunk_chroma_w
15344 + uc * cu_tx;
15345 dst[start..start + cu_tx]
15346 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
15347 }
15348 }
15349 }
15350 }
15351 }
15352 }
15353 // The block-level luma bands were recorded per leaf above; the
15354 // composed chroma grids carry every unit in place.
15355 luma_grid = Grid::Zero(side * side);
15356 u_grid = if u_units.is_empty() {
15357 Grid::Zero(cside * cside)
15358 } else {
15359 Grid::Own(std::mem::take(&mut u_units))
15360 };
15361 v_grid = if v_units.is_empty() {
15362 Grid::Zero(cside * cside)
15363 } else {
15364 Grid::Own(std::mem::take(&mut v_units))
15365 };
15366 }
15367 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
15368 // neighbour reads a mode, zeroed palette state, the skip grid, the
15369 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
15370 // and the DV into the intrabc mi grid.
15371 if skip {
15372 neighbours.record_rect_mi(
15373 (mi_r, mi_c),
15374 bw,
15375 bh,
15376 DC_PRED,
15377 DC_PRED,
15378 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
15379 );
15380 } else {
15381 neighbours.record_split_luma_rect_mi(
15382 (mi_r, mi_c),
15383 bw,
15384 bh,
15385 DC_PRED,
15386 DC_PRED,
15387 [&u_grid[..], &v_grid[..]],
15388 );
15389 }
15390 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
15391 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
15392 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
15393 // both planes with ONE `neighbour_state(composed_grid)` over the whole
15394 // span -- level = the SUM of every unit's levels and dc = the top-left
15395 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
15396 // inter block: the next block read a stale `dc_sign_ctx` one row low).
15397 // Measured on this shape: the 128x64 block at mi(64,32) of the
15398 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
15399 // into chunk-0's cells and the block below read `txb_skip` off the sum.
15400 // Replay every coded unit's own state after the record, in mu-chunk order
15401 // so a later unit still wins over an earlier one on the shared seam cells
15402 // (the composed construction `mu_chroma_units` uses, transcribed here).
15403 if mu_chroma {
15404 let cu = if lossless(fctx) { 4usize } else { 32usize };
15405 // The unit's own footprint on the LUMA mi grid (the chroma context
15406 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
15407 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
15408 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
15409 let unit_luma_w = cu << ss_x(fctx);
15410 let unit_luma_h = cu << ss_y(fctx);
15411 // A 64x64 mu chunk's chroma plane block is PER-AXIS
15412 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
15413 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
15414 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
15415 let chunk_chroma_w = (64usize) >> ss_x(fctx);
15416 let chunk_chroma_h = (64usize) >> ss_y(fctx);
15417 if lossless(fctx) {
15418 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
15419 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
15420 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
15421 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
15422 // enumerate it, and this arm re-stamps only the 4x4 at each
15423 // chunk's top-left with a 2x2-mi span. The twin
15424 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
15425 // instead raster-walks the WHOLE plane block at `cu` steps, and
15426 // that is the correct shape here too. It is left as-is on purpose:
15427 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
15428 // it would change 4:2:0 LOSSLESS output -- which this lane's
15429 // byte-identity requirement forbids doing on an unverified
15430 // reconstruction. Measured unreachability: this arm is entered
15431 // 0 times by the whole `lossless` and `intrabc` gate battery
15432 // (temporary env-gated counter in the arm). Unblock: one
15433 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
15434 // intrabc strip (`--lossless=1 --sb-size=128
15435 // --min-partition-size=64 --enable-rect-partitions=1
15436 // --enable-intrabc=1` over near-match screen content).
15437 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
15438 for cr in 0..rows {
15439 for cc in 0..cols {
15440 let unit_mi = (
15441 mi_r + cr * (unit_luma_h / MI),
15442 mi_c + cc * (unit_luma_w / MI),
15443 );
15444 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
15445 let mut unit = Vec::with_capacity(cu * cu);
15446 for rr in 0..cu {
15447 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
15448 unit.extend_from_slice(&grid[start..start + cu]);
15449 }
15450 neighbours.record_mi_chroma(
15451 unit_mi,
15452 unit_luma_w,
15453 unit_luma_h,
15454 plane_idx,
15455 &unit,
15456 );
15457 }
15458 }
15459 }
15460 } else {
15461 // The chunk count on each axis, then EVERY unit inside each
15462 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
15463 // span, and its own quadrant of the composed plane grid -- the
15464 // twin's loop (decode_inter_block's `mu_chroma_units`,
15465 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
15466 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
15467 // the grid PER UNIT, which only agrees when a chunk holds exactly
15468 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
15469 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
15470 // 2 or 4, so the old body reached only the first of the stacked
15471 // units and the rest of the chunk kept the composed-grid smearing
15472 // this replay exists to undo. A unit the frame edge clipped codes
15473 // nothing and carries no composed samples beyond the clip, so it
15474 // replays as the zero state exactly like libaom's uncoded unit.
15475 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
15476 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
15477 for cr in 0..rows {
15478 for cc in 0..cols {
15479 for kr in 0..ur {
15480 for kc in 0..uc {
15481 let unit_mi = (
15482 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
15483 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
15484 );
15485 let (cy, cx) =
15486 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
15487 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
15488 let mut unit = Vec::with_capacity(cu * cu);
15489 for rr in 0..cu {
15490 let start = (cy + rr) * cside + cx;
15491 unit.extend_from_slice(&grid[start..start + cu]);
15492 }
15493 neighbours.record_mi_chroma(
15494 unit_mi,
15495 unit_luma_w,
15496 unit_luma_h,
15497 plane_idx,
15498 &unit,
15499 );
15500 }
15501 }
15502 }
15503 }
15504 }
15505 }
15506 }
15507 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
15508 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
15509 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15510 // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree
15511 // published the bands, so no whole-footprint publish here.
15512 neighbours.fill_lf_grid_rect_after_vartx(
15513 (mi_r, mi_c),
15514 bw / MI,
15515 bh / MI,
15516 bw.min(64) as u8,
15517 bh.min(64) as u8,
15518 0,
15519 fctx,
15520 );
15521 record_intrabc_mi_rect(
15522 mi_r,
15523 mi_c,
15524 bw / MI,
15525 bh / MI,
15526 Some((dv_row, dv_col)),
15527 neighbours,
15528 fctx,
15529 );
15530 Ok(())
15531}
15532
15533/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
15534/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
15535/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
15536/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
15537/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
15538/// has no rectangular-transform coefficient reader, and a chroma plane here
15539/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
15540/// with no depth-based square-tiling escape the way luma's own resolved
15541/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
15542/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
15543#[allow(clippy::too_many_arguments)]
15544fn decode_block_rect(
15545 dec: &mut SymbolDecoder,
15546 cdfs: &mut Cdfs,
15547 neighbours: &mut Neighbours,
15548 at: (usize, usize),
15549 bw: usize,
15550 bh: usize,
15551 y: &mut PlaneBuf<'static>,
15552 u: &mut PlaneBuf<'static>,
15553 v: &mut PlaneBuf<'static>,
15554 enable_filter_intra: bool,
15555 allow_screen_content_tools: bool,
15556 base_q_idx: u8,
15557 tx_select: bool,
15558 reduced_tx_set: bool,
15559 fctx: &crate::decode::FrameCtx,
15560) -> Result<()> {
15561 let (r, c) = at;
15562 let (px, py) = (c * SUB, r * SUB);
15563 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
15564 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
15565 let palette_uv_cache = neighbours.palette_uv_cache(at);
15566 let (
15567 skip,
15568 mode,
15569 angle_delta_y,
15570 uv_mode,
15571 angle_delta_uv,
15572 alpha,
15573 filter_intra,
15574 palette_y,
15575 palette_uv,
15576 intrabc,
15577 ) = read_intra_mode_rect(
15578 dec,
15579 cdfs,
15580 nb_above_mode,
15581 nb_left_mode,
15582 true,
15583 true,
15584 bw,
15585 bh,
15586 enable_filter_intra,
15587 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
15588 allow_screen_content_tools,
15589 Some((palette_ctx, &palette_cache)),
15590 &palette_uv_cache,
15591 r * (SUB / MI),
15592 c * (SUB / MI),
15593 fctx,
15594 )?;
15595
15596 if let Some((dv_row, dv_col)) = intrabc {
15597 return decode_intrabc_rect(
15598 dec,
15599 cdfs,
15600 neighbours,
15601 (r * (SUB / MI), c * (SUB / MI)),
15602 (bw, bh),
15603 skip,
15604 (dv_row, dv_col),
15605 y,
15606 u,
15607 v,
15608 base_q_idx,
15609 fctx,
15610 );
15611 }
15612 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
15613 if smooth_neighbor {
15614 hit!(SMOOTH_LUMA_HITS);
15615 }
15616 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
15617 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
15618 // `uv_mode`, not the luma one.
15619 let smooth_neighbor_uv =
15620 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
15621 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
15622 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
15623 // rectangle just as happily), so a `use_filter_intra` strip at this level
15624 // predicts instead of refusing. The below-16x16 leaf arm
15625 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
15626 if filter_intra.is_some() {
15627 hit!(FILTER_INTRA_RECT_HITS);
15628 }
15629 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15630 DC_PRED
15631 } else {
15632 uv_mode
15633 };
15634 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
15635 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
15636 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
15637 // one did not, so with `--enable-tx-size-search=0` -- which several gate
15638 // recipes use -- the decoder consumed a symbol the encoder never wrote and
15639 // desynced the tile from that point on. That is why both strips of the
15640 // pinned HORZ quadrant were wrong from their very first pixel, and why our
15641 // range after the read equalled the oracle's range for the whole block.
15642 // lane-av1mixloss: the lossless-segment early return
15643 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
15644 // rect block codes no depth symbol here either (class sweep of the sub8
15645 // leaf's fix).
15646 let depth = if tx_select && !lossless(fctx) {
15647 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15648 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15649 // intra-only frame publishes them from every block too
15650 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15651 // 1920x792 128-superblock stream,
15652 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15653 // `tx_size_cat2` row 1 where libaom reads row 2.
15654 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15655 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
15656 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15657 eprintln!(
15658 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
15659 dec.debug_state().0
15660 );
15661 }
15662 d
15663 } else {
15664 0
15665 };
15666 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
15667 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15668 publish_txfm_bands_if_in_inter(
15669 neighbours,
15670 (mi_r, mi_c),
15671 depth_to_tx_wh(bw, bh, depth, fctx),
15672 (bw, bh),
15673 fctx,
15674 );
15675 if depth != 0 || lossless(fctx) {
15676 hit!(TX_DEPTH_HITS);
15677 // lane-rectsplit r1: a split transform is predicted and reconstructed
15678 // per transform unit, each unit taking its edges from the previous
15679 // unit's reconstruction inside this same strip (spec 5.11.36) --
15680 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
15681 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15682 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15683 eprintln!(
15684 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
15685 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
15686 angle_y={angle_delta_y}"
15687 );
15688 }
15689 let modes = RectStripModes {
15690 skip,
15691 mode,
15692 angle_delta_y,
15693 uv_predict_mode,
15694 angle_delta_uv,
15695 alpha,
15696 filter_intra,
15697 smooth_neighbor,
15698 smooth_neighbor_uv,
15699 palette_y: palette_y
15700 .as_ref()
15701 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
15702 palette_uv: palette_uv.as_ref().map(|p| {
15703 (
15704 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15705 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15706 )
15707 }),
15708 };
15709 if palette_y.is_some() || palette_uv.is_some() {
15710 hit!(PALETTE_SPLIT_TX_HITS);
15711 }
15712 decode_rect_split(
15713 dec,
15714 cdfs,
15715 neighbours,
15716 (mi_r, mi_c),
15717 bw,
15718 bh,
15719 tx_w,
15720 tx_h,
15721 &modes,
15722 y,
15723 u,
15724 v,
15725 base_q_idx,
15726 reduced_tx_set,
15727 fctx,
15728 )?;
15729 // This early return skips this fn's own tail, so the palette
15730 // neighbour state has to be stamped HERE too: without it a split-tx
15731 // strip left the above/left palette arrays holding a DEAD block's
15732 // colours, and the next block's colour cache
15733 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
15734 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
15735 // and only those pixels were wrong (lane-palette2 r10).
15736 let (py_size, py_colors) = palette_y
15737 .as_ref()
15738 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15739 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15740 let (puv_size, puv_colors) = palette_uv
15741 .as_ref()
15742 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15743 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15744 hit!(RECT_PARTITION_HITS);
15745 return Ok(());
15746 }
15747 let (tx_w, tx_h) = (bw, bh);
15748 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15749 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15750 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15751 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15752 let (rng, _) = dec.debug_state();
15753 eprintln!(
15754 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
15755 skip={} tx={depth} rng={rng}",
15756 skip as i32
15757 );
15758 }
15759 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
15760 // block's prediction is the reconstructed colour-index map, set fresh
15761 // right before each `reconstruct_rect` call below (lane-palette2 r4).
15762 if let Some(ref pyv) = palette_y {
15763 let buf: Vec<u16> = pyv
15764 .map
15765 .iter()
15766 .map(|&idx| pyv.colors[idx as usize])
15767 .collect();
15768 set_palette_pred(buf, fctx);
15769 }
15770 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15771 (
15772 puv.map
15773 .iter()
15774 .map(|&idx| puv.u_colors[idx as usize])
15775 .collect(),
15776 puv.map
15777 .iter()
15778 .map(|&idx| puv.v_colors[idx as usize])
15779 .collect(),
15780 )
15781 });
15782 if skip {
15783 push_intra_rect(
15784 0,
15785 px,
15786 py,
15787 bw,
15788 bh,
15789 mode,
15790 angle_delta_y,
15791 reach,
15792 &ZERO_RESIDUAL[..bw * bh],
15793 None,
15794 filter_intra,
15795 smooth_neighbor,
15796 fctx,
15797 );
15798 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15799 if let Some((ub, _)) = &palette_uv_bufs {
15800 set_palette_pred(ub.clone(), fctx);
15801 }
15802 push_intra_rect(
15803 1,
15804 cpx,
15805 cpy,
15806 chroma_w,
15807 chroma_h,
15808 uv_predict_mode,
15809 angle_delta_uv,
15810 reach,
15811 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15812 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15813 None,
15814 smooth_neighbor_uv,
15815 fctx,
15816 );
15817 if let Some((_, vb)) = &palette_uv_bufs {
15818 set_palette_pred(vb.clone(), fctx);
15819 }
15820 push_intra_rect(
15821 2,
15822 cpx,
15823 cpy,
15824 chroma_w,
15825 chroma_h,
15826 uv_predict_mode,
15827 angle_delta_uv,
15828 reach,
15829 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15830 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15831 None,
15832 smooth_neighbor_uv,
15833 fctx,
15834 );
15835 neighbours.record_rect(
15836 at,
15837 bw,
15838 bh,
15839 mode,
15840 uv_predict_mode,
15841 &[
15842 &ZERO_RESIDUAL[..bw * bh],
15843 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15844 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15845 ],
15846 );
15847 } else {
15848 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
15849 // reduces both size pairs to their square-up CDF sets
15850 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
15851 // doc comments); the scan order and 2D context tables are the real
15852 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
15853 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
15854 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
15855 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
15856 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
15857 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15858 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15859 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15860 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
15861 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
15862 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
15863 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
15864 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
15865 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
15866 // default follows the >=32 rule below -- the same pairing the
15867 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
15868 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
15869 // is reachable there.
15870 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
15871 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15872 _ => {
15873 return Err(unsupported(
15874 "a rectangular chroma transform whose size has no coefficient table",
15875 ));
15876 }
15877 };
15878 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
15879 TxType::DctDct
15880 } else {
15881 default_intra_tx_type(uv_predict_mode as u8)
15882 };
15883 // lane-rectwire r3: real coefficients desync a pixel-exact gate
15884 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
15885 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
15886 // pixel (not a subtle context-table off-by-one), while the sibling
15887 // non-rect quadrants of the same frame match. Range-ladder bisection
15888 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
15889 // but the intra key-frame path has no traced symbol between the
15890 // partition read and the first coefficient block (mode/skip/tx_depth
15891 // reads are all untraced in libaom's decodeframe.c intra path, unlike
15892 // the inter EC_TRACE_MODE this round added), so a same-length range
15893 // comparison wasn't reachable within budget -- see
15894 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
15895 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
15896 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
15897 // libaom and match). lane-rectwire r4: range-ladder against the
15898 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
15899 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
15900 // both confirmed in sync -- rng=58692 on both sides right after
15901 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
15902 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
15903 // immediately after: ours moves rng 58692 -> 43570, which cannot be
15904 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
15905 // its own tx_size read) unless oracle's tx symbol is a near-certainty
15906 // CDF that barely narrows the range -- i.e. this decoder's
15907 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
15908 // a 32x16/16x32 strip is the first diverging symbol, not the
15909 // coefficient-context math r3 already cleared. Not confirmed byte-
15910 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
15911 // `read_tx_size`'s own rng, not attempted this round -- budget), so
15912 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
15913 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
15914 // it unconditionally where both square paths gate on `tx_select`. With
15915 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
15916 // decoder consumed one that was never there.
15917 {
15918 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15919 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15920 // strip's chroma is a square (side/2, side) block whose above cells
15921 // spread over `side` LUMA mi columns, so the per-mi rect gather
15922 // double-counts every chroma column's whole-unit dc sign. Measured on
15923 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15924 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15925 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15926 // 45260 whose pre-state, bit position and symbol all match and only
15927 // the CDF row differs, and the first divergence in the EC_SYMR
15928 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15929 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15930 let mut around = neighbours.around_rect(at, bw, bh);
15931 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15932 let c2 =
15933 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15934 around[1] = c2[1];
15935 around[2] = c2[2];
15936 }
15937 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15938 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15939 dec,
15940 &mut luma_coding,
15941 luma_scan,
15942 bw,
15943 bh,
15944 0,
15945 dc_sign_ctx(around[0].2),
15946 TxType::DctDct,
15947 0,
15948 )?;
15949 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15950 let (rng, _) = dec.debug_state();
15951 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15952 }
15953 let luma_residual = dequant_and_inverse_typed_wh(
15954 &luma_levels,
15955 bw,
15956 bh,
15957 crate::decode::bit_depth(fctx),
15958 block_q_idx(fctx),
15959 plane_q_delta(0, fctx).0,
15960 plane_q_delta(0, fctx).1,
15961 luma_tx_type,
15962 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15963 );
15964 push_intra_rect(
15965 0,
15966 px,
15967 py,
15968 bw,
15969 bh,
15970 mode,
15971 angle_delta_y,
15972 reach,
15973 &luma_residual,
15974 None,
15975 filter_intra,
15976 smooth_neighbor,
15977 fctx,
15978 );
15979 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15980 if let Some((ub, _)) = &palette_uv_bufs {
15981 set_palette_pred(ub.clone(), fctx);
15982 }
15983 let u_default_tx = chroma_default_tx;
15984 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15985 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15986 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15987 dec,
15988 &mut u_coding,
15989 chroma_scan,
15990 chroma_w,
15991 chroma_h,
15992 u_skip_ctx,
15993 dc_sign_ctx(around[1].2),
15994 u_default_tx,
15995 fctx,
15996 1,
15997 )?;
15998 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15999 let (rng, _) = dec.debug_state();
16000 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
16001 }
16002 let u_residual = dequant_and_inverse_typed_wh(
16003 &u_levels,
16004 chroma_w,
16005 chroma_h,
16006 crate::decode::bit_depth(fctx),
16007 block_q_idx(fctx),
16008 plane_q_delta(1, fctx).0,
16009 plane_q_delta(1, fctx).1,
16010 u_tx_type,
16011 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
16012 );
16013 push_intra_rect(
16014 1,
16015 cpx,
16016 cpy,
16017 chroma_w,
16018 chroma_h,
16019 uv_predict_mode,
16020 angle_delta_uv,
16021 reach,
16022 &u_residual,
16023 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16024 None,
16025 smooth_neighbor_uv,
16026 fctx,
16027 );
16028 if let Some((_, vb)) = &palette_uv_bufs {
16029 set_palette_pred(vb.clone(), fctx);
16030 }
16031 let v_default_tx = chroma_default_tx;
16032 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
16033 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
16034 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
16035 dec,
16036 &mut v_coding,
16037 chroma_scan,
16038 chroma_w,
16039 chroma_h,
16040 v_skip_ctx,
16041 dc_sign_ctx(around[2].2),
16042 v_default_tx,
16043 fctx,
16044 2,
16045 )?;
16046 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16047 let (rng, _) = dec.debug_state();
16048 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
16049 }
16050 let v_residual = dequant_and_inverse_typed_wh(
16051 &v_levels,
16052 chroma_w,
16053 chroma_h,
16054 crate::decode::bit_depth(fctx),
16055 block_q_idx(fctx),
16056 plane_q_delta(2, fctx).0,
16057 plane_q_delta(2, fctx).1,
16058 v_tx_type,
16059 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
16060 );
16061 push_intra_rect(
16062 2,
16063 cpx,
16064 cpy,
16065 chroma_w,
16066 chroma_h,
16067 uv_predict_mode,
16068 angle_delta_uv,
16069 reach,
16070 &v_residual,
16071 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16072 None,
16073 smooth_neighbor_uv,
16074 fctx,
16075 );
16076 neighbours.record_rect(
16077 at,
16078 bw,
16079 bh,
16080 mode,
16081 uv_predict_mode,
16082 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16083 );
16084 hit!(RECT_COEFF_HITS);
16085 }
16086 }
16087 let (py_size, py_colors) = palette_y
16088 .as_ref()
16089 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16090 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
16091 let (puv_size, puv_colors) = palette_uv
16092 .as_ref()
16093 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16094 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
16095 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
16096 neighbours.fill_lf_grid_rect(
16097 (mi_r, mi_c),
16098 bw / MI,
16099 bh / MI,
16100 tx_w as u8,
16101 tx_h as u8,
16102 0,
16103 fctx,
16104 );
16105 hit!(RECT_PARTITION_HITS);
16106 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16107 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
16108 }
16109 Ok(())
16110}
16111
16112/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
16113/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
16114/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
16115/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
16116/// the second strip of a HORZ/VERT split sits offset by half the 16x16
16117/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
16118/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
16119/// previous strip is directly above (same column, `mi_h` rows up) or
16120/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
16121/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
16122/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
16123/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
16124/// this strip's real position, never the coarse `record_rect` (which the
16125/// caller uses once, after both strips, exactly like the `VERT_B` arm next
16126/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
16127/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
16128/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
16129/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
16130/// half-width, unhalved height), the two size classes one level
16131/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
16132#[allow(clippy::too_many_arguments)]
16133fn decode_leaf_rect(
16134 dec: &mut SymbolDecoder,
16135 cdfs: &mut Cdfs,
16136 neighbours: &mut Neighbours,
16137 outer_at: (usize, usize),
16138 leaf_mi: (usize, usize),
16139 bw: usize,
16140 bh: usize,
16141 prev_leaf: Option<((usize, usize), usize)>,
16142 y: &mut PlaneBuf<'static>,
16143 u: &mut PlaneBuf<'static>,
16144 v: &mut PlaneBuf<'static>,
16145 enable_filter_intra: bool,
16146 allow_screen_content_tools: bool,
16147 base_q_idx: u8,
16148 tx_select: bool,
16149 reduced_tx_set: bool,
16150 fctx: &crate::decode::FrameCtx,
16151) -> Result<usize> {
16152 let _ = base_q_idx;
16153 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
16154 eprintln!(
16155 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
16156 dec.debug_state().0
16157 );
16158 }
16159 let (r, c) = outer_at;
16160 let mut above_mode = neighbours.above_mode[c];
16161 let mut left_mode = neighbours.left_mode[r];
16162 let (mi_w, mi_h) = (bw / MI, bh / MI);
16163 if let Some(((pr, pc), pmode)) = prev_leaf {
16164 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
16165 above_mode = pmode;
16166 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
16167 left_mode = pmode;
16168 }
16169 }
16170 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
16171 // cannot hold the modes a split (or a pair of strips) leaves behind, so
16172 // when the map holds the block at exactly this strip's above/left mi it
16173 // is the neighbour libaom's `above_mi`/`left_mi` reads.
16174 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
16175 // availability-correct -- four 16x8 strips share one coarse 16x16
16176 // `left_mode` cell too, so the fallback must not stand in for an absent
16177 // tile-edge neighbour.
16178 let (above_mode, left_mode) =
16179 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
16180 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16181 if smooth_neighbor {
16182 hit!(SMOOTH_LUMA_HITS);
16183 }
16184 // The palette-Y mode CDF row is picked by the neighbours' palette use
16185 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
16186 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
16187 // a palette narrows the wrong interval and desyncs the tile even when the
16188 // decoded bit is the same. The cell is the 16px-SUB cell containing the
16189 // leaf (the palette neighbour arrays have no finer granularity).
16190 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
16191 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
16192 // exclusion and the neighbour palette lookup itself are mi-granular
16193 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
16194 let pal_at = leaf_mi;
16195 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
16196 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
16197 let (
16198 skip,
16199 mode,
16200 angle_delta_y,
16201 uv_mode,
16202 angle_delta_uv,
16203 alpha,
16204 filter_intra,
16205 palette_y,
16206 palette_uv,
16207 intrabc,
16208 ) = read_intra_mode_rect(
16209 dec,
16210 cdfs,
16211 above_mode,
16212 left_mode,
16213 true,
16214 true,
16215 bw,
16216 bh,
16217 enable_filter_intra,
16218 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
16219 allow_screen_content_tools,
16220 Some((palette_ctx, &palette_cache)),
16221 &palette_uv_cache,
16222 leaf_mi.0,
16223 leaf_mi.1,
16224 fctx,
16225 )?;
16226
16227 if let Some((dv_row, dv_col)) = intrabc {
16228 decode_intrabc_rect(
16229 dec,
16230 cdfs,
16231 neighbours,
16232 leaf_mi,
16233 (bw, bh),
16234 skip,
16235 (dv_row, dv_col),
16236 y,
16237 u,
16238 v,
16239 base_q_idx,
16240 fctx,
16241 )?;
16242 return Ok(DC_PRED);
16243 }
16244 // lane-kf900 r4: palette prediction on this shape, the same colour-index
16245 // map -> base colours buffer [`decode_block_rect`] hands each
16246 // `reconstruct_rect` through [`set_palette_pred`].
16247 if palette_y.is_some() || palette_uv.is_some() {
16248 hit!(RECT4_PALETTE_HITS);
16249 }
16250 let palette_y_buf: Option<Vec<u16>> = palette_y
16251 .as_ref()
16252 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16253 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16254 (
16255 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16256 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16257 )
16258 });
16259 let (pal_y_size, pal_y_colors) = palette_y
16260 .as_ref()
16261 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16262 let (pal_uv_size, pal_uv_colors) = palette_uv
16263 .as_ref()
16264 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16265 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
16266 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
16267 }
16268 if filter_intra.is_some() {
16269 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
16270 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
16271 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
16272 // below already makes; this refusal was square-only prose.
16273 hit!(FILTER_INTRA_RECT_HITS);
16274 hit!(FILTER_INTRA_RECT_SUB16_HITS);
16275 }
16276 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16277 DC_PRED
16278 } else {
16279 uv_mode
16280 };
16281 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
16282 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
16283 // a constant `false`.
16284 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
16285 let depth = if tx_select && !lossless(fctx) {
16286 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
16287 // every other rect reader now does -- a no-op on a key frame.
16288 // lane-av1mixloss: libaom `read_tx_size`'s first line
16289 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
16290 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
16291 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
16292 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
16293 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
16294 // read was the leaf's own txb_skip.
16295 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
16296 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
16297 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
16298 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
16299 // count (3), different CDF row: a wrong-table read of a real symbol,
16300 // the class that cost lane-rectsplit r1 its 64x32 depth.
16301 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
16302 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
16303 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
16304 // function also decodes) sit at depth 2, so they read
16305 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
16306 // while `tx_size_cat2` belongs to the 32-level shapes
16307 // ([`decode_block_rect`]). Both tables carry three symbols, so the
16308 // wrong one decodes a plausible depth from the wrong probabilities:
16309 // the range diverges silently at the first such leaf and every later
16310 // symbol in the tile is read from the wrong place (class
16311 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
16312 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
16313 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16314 eprintln!(
16315 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
16316 leaf_mi.0,
16317 leaf_mi.1,
16318 dec.debug_state().0
16319 );
16320 }
16321 d
16322 } else {
16323 0
16324 };
16325 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
16326 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
16327 publish_txfm_bands_if_in_inter(
16328 neighbours,
16329 leaf_mi,
16330 depth_to_tx_wh(bw, bh, depth, fctx),
16331 (bw, bh),
16332 fctx,
16333 );
16334 if depth != 0 || lossless(fctx) {
16335 // The same per-transform-unit walk the bigger strips take
16336 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
16337 // depth 2), addressed at this leaf's own mi position.
16338 hit!(TX_DEPTH_HITS);
16339 hit!(SUB16_SPLIT_HITS);
16340 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16341 let modes = RectStripModes {
16342 skip,
16343 mode,
16344 angle_delta_y,
16345 uv_predict_mode,
16346 angle_delta_uv,
16347 alpha,
16348 filter_intra,
16349 smooth_neighbor,
16350 // lane-rectsplitx r3: the split arm hard-coded `false` here while
16351 // the unsplit arm below passes the real neighbour answer -- chroma
16352 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
16353 smooth_neighbor_uv,
16354 palette_y: palette_y_buf.clone(),
16355 palette_uv: palette_uv_bufs.clone(),
16356 };
16357 if palette_y.is_some() || palette_uv.is_some() {
16358 hit!(PALETTE_SPLIT_TX_HITS);
16359 }
16360 decode_rect_split(
16361 dec,
16362 cdfs,
16363 neighbours,
16364 leaf_mi,
16365 bw,
16366 bh,
16367 tx_w,
16368 tx_h,
16369 &modes,
16370 y,
16371 u,
16372 v,
16373 base_q_idx,
16374 reduced_tx_set,
16375 fctx,
16376 )?;
16377 record_strip_palette(
16378 neighbours,
16379 pal_at,
16380 bw,
16381 bh,
16382 pal_y_size,
16383 pal_y_colors,
16384 pal_uv_size,
16385 pal_uv_colors,
16386 );
16387 return Ok(mode);
16388 }
16389 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16390 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16391 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16392 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16393 let (luma_levels, u_levels, v_levels);
16394 if skip {
16395 luma_levels = Grid::Zero(bw * bh);
16396 u_levels = Grid::Zero(chroma_w * chroma_h);
16397 v_levels = Grid::Zero(chroma_w * chroma_h);
16398 if let Some(b) = &palette_y_buf {
16399 set_palette_pred(b.clone(), fctx);
16400 }
16401 push_intra_rect(
16402 0,
16403 px,
16404 py,
16405 bw,
16406 bh,
16407 mode,
16408 angle_delta_y,
16409 reach,
16410 &luma_levels,
16411 None,
16412 filter_intra,
16413 smooth_neighbor,
16414 fctx,
16415 );
16416 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16417 if let Some((ub, _)) = &palette_uv_bufs {
16418 set_palette_pred(ub.clone(), fctx);
16419 }
16420 push_intra_rect(
16421 1,
16422 cpx,
16423 cpy,
16424 chroma_w,
16425 chroma_h,
16426 uv_predict_mode,
16427 angle_delta_uv,
16428 reach,
16429 &u_levels,
16430 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16431 None,
16432 smooth_neighbor_uv,
16433 fctx,
16434 );
16435 if let Some((_, vb)) = &palette_uv_bufs {
16436 set_palette_pred(vb.clone(), fctx);
16437 }
16438 push_intra_rect(
16439 2,
16440 cpx,
16441 cpy,
16442 chroma_w,
16443 chroma_h,
16444 uv_predict_mode,
16445 angle_delta_uv,
16446 reach,
16447 &v_levels,
16448 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16449 None,
16450 smooth_neighbor_uv,
16451 fctx,
16452 );
16453 } else {
16454 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
16455 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
16456 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
16457 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
16458 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
16459 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
16460 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
16461 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
16462 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
16463 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
16464 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
16465 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
16466 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
16467 if bw == 16 {
16468 (&SCAN_16X8, &SCAN_16X8)
16469 } else {
16470 (&SCAN_8X16, &SCAN_8X16)
16471 }
16472 } else if chroma_422 {
16473 if bw == 16 {
16474 (&SCAN_16X8, default_scan(8))
16475 } else {
16476 (&SCAN_8X16, default_scan(8))
16477 }
16478 } else if bw == 16 {
16479 (&SCAN_16X8, &SCAN_8X4)
16480 } else {
16481 (&SCAN_8X16, &SCAN_4X8)
16482 };
16483 let chroma_rect_set = if ss_x(fctx) == 0 {
16484 TxbSet::ChromaRect16x8
16485 } else if chroma_422 {
16486 TxbSet::Chroma8
16487 } else {
16488 TxbSet::ChromaRect8x4
16489 };
16490 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
16491 // (side/2, side) block, so `side` chroma 4-px cells above it spread
16492 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
16493 // mi cells, and both carry the covering unit's whole-unit dc sign.
16494 // The per-mi rect gather therefore double-counts every chroma
16495 // column's sign. `around_mi_422_chroma`'s every-second above-cell
16496 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
16497 // gather in this file already routes through it (see the gate at this
16498 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
16499 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
16500 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
16501 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
16502 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
16503 // divergence in the frame (the bit offset is a clean constant through
16504 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
16505 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
16506 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
16507 if chroma_422 {
16508 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
16509 around[1] = c[1];
16510 around[2] = c[2];
16511 }
16512 let luma_set = if reduced_tx_set {
16513 TxbSet::LumaRect16x8
16514 } else {
16515 TxbSet::LumaRect16x8Set1
16516 };
16517 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
16518 let (l_levels, luma_tx_type) = read_coeffs_rect(
16519 dec,
16520 &mut luma_coding,
16521 luma_scan,
16522 bw,
16523 bh,
16524 0,
16525 dc_sign_ctx(around[0].2),
16526 TxType::DctDct,
16527 0,
16528 )?;
16529 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
16530 let nz: Vec<(usize, i32)> = l_levels
16531 .iter()
16532 .copied()
16533 .enumerate()
16534 .filter(|(_, v)| *v != 0)
16535 .collect();
16536 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
16537 }
16538 luma_levels = l_levels;
16539 let luma_residual = dequant_and_inverse_typed_wh(
16540 &luma_levels,
16541 bw,
16542 bh,
16543 crate::decode::bit_depth(fctx),
16544 block_q_idx(fctx),
16545 plane_q_delta(0, fctx).0,
16546 plane_q_delta(0, fctx).1,
16547 luma_tx_type,
16548 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16549 );
16550 if let Some(b) = &palette_y_buf {
16551 set_palette_pred(b.clone(), fctx);
16552 }
16553 push_intra_rect(
16554 0,
16555 px,
16556 py,
16557 bw,
16558 bh,
16559 mode,
16560 angle_delta_y,
16561 reach,
16562 &luma_residual,
16563 None,
16564 filter_intra,
16565 smooth_neighbor,
16566 fctx,
16567 );
16568 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16569 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
16570 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
16571 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
16572 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
16573 dec,
16574 &mut u_coding,
16575 chroma_scan,
16576 chroma_w,
16577 chroma_h,
16578 u_skip_ctx,
16579 dc_sign_ctx(around[1].2),
16580 u_default_tx,
16581 fctx,
16582 1,
16583 )?;
16584 u_levels = u_l;
16585 let u_residual = dequant_and_inverse_typed_wh(
16586 &u_levels,
16587 chroma_w,
16588 chroma_h,
16589 crate::decode::bit_depth(fctx),
16590 block_q_idx(fctx),
16591 plane_q_delta(1, fctx).0,
16592 plane_q_delta(1, fctx).1,
16593 u_tx_type,
16594 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
16595 );
16596 if let Some((ub, _)) = &palette_uv_bufs {
16597 set_palette_pred(ub.clone(), fctx);
16598 }
16599 push_intra_rect(
16600 1,
16601 cpx,
16602 cpy,
16603 chroma_w,
16604 chroma_h,
16605 uv_predict_mode,
16606 angle_delta_uv,
16607 reach,
16608 &u_residual,
16609 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16610 None,
16611 smooth_neighbor_uv,
16612 fctx,
16613 );
16614 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
16615 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
16616 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
16617 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
16618 dec,
16619 &mut v_coding,
16620 chroma_scan,
16621 chroma_w,
16622 chroma_h,
16623 v_skip_ctx,
16624 dc_sign_ctx(around[2].2),
16625 v_default_tx,
16626 fctx,
16627 2,
16628 )?;
16629 v_levels = v_l;
16630 let v_residual = dequant_and_inverse_typed_wh(
16631 &v_levels,
16632 chroma_w,
16633 chroma_h,
16634 crate::decode::bit_depth(fctx),
16635 block_q_idx(fctx),
16636 plane_q_delta(2, fctx).0,
16637 plane_q_delta(2, fctx).1,
16638 v_tx_type,
16639 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
16640 );
16641 if let Some((_, vb)) = &palette_uv_bufs {
16642 set_palette_pred(vb.clone(), fctx);
16643 }
16644 push_intra_rect(
16645 2,
16646 cpx,
16647 cpy,
16648 chroma_w,
16649 chroma_h,
16650 uv_predict_mode,
16651 angle_delta_uv,
16652 reach,
16653 &v_residual,
16654 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16655 None,
16656 smooth_neighbor_uv,
16657 fctx,
16658 );
16659 hit!(RECT_LEAF_COEFF_HITS);
16660 }
16661 neighbours.record_mi_rect(
16662 leaf_mi,
16663 bw,
16664 bh,
16665 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16666 );
16667 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
16668 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16669 // The leaf's own palette state (`0` clears, as this site always did
16670 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
16671 // AXIS only until the pair's closing leaf: the coarse cell holds one
16672 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
16673 // real left neighbour leaf 1 reads (lane-kf900 r4).
16674 record_strip_palette(
16675 neighbours,
16676 pal_at,
16677 bw,
16678 bh,
16679 pal_y_size,
16680 pal_y_colors,
16681 pal_uv_size,
16682 pal_uv_colors,
16683 );
16684 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
16685 // rows -- record the whole span, not one cell.
16686 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
16687 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
16688 Ok(mode)
16689}
16690
16691/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
16692/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
16693/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
16694/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
16695/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
16696/// strip's mode so this one's mode context sees its true above/left
16697/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
16698///
16699/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
16700/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
16701/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
16702/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
16703/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
16704/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
16705/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
16706///
16707/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
16708/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
16709/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
16710/// unexamined.
16711#[allow(clippy::too_many_arguments)]
16712fn decode_block_rect4(
16713 dec: &mut SymbolDecoder,
16714 cdfs: &mut Cdfs,
16715 neighbours: &mut Neighbours,
16716 strip_mi: (usize, usize),
16717 bw: usize,
16718 bh: usize,
16719 prev_strip: Option<((usize, usize), usize)>,
16720 y: &mut PlaneBuf<'static>,
16721 u: &mut PlaneBuf<'static>,
16722 v: &mut PlaneBuf<'static>,
16723 enable_filter_intra: bool,
16724 allow_screen_content_tools: bool,
16725 base_q_idx: u8,
16726 tx_select: bool,
16727 fctx: &crate::decode::FrameCtx,
16728) -> Result<(usize, usize)> {
16729 let _ = base_q_idx;
16730 let (mi_r, mi_c) = strip_mi;
16731 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
16732 let (mi_w, mi_h) = (bw / MI, bh / MI);
16733 let mut above_mode = neighbours.above_mode[c];
16734 let mut left_mode = neighbours.left_mode[r];
16735 if let Some(((pr, pc), pmode)) = prev_strip {
16736 if pc == mi_c && mi_r == pr + mi_h {
16737 above_mode = pmode;
16738 } else if pr == mi_r && mi_c == pc + mi_w {
16739 left_mode = pmode;
16740 }
16741 }
16742 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
16743 // availability-correct neighbour modes (see
16744 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
16745 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
16746 let (above_mode, left_mode) =
16747 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
16748 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
16749 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
16750 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
16751 // wrong interval, so a screen-content tile desynced at the first strip
16752 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
16753 let pal_at = (mi_r, mi_c);
16754 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
16755 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
16756 let (
16757 skip,
16758 mode,
16759 angle_delta_y,
16760 uv_mode,
16761 angle_delta_uv,
16762 alpha,
16763 filter_intra,
16764 palette_y,
16765 palette_uv,
16766 intrabc,
16767 ) = read_intra_mode_rect(
16768 dec,
16769 cdfs,
16770 above_mode,
16771 left_mode,
16772 true,
16773 true,
16774 bw,
16775 bh,
16776 enable_filter_intra,
16777 neighbours.skip_txfm_ctx(mi_r, mi_c),
16778 allow_screen_content_tools,
16779 Some((palette_ctx, &palette_cache)),
16780 &palette_uv_cache,
16781 mi_r,
16782 mi_c,
16783 fctx,
16784 )?;
16785 if let Some((dv_row, dv_col)) = intrabc {
16786 decode_intrabc_rect(
16787 dec,
16788 cdfs,
16789 neighbours,
16790 strip_mi,
16791 (bw, bh),
16792 skip,
16793 (dv_row, dv_col),
16794 y,
16795 u,
16796 v,
16797 base_q_idx,
16798 fctx,
16799 )?;
16800 return Ok((DC_PRED, DC_PRED));
16801 }
16802 // lane-kf900 r4: palette prediction on this shape, exactly as
16803 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
16804 // mapped through the base colours IS the prediction (it reads no edge
16805 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
16806 if palette_y.is_some() || palette_uv.is_some() {
16807 hit!(RECT4_PALETTE_HITS);
16808 }
16809 let palette_y_buf: Option<Vec<u16>> = palette_y
16810 .as_ref()
16811 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16812 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16813 (
16814 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16815 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16816 )
16817 });
16818 let (pal_y_size, pal_y_colors) = palette_y
16819 .as_ref()
16820 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16821 let (pal_uv_size, pal_uv_colors) = palette_uv
16822 .as_ref()
16823 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16824 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16825 if smooth_neighbor {
16826 hit!(SMOOTH_LUMA_HITS);
16827 }
16828 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
16829 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
16830 // `r * (SUB / MI)` names a different mi column and the chroma
16831 // edge-filter strength was read from the wrong neighbour (measured:
16832 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
16833 // with luma bit-exact).
16834 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
16835 if filter_intra.is_some() {
16836 hit!(FILTER_INTRA_RECT_HITS);
16837 if bw > bh {
16838 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
16839 } else {
16840 hit!(FILTER_INTRA_RECT4_VERT_HITS);
16841 }
16842 }
16843 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16844 DC_PRED
16845 } else {
16846 uv_mode
16847 };
16848 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
16849 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
16850 // depth symbol here either (class sweep of the sub8 leaf's fix).
16851 let depth = if tx_select && !lossless(fctx) {
16852 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
16853 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
16854 // intra-only frame publishes them from every block too
16855 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
16856 // 1920x792 128-superblock stream,
16857 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
16858 // `tx_size_cat2` row 1 where libaom reads row 2.
16859 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
16860 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
16861 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16862 eprintln!(
16863 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
16864 dec.debug_state().0
16865 );
16866 }
16867 d
16868 } else {
16869 0
16870 };
16871 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
16872 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
16873 publish_txfm_bands_if_in_inter(
16874 neighbours,
16875 (mi_r, mi_c),
16876 depth_to_tx_wh(bw, bh, depth, fctx),
16877 (bw, bh),
16878 fctx,
16879 );
16880 if depth != 0 || lossless(fctx) {
16881 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
16882 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
16883 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
16884 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
16885 // both interleave in every real stream.
16886 hit!(TX_DEPTH_HITS);
16887 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16888 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
16889 // predicted -- depth 1 fires FIRST in every attempt that splits at
16890 // all, so a depth-2-only lift could never be gated. The r1 mismatch
16891 // was never the rect unit: it was the neighbour MODE the strip reads
16892 // (see `modes_above_left_mi`).
16893 let which = if depth == 1 {
16894 &RECT4_SPLIT_DEPTH1_HITS
16895 } else {
16896 &RECT4_SPLIT_DEPTH2_HITS
16897 };
16898 hit_do! { which.with(|c| c.set(c.get() + 1)); }
16899 let modes = RectStripModes {
16900 skip,
16901 mode,
16902 angle_delta_y,
16903 uv_predict_mode,
16904 angle_delta_uv,
16905 alpha,
16906 filter_intra,
16907 smooth_neighbor,
16908 smooth_neighbor_uv,
16909 palette_y: palette_y_buf.clone(),
16910 palette_uv: palette_uv_bufs.clone(),
16911 };
16912 if palette_y.is_some() || palette_uv.is_some() {
16913 hit!(PALETTE_SPLIT_TX_HITS);
16914 }
16915 decode_rect_split(
16916 dec,
16917 cdfs,
16918 neighbours,
16919 (mi_r, mi_c),
16920 bw,
16921 bh,
16922 tx_w,
16923 tx_h,
16924 &modes,
16925 y,
16926 u,
16927 v,
16928 base_q_idx,
16929 false,
16930 fctx,
16931 )?;
16932 record_strip_palette(
16933 neighbours,
16934 pal_at,
16935 bw,
16936 bh,
16937 pal_y_size,
16938 pal_y_colors,
16939 pal_uv_size,
16940 pal_uv_colors,
16941 );
16942 if bw > bh {
16943 hit!(RECT4_32_HORZ_HITS);
16944 } else {
16945 hit!(RECT4_32_VERT_HITS);
16946 }
16947 if !skip {
16948 hit!(RECT4_COEFF_HITS);
16949 }
16950 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16951 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16952 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16953 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16954 // transform size in both TXFM_CONTEXT bands. Without it the next block
16955 // reads the row's stale value.
16956 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16957 return Ok((mode, uv_predict_mode));
16958 }
16959 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16960 // that is 8 px tall, so each strip stamps every cell it touches and the
16961 // LAST strip wins -- which is the right answer for the block below/right
16962 // of the 32x32, the only reader outside it. Written after this strip's
16963 // own context read above, never before.
16964 for cell in 0..bw.div_ceil(SUB) {
16965 neighbours.above_mode[c + cell] = mode;
16966 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16967 neighbours.above_side[c + cell] = bw;
16968 }
16969 for cell in 0..bh.div_ceil(SUB) {
16970 neighbours.left_mode[r + cell] = mode;
16971 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16972 neighbours.left_side[r + cell] = bh;
16973 }
16974 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16975 // [`decode_leaf_rect`] does (the split arm above records these through
16976 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16977 // `sub8_mode_row` holding the previous block, and the next 32x32's
16978 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16979 // fixture).
16980 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16981 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16982 let (px, py) = (mi_c * MI, mi_r * MI);
16983 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16984 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16985 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16986 // lane-av1-444: the strip's chroma shape follows the subsampling.
16987 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16988 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16989 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16990 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16991 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16992 // and 1/1 only -- so the table is exhaustive.
16993 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16994 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16995 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16996 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16997 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16998 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16999 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
17000 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
17001 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
17002 // [`decode_rect_split`]'s chroma table use.
17003 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
17004 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
17005 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
17006 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
17007 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
17008 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
17009 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
17010 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
17011 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
17012 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
17013 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
17014 // instead of refusing; no coefficient-table row is added, because
17015 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
17016 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
17017 // 4:2:2-only.
17018 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
17019 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
17020 // lane-av1-422p: the units' own set/scan -- the whole-rect read
17021 // below never sees this row, the `chroma422_rect32` arm chunks
17022 // first. Anything else is still a named-lane gap.
17023 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
17024 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
17025 };
17026 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
17027 let (luma_levels, u_levels, v_levels) = if skip {
17028 (
17029 vec![0i32; bw * bh],
17030 vec![0i32; chroma_w * chroma_h],
17031 vec![0i32; chroma_w * chroma_h],
17032 )
17033 } else if chroma422_rect32 {
17034 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
17035 // plane-major (every U unit, then every V) -- the walk the pinned
17036 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
17037 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
17038 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
17039 // Luma is the same single TX_8X32 rect the general arm reads.
17040 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17041 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
17042 let (luma_levels, luma_tx_type) = read_coeffs_rect(
17043 dec,
17044 &mut luma_coding,
17045 luma_scan,
17046 bw,
17047 bh,
17048 0,
17049 dc_sign_ctx(around[0].2),
17050 TxType::DctDct,
17051 0,
17052 )?;
17053 hit!(RECT4_COEFF_HITS);
17054 let luma_residual = dequant_and_inverse_typed_wh(
17055 &luma_levels,
17056 bw,
17057 bh,
17058 crate::decode::bit_depth(fctx),
17059 block_q_idx(fctx),
17060 plane_q_delta(0, fctx).0,
17061 plane_q_delta(0, fctx).1,
17062 luma_tx_type,
17063 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
17064 );
17065 if let Some(b) = &palette_y_buf {
17066 set_palette_pred(b.clone(), fctx);
17067 }
17068 push_intra_rect(
17069 0,
17070 px,
17071 py,
17072 bw,
17073 bh,
17074 mode,
17075 angle_delta_y,
17076 reach,
17077 &luma_residual,
17078 None,
17079 filter_intra,
17080 smooth_neighbor,
17081 fctx,
17082 );
17083 // CfL parameters are computed ONCE per block over the strip's luma
17084 // (`are_parameters_computed`) and shared by all four units, as in
17085 // every other chunk arm.
17086 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
17087 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
17088 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
17089 for unit_row in 0..4usize {
17090 let unit_mi = (mi_r + unit_row * 2, mi_c);
17091 let unit_reach = tu_reach_rect(
17092 bw,
17093 bh,
17094 0,
17095 unit_row * 8,
17096 8,
17097 8,
17098 reach,
17099 px,
17100 py,
17101 y.width,
17102 y.height,
17103 fctx,
17104 );
17105 if let Some((ub, vb)) = &palette_uv_bufs {
17106 let pbuf = if plane == 1 { ub } else { vb };
17107 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
17108 }
17109 // Each unit is read and recorded IMMEDIATELY: unit row 0's
17110 // `txb_skip_ctx` still sees the real above/left neighbour
17111 // states, a lower unit sees this block's own upper unit's
17112 // (libaom's per-unit `set_entropy_context`), and the lower
17113 // unit predicts off the upper one's reconstructed samples.
17114 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
17115 let unit_grid = read_rect_chroma_unit(
17116 dec,
17117 cdfs,
17118 TxbSet::ChromaRect8x4,
17119 &SCAN_4X8,
17120 4,
17121 8,
17122 plane,
17123 chroma_around[plane],
17124 uv_predict_mode,
17125 angle_delta_uv,
17126 unit_reach,
17127 buf,
17128 cpx,
17129 cpy + unit_row * 8,
17130 base_q_idx,
17131 // `get_txb_ctx_general`'s chroma branch
17132 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
17133 // here, `num_pels_log2_lookup[255]` = 255 (the +255
17134 // byte of the decodetxb copy at 0xc0de70,
17135 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
17136 // ctx_offset is 10 -- the port's offset-7-first
17137 // `txb_skip_chroma_8` stores the offset-10 rows at
17138 // rows 3..6, hence +3.
17139 Some(3),
17140 alpha
17141 .zip(ac)
17142 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17143 smooth_neighbor_uv,
17144 fctx,
17145 )?;
17146 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
17147 unit_grids.push((unit_mi, plane, unit_grid));
17148 }
17149 }
17150 // The whole-block stamp rewrites the chroma cells ONE state wide,
17151 // which would erase the unit boundary the next block reads (class
17152 // `override-slot-on-one-arm`), so it carries zero chroma grids and
17153 // the per-unit writes replay after it. Its luma cells and side
17154 // spans are this arm's own bookkeeping.
17155 let zero_chroma = vec![0i32; chroma_w * chroma_h];
17156 neighbours.record_mi_rect(
17157 (mi_r, mi_c),
17158 bw,
17159 bh,
17160 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
17161 );
17162 for (unit_mi, plane, grid) in &unit_grids {
17163 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
17164 }
17165 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
17166 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
17167 record_strip_palette(
17168 neighbours,
17169 pal_at,
17170 bw,
17171 bh,
17172 pal_y_size,
17173 pal_y_colors,
17174 pal_uv_size,
17175 pal_uv_colors,
17176 );
17177 if bw > bh {
17178 hit!(RECT4_32_HORZ_HITS);
17179 } else {
17180 hit!(RECT4_32_VERT_HITS);
17181 }
17182 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
17183 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
17184 // frame, so this 1:4 strip -- which is also the INTER frame's reader
17185 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
17186 // transform size in both TXFM_CONTEXT bands. Without it the next block
17187 // reads the row's stale value.
17188 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
17189 return Ok((mode, uv_predict_mode));
17190 } else {
17191 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17192 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
17193 let (luma_levels, luma_tx_type) = read_coeffs_rect(
17194 dec,
17195 &mut luma_coding,
17196 luma_scan,
17197 bw,
17198 bh,
17199 0,
17200 dc_sign_ctx(around[0].2),
17201 TxType::DctDct,
17202 0,
17203 )?;
17204 let mut planes = Vec::with_capacity(2);
17205 for plane in 1..3 {
17206 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
17207 // stands only while it is a member of this tx size's set; a
17208 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
17209 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
17210 // to DCT_DCT there, and ADST is undefined at widths above 16.
17211 let default_tx = if chroma_w.max(chroma_h) >= 32 {
17212 TxType::DctDct
17213 } else {
17214 default_intra_tx_type(uv_predict_mode as u8)
17215 };
17216 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
17217 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
17218 let (levels, tx_type) = read_chroma_coeffs_rect(
17219 dec,
17220 &mut coding,
17221 chroma_scan,
17222 chroma_w,
17223 chroma_h,
17224 skip_ctx,
17225 dc_sign_ctx(around[plane].2),
17226 default_tx,
17227 fctx,
17228 plane,
17229 )?;
17230 planes.push((levels, tx_type));
17231 }
17232 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
17233 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
17234 hit!(RECT4_COEFF_HITS);
17235 let luma_residual = dequant_and_inverse_typed_wh(
17236 &luma_levels,
17237 bw,
17238 bh,
17239 crate::decode::bit_depth(fctx),
17240 block_q_idx(fctx),
17241 plane_q_delta(0, fctx).0,
17242 plane_q_delta(0, fctx).1,
17243 luma_tx_type,
17244 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
17245 );
17246 if let Some(b) = &palette_y_buf {
17247 set_palette_pred(b.clone(), fctx);
17248 }
17249 push_intra_rect(
17250 0,
17251 px,
17252 py,
17253 bw,
17254 bh,
17255 mode,
17256 angle_delta_y,
17257 reach,
17258 &luma_residual,
17259 None,
17260 filter_intra,
17261 smooth_neighbor,
17262 fctx,
17263 );
17264 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
17265 for (plane, _buf, levels, tx_type) in [
17266 (1usize, &mut *u, &u_levels, u_tx_type),
17267 (2, &mut *v, &v_levels, v_tx_type),
17268 ] {
17269 let residual = dequant_and_inverse_typed_wh(
17270 levels,
17271 chroma_w,
17272 chroma_h,
17273 crate::decode::bit_depth(fctx),
17274 block_q_idx(fctx),
17275 plane_q_delta(plane, fctx).0,
17276 plane_q_delta(plane, fctx).1,
17277 tx_type,
17278 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
17279 );
17280 if let Some((ub, vb)) = &palette_uv_bufs {
17281 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
17282 }
17283 push_intra_rect(
17284 plane,
17285 cpx,
17286 cpy,
17287 chroma_w,
17288 chroma_h,
17289 uv_predict_mode,
17290 angle_delta_uv,
17291 reach,
17292 &residual,
17293 alpha
17294 .zip(ac)
17295 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17296 None,
17297 smooth_neighbor_uv,
17298 fctx,
17299 );
17300 }
17301 neighbours.record_mi_rect(
17302 (mi_r, mi_c),
17303 bw,
17304 bh,
17305 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
17306 );
17307 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
17308 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
17309 record_strip_palette(
17310 neighbours,
17311 pal_at,
17312 bw,
17313 bh,
17314 pal_y_size,
17315 pal_y_colors,
17316 pal_uv_size,
17317 pal_uv_colors,
17318 );
17319 if bw > bh {
17320 hit!(RECT4_32_HORZ_HITS);
17321 } else {
17322 hit!(RECT4_32_VERT_HITS);
17323 }
17324 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
17325 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
17326 // frame, so this 1:4 strip -- which is also the INTER frame's reader
17327 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
17328 // transform size in both TXFM_CONTEXT bands. Without it the next block
17329 // reads the row's stale value.
17330 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
17331 return Ok((mode, uv_predict_mode));
17332 };
17333 if let Some(b) = &palette_y_buf {
17334 set_palette_pred(b.clone(), fctx);
17335 }
17336 push_intra_rect(
17337 0,
17338 px,
17339 py,
17340 bw,
17341 bh,
17342 mode,
17343 angle_delta_y,
17344 reach,
17345 &luma_levels,
17346 None,
17347 filter_intra,
17348 smooth_neighbor,
17349 fctx,
17350 );
17351 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
17352 if chroma422_rect32 {
17353 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
17354 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
17355 // arm walks the same four TX_4X8 units per plane -- the lower unit
17356 // predicts off the upper one's predicted samples. No coefficients
17357 // are coded; the tail's whole-block zero stamp below is the state
17358 // libaom's `set_entropy_context` leaves.
17359 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
17360 for unit_row in 0..4usize {
17361 let unit_reach = tu_reach_rect(
17362 bw,
17363 bh,
17364 0,
17365 unit_row * 8,
17366 8,
17367 8,
17368 reach,
17369 px,
17370 py,
17371 y.width,
17372 y.height,
17373 fctx,
17374 );
17375 if let Some((ub, vb)) = &palette_uv_bufs {
17376 let pbuf = if plane == 1 { ub } else { vb };
17377 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
17378 }
17379 push_intra_rect(
17380 plane,
17381 cpx,
17382 cpy + unit_row * 8,
17383 4,
17384 8,
17385 uv_predict_mode,
17386 angle_delta_uv,
17387 unit_reach,
17388 &ZERO_RESIDUAL[..4 * 8],
17389 alpha
17390 .zip(ac)
17391 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17392 None,
17393 smooth_neighbor_uv,
17394 fctx,
17395 );
17396 }
17397 }
17398 } else {
17399 if let Some((ub, _)) = &palette_uv_bufs {
17400 set_palette_pred(ub.clone(), fctx);
17401 }
17402 push_intra_rect(
17403 1,
17404 cpx,
17405 cpy,
17406 chroma_w,
17407 chroma_h,
17408 uv_predict_mode,
17409 angle_delta_uv,
17410 reach,
17411 &u_levels,
17412 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17413 None,
17414 smooth_neighbor_uv,
17415 fctx,
17416 );
17417 if let Some((_, vb)) = &palette_uv_bufs {
17418 set_palette_pred(vb.clone(), fctx);
17419 }
17420 push_intra_rect(
17421 2,
17422 cpx,
17423 cpy,
17424 chroma_w,
17425 chroma_h,
17426 uv_predict_mode,
17427 angle_delta_uv,
17428 reach,
17429 &v_levels,
17430 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17431 None,
17432 smooth_neighbor_uv,
17433 fctx,
17434 );
17435 }
17436 neighbours.record_mi_rect(
17437 (mi_r, mi_c),
17438 bw,
17439 bh,
17440 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
17441 );
17442 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
17443 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
17444 record_strip_palette(
17445 neighbours,
17446 pal_at,
17447 bw,
17448 bh,
17449 pal_y_size,
17450 pal_y_colors,
17451 pal_uv_size,
17452 pal_uv_colors,
17453 );
17454 if bw > bh {
17455 hit!(RECT4_32_HORZ_HITS);
17456 } else {
17457 hit!(RECT4_32_VERT_HITS);
17458 }
17459 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
17460 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
17461 // frame, so this 1:4 strip -- which is also the INTER frame's reader
17462 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
17463 // transform size in both TXFM_CONTEXT bands. Without it the next block
17464 // reads the row's stale value.
17465 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
17466 Ok((mode, uv_predict_mode))
17467}
17468
17469/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
17470/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
17471/// down, and the first shape here whose luma block is a single mi row (or
17472/// column).
17473///
17474/// What is new at this size is CHROMA. `is_chroma_reference`
17475/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
17476/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
17477/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
17478/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
17479/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
17480/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
17481/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
17482///
17483/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
17484/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
17485/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
17486/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
17487/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
17488/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
17489/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
17490/// shape's own CDF row.
17491///
17492/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
17493/// refuses by name rather than guess-decode.
17494#[allow(clippy::too_many_arguments)]
17495fn decode_rect4_16(
17496 dec: &mut SymbolDecoder,
17497 cdfs: &mut Cdfs,
17498 neighbours: &mut Neighbours,
17499 at16: (usize, usize),
17500 horz: bool,
17501 y: &mut PlaneBuf<'static>,
17502 u: &mut PlaneBuf<'static>,
17503 v: &mut PlaneBuf<'static>,
17504 enable_filter_intra: bool,
17505 allow_screen_content_tools: bool,
17506 base_q_idx: u8,
17507 tx_select: bool,
17508 reduced_tx_set: bool,
17509 fctx: &crate::decode::FrameCtx,
17510) -> Result<()> {
17511 let (r, c) = at16;
17512 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
17513 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
17514 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
17515 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
17516 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
17517 let mut prev: Option<((usize, usize), usize)> = None;
17518 let mut last_mode = DC_PRED;
17519 let mut last_uv_mode = DC_PRED;
17520 for i in 0..4usize {
17521 let lmi = if horz {
17522 (mi_row0 + i, mi_col0)
17523 } else {
17524 (mi_row0, mi_col0 + i)
17525 };
17526 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
17527 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
17528 // already >= 4x4) -- there is no 4:2:0 pair to close.
17529 // lane-av1-422o: the parity rule is per axis, straight out of
17530 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
17531 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
17532 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
17533 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
17534 // every ss_x == 1 format -- the ODD strip closes the pair and reads
17535 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
17536 // even mi_col, so `i % 2 == 1` is that clause.)
17537 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
17538 let (mode, uv, _tx) = decode_rect4_16_strip(
17539 dec,
17540 cdfs,
17541 neighbours,
17542 lmi,
17543 horz,
17544 has_chroma,
17545 prev,
17546 y,
17547 u,
17548 v,
17549 enable_filter_intra,
17550 allow_screen_content_tools,
17551 base_q_idx,
17552 tx_select,
17553 reduced_tx_set,
17554 fctx,
17555 )?;
17556 if let Some(m) = uv {
17557 last_uv_mode = m;
17558 }
17559 last_mode = mode;
17560 prev = Some((lmi, mode));
17561 }
17562 // The coarse 16-px cell holds one entry for the whole 16x16: the last
17563 // strip is what a block below (right) sees through it, the mi-exact maps
17564 // above answering everything finer.
17565 neighbours.above_mode[c] = last_mode;
17566 neighbours.left_mode[r] = last_mode;
17567 neighbours.above_uv_mode[c] = last_uv_mode;
17568 neighbours.left_uv_mode[r] = last_uv_mode;
17569 neighbours.above_side[c] = bw;
17570 neighbours.left_side[r] = bh;
17571 Ok(())
17572}
17573
17574/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
17575/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
17576/// block path can decode a SINGLE intra strip of a partition whose other
17577/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
17578/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
17579/// every strip publishes its own mi-exact mode). Returns
17580/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
17581/// Intrabc reconstruction for a rect strip that OWNS its chroma
17582/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
17583/// pair goes through [`decode_rect4_16_intrabc`].
17584///
17585/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
17586/// (predict once, then one residual per transform unit on the INTER sets,
17587/// chroma inherits luma's `tx_type`), written against the helpers that exist
17588/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
17589/// merge with lane-av1-intrabc should keep one of the two bodies; the call
17590/// shape is the same.
17591#[allow(clippy::too_many_arguments)]
17592fn decode_intrabc_owned_rect(
17593 dec: &mut SymbolDecoder,
17594 cdfs: &mut Cdfs,
17595 neighbours: &mut Neighbours,
17596 (mi_r, mi_c): (usize, usize),
17597 (bw, bh): (usize, usize),
17598 skip: bool,
17599 (dv_row, dv_col): (i32, i32),
17600 y: &mut PlaneBuf<'static>,
17601 u: &mut PlaneBuf<'static>,
17602 v: &mut PlaneBuf<'static>,
17603 base_q_idx: u8,
17604 tx_select: bool,
17605 reduced_tx_set: bool,
17606 fctx: &crate::decode::FrameCtx,
17607) -> Result<()> {
17608 let _ = base_q_idx;
17609 let (px, py) = (mi_c * MI, mi_r * MI);
17610 // lane-av1chromarect: libaom does NOT halve a 128-root intra-BC strip's
17611 // chroma plane block. `av1_get_max_uv_txsize` (blockd.h:1372) is
17612 // `max_txsize_rect_lookup[get_plane_block_size(bsize, ss_x, ss_y)]` run
17613 // through `av1_get_adjusted_tx_size`, and `get_plane_block_size` is
17614 // `ss_size_lookup[bsize]` -- at 4:4:4 the chroma plane block is the block's
17615 // OWN footprint, so the extent below and the eight chroma MV origin pairs
17616 // that follow must be `>> ss_x` / `>> ss_y`, not `/ 2`. At 4:2:0
17617 // (`ss_x == ss_y == 1`) the two forms are the same arithmetic.
17618 // MEASURED on the 4:4:4 LOSSY witness `fixtures/r512.obu` (6948 B, 3
17619 // frames, 5 strips through this function): with the halving, frame 0
17620 // diverges from the aomdec oracle in 166229 Y / 155383 U / 153498 V
17621 // samples and both later frames keep luma byte-exact while 74708 U +
17622 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
17623 // what makes this a chroma-sizing defect and not a block-geometry one.
17624 // Re-measured by this lane; see lanes/av1chromarect.report.md.
17625 if crate::envflags::env_flag!("EC_HALVSWEEP") {
17626 eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
17627 }
17628 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
17629 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
17630 let side = bw.max(bh);
17631 let cside = cw.max(ch);
17632 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
17633 hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS);
17634 }
17635 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17636 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
17637 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17638 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
17639 // false; the real bit is the caller's `tx_select`. Restored before return.
17640 fctx.tx_select_inter.with(|c| c.set(tx_select));
17641 let restore = ReducedTxRestore {
17642 fctx,
17643 saved_reduced,
17644 saved_tx,
17645 };
17646
17647 flush_recon(fctx, y, u, v);
17648 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
17649 let pred_u = predict_intrabc_window(u, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17650 let pred_v = predict_intrabc_window(v, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17651
17652 let mi_cols = 2 * y.true_width.div_ceil(8);
17653 let mi_rows = 2 * y.true_height.div_ceil(8);
17654 let leaves = read_block_tx_size_rect(
17655 dec,
17656 cdfs,
17657 neighbours,
17658 (mi_r, mi_c),
17659 (bw, bh),
17660 (mi_cols, mi_rows),
17661 skip,
17662 fctx,
17663 )?;
17664 let mut luma_tx_type = TxType::DctDct;
17665 let luma_grid;
17666 let u_grid;
17667 let v_grid;
17668 if skip {
17669 // `reconstruct_mc_rect` indexes the residual at the square stride.
17670 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
17671 push_mc_rect(
17672 0,
17673 px,
17674 py,
17675 side,
17676 bw,
17677 bh,
17678 Pred::Inline(&pred_y, side),
17679 &ZERO_RESIDUAL[..side * bh],
17680 fctx,
17681 );
17682 push_mc_rect(
17683 1,
17684 cpx,
17685 cpy,
17686 cside,
17687 cw,
17688 ch,
17689 Pred::Inline(&pred_u, cside),
17690 &ZERO_RESIDUAL[..cside * ch],
17691 fctx,
17692 );
17693 push_mc_rect(
17694 2,
17695 cpx,
17696 cpy,
17697 cside,
17698 cw,
17699 ch,
17700 Pred::Inline(&pred_v, cside),
17701 &ZERO_RESIDUAL[..cside * ch],
17702 fctx,
17703 );
17704 if let Some(ls) = leaves.as_ref() {
17705 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
17706 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
17707 // whole entropy-band footprint. The non-skip arm below writes
17708 // those bands per transform unit and the tail's
17709 // `record_split_luma_rect_mi` writes chroma only, so without
17710 // this walk a skipped strip whose `leaves` resolved (every
17711 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
17712 // returns the 4x4 grid before it looks at `skip`) leaked the
17713 // PREVIOUS occupant's luma bands into the next block's
17714 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
17715 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
17716 // stream left a stale 7 in left[48] and mi(48,68)'s first
17717 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
17718 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
17719 for &(row, col, tw, th) in ls {
17720 neighbours.record_mi_luma_rect(
17721 (mi_r + row, mi_c + col),
17722 tw,
17723 th,
17724 &ZERO_RESIDUAL[..tw * th],
17725 );
17726 }
17727 }
17728 luma_grid = Grid::Zero(side * side);
17729 u_grid = Grid::Zero(cside * cside);
17730 v_grid = Grid::Zero(cside * cside);
17731 } else if let Some(ls) = leaves.as_ref() {
17732 let mut leaf_types: Vec<(usize, usize, usize, usize, TxType)> =
17733 Vec::with_capacity(ls.len());
17734 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17735 let tu_mi = (mi_r + row, mi_c + col);
17736 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17737 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17738 let (g, tt) = if tw == th {
17739 read_inter_plane(
17740 dec,
17741 cdfs,
17742 inter_txbset_for(tw, reduced_tx_set),
17743 &default_scan(tw.min(32)),
17744 0,
17745 neighbours.around_mi(tu_mi, tw)[0],
17746 0,
17747 y,
17748 tu_px,
17749 tu_py,
17750 tw,
17751 base_q_idx,
17752 tu_pred,
17753 None,
17754 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17755 fctx,
17756 )?
17757 } else {
17758 read_inter_plane_rect(
17759 dec,
17760 cdfs,
17761 rect_inter_luma_set(tw, th, fctx)?,
17762 (tw, th),
17763 side,
17764 0,
17765 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17766 0,
17767 y,
17768 tu_px,
17769 tu_py,
17770 tu_pred,
17771 None,
17772 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17773 fctx,
17774 )?
17775 };
17776 leaf_types.push((row, col, tw, th, tt));
17777 if idx == 0 {
17778 luma_tx_type = tt;
17779 }
17780 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17781 if tw != th {
17782 neighbours.fill_lf_grid_leaf_luma(
17783 (tu_mi.0, tu_mi.1),
17784 tw / MI,
17785 th / MI,
17786 tw as u8,
17787 th as u8,
17788 );
17789 }
17790 }
17791 luma_grid = Grid::Zero(side * side);
17792 if cw.min(32) != cw || ch.min(32) != ch {
17793 // lane-av1chromarect: more than one chroma transform unit (the
17794 // 4:4:4 32x64/64x32 plane block). See the helper.
17795 let (ug, vg) = read_intrabc_rect_chroma_split(
17796 dec,
17797 cdfs,
17798 neighbours,
17799 (mi_r, mi_c),
17800 (cpx, cpy),
17801 (cw, ch),
17802 cside,
17803 &pred_u,
17804 &pred_v,
17805 &leaf_types,
17806 luma_tx_type,
17807 u,
17808 v,
17809 fctx,
17810 )?;
17811 u_grid = ug;
17812 v_grid = vg;
17813 } else {
17814 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17815 let (ug, _) = read_inter_plane_rect(
17816 dec,
17817 cdfs,
17818 rect_inter_chroma_set(cw, ch)?,
17819 (cw, ch),
17820 cside,
17821 1,
17822 around[1],
17823 0,
17824 u,
17825 cpx,
17826 cpy,
17827 Pred::Inline(&pred_u, cside),
17828 Some(luma_tx_type),
17829 None,
17830 fctx,
17831 )?;
17832 let (vg, _) = read_inter_plane_rect(
17833 dec,
17834 cdfs,
17835 rect_inter_chroma_set(cw, ch)?,
17836 (cw, ch),
17837 cside,
17838 2,
17839 around[2],
17840 0,
17841 v,
17842 cpx,
17843 cpy,
17844 Pred::Inline(&pred_v, cside),
17845 Some(luma_tx_type),
17846 None,
17847 fctx,
17848 )?;
17849 u_grid = ug;
17850 v_grid = vg;
17851 }
17852 } else {
17853 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17854 let (g, tt) = read_inter_plane_rect(
17855 dec,
17856 cdfs,
17857 rect_inter_luma_set(bw, bh, fctx)?,
17858 (bw, bh),
17859 side,
17860 0,
17861 around[0],
17862 0,
17863 y,
17864 px,
17865 py,
17866 Pred::Inline(&pred_y, side),
17867 None,
17868 None,
17869 fctx,
17870 )?;
17871 luma_tx_type = tt;
17872 luma_grid = g;
17873 if cw.min(32) != cw || ch.min(32) != ch {
17874 // lane-av1chromarect: more than one chroma transform unit (the
17875 // 4:4:4 32x64/64x32 plane block). See the helper.
17876 let (ug, vg) = read_intrabc_rect_chroma_split(
17877 dec,
17878 cdfs,
17879 neighbours,
17880 (mi_r, mi_c),
17881 (cpx, cpy),
17882 (cw, ch),
17883 cside,
17884 &pred_u,
17885 &pred_v,
17886 &[],
17887 luma_tx_type,
17888 u,
17889 v,
17890 fctx,
17891 )?;
17892 u_grid = ug;
17893 v_grid = vg;
17894 } else {
17895 let (ug, _) = read_inter_plane_rect(
17896 dec,
17897 cdfs,
17898 rect_inter_chroma_set(cw, ch)?,
17899 (cw, ch),
17900 cside,
17901 1,
17902 around[1],
17903 0,
17904 u,
17905 cpx,
17906 cpy,
17907 Pred::Inline(&pred_u, cside),
17908 Some(luma_tx_type),
17909 None,
17910 fctx,
17911 )?;
17912 let (vg, _) = read_inter_plane_rect(
17913 dec,
17914 cdfs,
17915 rect_inter_chroma_set(cw, ch)?,
17916 (cw, ch),
17917 cside,
17918 2,
17919 around[2],
17920 0,
17921 v,
17922 cpx,
17923 cpy,
17924 Pred::Inline(&pred_v, cside),
17925 Some(luma_tx_type),
17926 None,
17927 fctx,
17928 )?;
17929 u_grid = ug;
17930 v_grid = vg;
17931 }
17932 }
17933 drop(restore);
17934 // lane-av1chromarect: when the chroma plane block was walked as SEVERAL
17935 // transform units, each unit stamped its own span through
17936 // `record_mi_chroma` and the whole-block stamp below would overwrite them
17937 // with one state (class `override-slot-on-one-arm`). libaom keeps the
17938 // per-unit above/left contexts distinct; the next block's first unit
17939 // reads them.
17940 // `!skip` matters: a SKIPPED strip reads no chroma unit at all (its whole
17941 // chroma plane block is one `push_mc_rect` of `ZERO_RESIDUAL`), so no
17942 // per-unit `record_mi_chroma` ran and the whole-block chroma stamp below
17943 // is still the only one that happens.
17944 let chroma_split_units = !skip && (cw.min(32) != cw || ch.min(32) != ch);
17945 if leaves.is_some() {
17946 if chroma_split_units {
17947 neighbours.record_split_luma_rect_mi_modes((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED);
17948 } else {
17949 neighbours.record_split_luma_rect_mi(
17950 (mi_r, mi_c),
17951 bw,
17952 bh,
17953 DC_PRED,
17954 DC_PRED,
17955 [&u_grid, &v_grid],
17956 );
17957 }
17958 } else if chroma_split_units {
17959 neighbours.record_rect_mi_luma_only((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &luma_grid);
17960 } else {
17961 neighbours.record_rect_mi(
17962 (mi_r, mi_c),
17963 bw,
17964 bh,
17965 DC_PRED,
17966 DC_PRED,
17967 &[&luma_grid, &u_grid, &v_grid],
17968 );
17969 }
17970 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17971 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17972 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17973 // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree
17974 // published the bands, so no whole-footprint publish here.
17975 neighbours.fill_lf_grid_rect_after_vartx(
17976 (mi_r, mi_c),
17977 bw / MI,
17978 bh / MI,
17979 bw.min(64) as u8,
17980 bh.min(64) as u8,
17981 0,
17982 fctx,
17983 );
17984 record_intrabc_mi_rect(
17985 mi_r,
17986 mi_c,
17987 bw / MI,
17988 bh / MI,
17989 Some((dv_row, dv_col)),
17990 neighbours,
17991 fctx,
17992 );
17993 let _ = luma_tx_type;
17994 Ok(())
17995}
17996
17997/// The chroma plane block of a 128-root intra-BC HORZ/VERT strip when that
17998/// plane block needs MORE THAN ONE transform unit -- the 4:4:4 cell, and the
17999/// 4:2:0 cell of a strip with a 128-px axis.
18000///
18001/// libaom never forms a 64-point CHROMA transform. `get_vartx_max_txsize`
18002/// (blockd.h:1447) returns `av1_get_adjusted_tx_size(max_txsize_rect_lookup
18003/// [plane_bsize])` and `av1_get_adjusted_tx_size` maps `TX_32X64`/`TX_64X32`
18004/// to `TX_32X32`; `decode_token_recon_block` (decodeframe.c:994-1004) then
18005/// steps the plane block by that size's mi units, and
18006/// `decode_reconstruct_tx`'s `tx_size == plane_tx_size || plane` arm never
18007/// recurses for chroma -- the same statement from the other side. So a 4:4:4
18008/// 32x64 chroma plane block is TWO stacked `TX_32X32` units, each with its
18009/// own eob, its own scan and its own coefficient context, NOT one 32x64 unit
18010/// whose coded corner happens to be 32x32: `av1_get_max_eob`'s 64-axis
18011/// truncation is a LUMA rule, and a chroma plane block is never 64 points
18012/// long to begin with.
18013///
18014/// That is exactly the tiling [`read_inter_rect_chroma`] implements
18015/// (`(write_chroma_w.min(32), write_chroma_h.min(32))` and the `nx * ny`
18016/// walk); this is the same walk for a caller that keeps its own grid
18017/// assembly and neighbour recording. The single-unit case is deliberately
18018/// NOT routed through here, so at 4:2:0 and at every 4:4:4 shape below 64
18019/// the caller keeps its own one-unit read verbatim.
18020#[allow(clippy::too_many_arguments)]
18021fn read_intrabc_rect_chroma_split(
18022 dec: &mut SymbolDecoder,
18023 cdfs: &mut Cdfs,
18024 neighbours: &mut Neighbours,
18025 (mi_r, mi_c): (usize, usize),
18026 (cpx, cpy): (usize, usize),
18027 (cw, ch): (usize, usize),
18028 cside: usize,
18029 pred_u: &[u16],
18030 pred_v: &[u16],
18031 leaf_tx_types: &[(usize, usize, usize, usize, TxType)],
18032 luma_tx_type: TxType,
18033 u: &mut PlaneBuf<'static>,
18034 v: &mut PlaneBuf<'static>,
18035 fctx: &crate::decode::FrameCtx,
18036) -> Result<(Grid, Grid)> {
18037 let (uw, uh) = (cw.min(32), ch.min(32));
18038 let (nx, ny) = (cw / uw, ch / uh);
18039 let set = rect_inter_chroma_set(uw, uh)?;
18040 let assembled_h = ch.max(cside);
18041 let mut assembled: [Vec<i32>; 2] = [
18042 vec![0i32; cside * assembled_h],
18043 vec![0i32; cside * assembled_h],
18044 ];
18045 for plane_idx in 1..=2 {
18046 let (src, buf) = if plane_idx == 1 {
18047 (pred_u, &mut *u)
18048 } else {
18049 (pred_v, &mut *v)
18050 };
18051 for cu_row in 0..ny {
18052 for cu_col in 0..nx {
18053 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
18054 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
18055 // lane-av1422llintra: the same ss (1, 0) above-column
18056 // double-count as the lossless walk at 12735 -- one chroma
18057 // column spans two luma mi columns and libaom reads one.
18058 // Identical at 4:2:0 and 4:4:4, where the plane block is
18059 // square.
18060 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
18061 neighbours.around_mi_422_chroma(cu_mi, span_x, span_y)
18062 } else {
18063 neighbours.around_mi_rect(cu_mi, span_x, span_y)
18064 };
18065 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
18066 let cu_pred = Pred::Inline(src, cside).offset(cu_row * uh * cside + cu_col * uw);
18067 // libaom's `av1_get_tx_type` (blockd.h:1287) reads
18068 // `xd->tx_type_map` at the chroma unit's OWN position scaled
18069 // back to luma, so a unit sitting over a luma leaf that coded
18070 // nothing takes that leaf's stamp, not the block-level one.
18071 let rel_mi = (cu_mi.0 - mi_r, cu_mi.1 - mi_c);
18072 let inherit_tx_type =
18073 covering_leaf_tx_type(leaf_tx_types, rel_mi).or(Some(luma_tx_type));
18074 let cu_grid = read_inter_plane_rect(
18075 dec,
18076 cdfs,
18077 set,
18078 (uw, uh),
18079 cside,
18080 plane_idx,
18081 cu_around[plane_idx],
18082 0,
18083 buf,
18084 cu_x,
18085 cu_y,
18086 cu_pred,
18087 inherit_tx_type,
18088 // `get_txb_ctx`: plus 10 when the plane block is bigger
18089 // than the transform -- the same offset-3 convention
18090 // `read_inter_rect_chroma` passes on this arm.
18091 Some(3),
18092 fctx,
18093 )?
18094 .0;
18095 // Immediately, so the next unit of this block reads this one's
18096 // coefficient context (libaom updates the chroma above/left
18097 // contexts per unit).
18098 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
18099 let dst = &mut assembled[plane_idx - 1];
18100 for rr in 0..uh {
18101 let start = (cu_row * uh + rr) * cside + cu_col * uw;
18102 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
18103 }
18104 }
18105 }
18106 }
18107 let [ug, vg] = assembled;
18108 Ok((Grid::Own(ug), Grid::Own(vg)))
18109}
18110
18111fn predict_intrabc_window(
18112 plane: &PlaneBuf<'_>,
18113 px: usize,
18114 py: usize,
18115 w: usize,
18116 h: usize,
18117 dv_col: i32,
18118 dv_row: i32,
18119 luma: bool,
18120 stride: usize,
18121 fctx: &crate::decode::FrameCtx,
18122) -> Vec<u16> {
18123 let mut dense = vec![0u16; w * h];
18124 mc::predict_with_filter(
18125 &plane.data,
18126 plane.width,
18127 plane.true_width,
18128 plane.true_height,
18129 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
18130 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
18131 w,
18132 h,
18133 mc::InterpFilterKind::Bilinear,
18134 &mut dense,
18135 fctx,
18136 );
18137 let mut laid = vec![0u16; stride * stride];
18138 for row in 0..h {
18139 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
18140 }
18141 laid
18142}
18143
18144struct ReducedTxRestore<'a> {
18145 fctx: &'a crate::decode::FrameCtx,
18146 saved_reduced: bool,
18147 saved_tx: bool,
18148}
18149impl Drop for ReducedTxRestore<'_> {
18150 fn drop(&mut self) {
18151 self.fctx
18152 .reduced_tx_set_inter
18153 .with(|c| c.set(self.saved_reduced));
18154 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
18155 }
18156}
18157
18158/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
18159///
18160/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
18161/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
18162/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
18163/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
18164/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
18165/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
18166/// strip's own footprint, copied from this strip's DV. The block is
18167/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
18168/// the luma unit's coded `tx_type`.
18169///
18170/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
18171/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
18172/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
18173/// would code chroma on every strip.
18174#[allow(clippy::too_many_arguments)]
18175fn decode_rect4_16_intrabc(
18176 dec: &mut SymbolDecoder,
18177 cdfs: &mut Cdfs,
18178 neighbours: &mut Neighbours,
18179 lmi: (usize, usize),
18180 horz: bool,
18181 has_chroma: bool,
18182 skip: bool,
18183 (dv_row, dv_col): (i32, i32),
18184 y: &mut PlaneBuf<'static>,
18185 u: &mut PlaneBuf<'static>,
18186 v: &mut PlaneBuf<'static>,
18187 base_q_idx: u8,
18188 tx_select: bool,
18189 reduced_tx_set: bool,
18190 fctx: &crate::decode::FrameCtx,
18191) -> Result<(usize, Option<usize>, (usize, usize))> {
18192 let _ = base_q_idx;
18193 hit!(RECT4_16_INTRABC_HITS);
18194 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
18195 let (mi_w, mi_h) = (bw / MI, bh / MI);
18196 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18197 let side = bw.max(bh);
18198 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
18199 // publishes `reduced_tx_set` into it; set it here too so a caller that
18200 // passed the bit explicitly cannot disagree with the set we read.
18201 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
18202 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
18203 let restored = scopeguard_reduced(fctx, saved_reduced);
18204
18205 flush_recon(fctx, y, u, v);
18206 let mut pred_y_dense = vec![0u16; bw * bh];
18207 mc::predict_with_filter(
18208 &y.data,
18209 y.width,
18210 y.true_width,
18211 y.true_height,
18212 mv_to_q4(px, dv_col, 0),
18213 mv_to_q4(py, dv_row, 0),
18214 bw,
18215 bh,
18216 mc::InterpFilterKind::Bilinear,
18217 &mut pred_y_dense,
18218 fctx,
18219 );
18220 let mut pred_y = vec![0u16; side * side];
18221 for row in 0..bh {
18222 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
18223 }
18224
18225 // lane-av1444rect r2 (the class this lane named, second instance): the
18226 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
18227 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
18228 // unconditionally true -- the strip is its own chroma reference, there is
18229 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
18230 // (VERT_4) at the strip's own origin, with its coefficient context read
18231 // over that same extent. The old constants instead predicted and coded an
18232 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
18233 //
18234 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
18235 // --enable-palette=1 --cq-level=60 --min-partition-size=4
18236 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
18237 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
18238 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
18239 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
18240 // twin of the same recipe is byte-exact.
18241 //
18242 // 4:2:0 alone keeps every constant below verbatim: a 1:4 strip's chroma
18243 // plane block is 4:2:0's PAIR (the block above / beside it), because at
18244 // ss (1,1) the strip's 8x2 chroma lies INSIDE that neighbour's chroma.
18245 //
18246 // lane-av1422luma: at ss (1,0) that containment is gone -- 4:2:2 subsamples
18247 // x only, so the strip's chroma is 8x4 (full height) at the STRIP'S OWN
18248 // origin, and libaom's own clause agrees: `is_chroma_reference`
18249 // (av1_common_int.h:1454) ends in `|| !subsampling_y`, which answers TRUE
18250 // for every block at ss_y 0. Reading the strip's chroma at the 4:2:0 pair
18251 // origin instead puts the unit one mi row high: on `s422_416x250_10b`
18252 // (416x250 10-bit, sha256 d6aa7f45...) that is the V/U pair's `txb_skip`
18253 // read at mi (51,84) -- ctx 2 where the oracle reads 8, `all_zero` decoded
18254 // as 1 instead of 0, and the frame desyncs from there (luma included).
18255 // The origin half is `lane/av1422seed`'s unlanded hunk, reproduced here so
18256 // the arm is measurable whole; the gather and the publication extents
18257 // below are this lane's. VERT_4 stays on the pair: `ss_size_lookup
18258 // [BLOCK_4X16][1][0]` is BLOCK_INVALID at 4:2:2, so only HORZ reaches it.
18259 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
18260 let own422 = ss_x(fctx) == 1 && ss_y(fctx) == 0 && horz;
18261 if own422 && has_chroma {
18262 hit!(INTRABC_RECT4_OWN_CHROMA422_HITS);
18263 }
18264 // One predicate for "this strip IS its own chroma reference": the strip's
18265 // own mi position, its own luma extent, and per-axis subsampled sizes.
18266 let own_chroma = own444 || own422;
18267 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
18268 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
18269 }
18270 let (pw, ph) = if own444 {
18271 (bw, bh)
18272 } else if horz {
18273 (16usize, 8usize)
18274 } else {
18275 (8, 16)
18276 };
18277 let (cw, ch) = if own_chroma {
18278 (bw >> ss_x(fctx), bh >> ss_y(fctx))
18279 } else {
18280 (pw / 2, ph / 2)
18281 };
18282 let pair_mi = if has_chroma {
18283 if own_chroma {
18284 lmi
18285 } else if horz {
18286 (lmi.0 - 1, lmi.1)
18287 } else {
18288 (lmi.0, lmi.1 - 1)
18289 }
18290 } else {
18291 lmi
18292 };
18293 let (cpx, cpy) = if has_chroma {
18294 if own_chroma {
18295 (px >> ss_x(fctx), py >> ss_y(fctx))
18296 } else {
18297 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
18298 }
18299 } else {
18300 (0, 0)
18301 };
18302 let cside = cw.max(ch);
18303 let (pred_u, pred_v) = if has_chroma {
18304 let mut ud = vec![0u16; cw * ch];
18305 mc::predict_with_filter(
18306 &u.data,
18307 u.width,
18308 u.true_width,
18309 u.true_height,
18310 mv_to_q4(cpx, dv_col, ss_x(fctx)),
18311 mv_to_q4(cpy, dv_row, ss_y(fctx)),
18312 cw,
18313 ch,
18314 mc::InterpFilterKind::Bilinear,
18315 &mut ud,
18316 fctx,
18317 );
18318 let mut us = vec![0u16; cside * cside];
18319 for row in 0..ch {
18320 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
18321 }
18322 let mut vd = vec![0u16; cw * ch];
18323 mc::predict_with_filter(
18324 &v.data,
18325 v.width,
18326 v.true_width,
18327 v.true_height,
18328 mv_to_q4(cpx, dv_col, ss_x(fctx)),
18329 mv_to_q4(cpy, dv_row, ss_y(fctx)),
18330 cw,
18331 ch,
18332 mc::InterpFilterKind::Bilinear,
18333 &mut vd,
18334 fctx,
18335 );
18336 let mut vs = vec![0u16; cside * cside];
18337 for row in 0..ch {
18338 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
18339 }
18340 (us, vs)
18341 } else {
18342 (Vec::new(), Vec::new())
18343 };
18344
18345 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
18346 // false for a key frame, so `read_block_tx_size_rect` would skip the
18347 // symbol; read it here against the parameter the intra path already uses.
18348 // A skipped intrabc block predicts the whole footprint once and codes
18349 // no residual (`decode_token_recon_block`'s inter branch). Lossless
18350 // still forces TX_4X4 when the block is coded.
18351 let leaves = if skip || (!lossless(fctx) && !tx_select) {
18352 None
18353 } else if lossless(fctx) {
18354 let mut leaves = Vec::new();
18355 for row in 0..bh / MI {
18356 for col in 0..bw / MI {
18357 leaves.push((row, col, 4usize, 4usize));
18358 }
18359 }
18360 // libaom's `else` branch (`!xd->lossless` fails the var-tx
18361 // condition): `set_txfm_ctxs(TX_4X4, ..)` over the block's own
18362 // width/height. Same reason as `read_block_tx_size_rect`'s arm --
18363 // it is what makes this body's `fill_lf_grid_rect_after_vartx`
18364 // suppression sound.
18365 txfm_partition_update_rect(neighbours, lmi, (4, 4), (bw, bh));
18366 Some(leaves)
18367 } else {
18368 let ctx = txfm_partition_ctx_rect(
18369 neighbours.above_txfm[lmi.1],
18370 neighbours.left_txfm[lmi.0],
18371 side,
18372 bw,
18373 bh,
18374 );
18375 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
18376 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18377 let (rng, _) = dec.debug_state();
18378 eprintln!(
18379 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
18380 lmi.0,
18381 lmi.1,
18382 u8::from(split)
18383 );
18384 }
18385 if !split {
18386 None
18387 } else {
18388 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
18389 let mi_cols = 2 * y.true_width.div_ceil(8);
18390 let mi_rows = 2 * y.true_height.div_ceil(8);
18391 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
18392 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
18393 let mut out = Vec::new();
18394 for row in (0..bh / MI).step_by(sub_h / MI) {
18395 for col in (0..bw / MI).step_by(sub_w / MI) {
18396 read_var_tx_size(
18397 dec,
18398 cdfs,
18399 neighbours,
18400 lmi,
18401 side,
18402 (max_w_mi, max_h_mi),
18403 (sub_w, sub_h),
18404 1,
18405 row,
18406 col,
18407 &mut out,
18408 );
18409 }
18410 }
18411 Some(out)
18412 }
18413 };
18414 let (tx_w, tx_h) = leaves
18415 .as_ref()
18416 .and_then(|ls| ls.first())
18417 .map_or((bw, bh), |l| (l.2, l.3));
18418
18419 let mut luma_tx_type = TxType::DctDct;
18420 let luma_grid;
18421 let mut u_grid = Grid::Zero(cw * ch);
18422 let mut v_grid = Grid::Zero(cw * ch);
18423 let chroma_stamped_per_unit;
18424
18425 if skip {
18426 push_mc_rect(
18427 0,
18428 px,
18429 py,
18430 side,
18431 bw,
18432 bh,
18433 Pred::Inline(&pred_y, side),
18434 &ZERO_RESIDUAL[..side * bh],
18435 fctx,
18436 );
18437 luma_grid = Grid::Zero(bw * bh);
18438 if has_chroma {
18439 push_mc_rect(
18440 1,
18441 cpx,
18442 cpy,
18443 cside,
18444 cw,
18445 ch,
18446 Pred::Inline(&pred_u, cside),
18447 &ZERO_RESIDUAL[..cside * ch],
18448 fctx,
18449 );
18450 push_mc_rect(
18451 2,
18452 cpx,
18453 cpy,
18454 cside,
18455 cw,
18456 ch,
18457 Pred::Inline(&pred_v, cside),
18458 &ZERO_RESIDUAL[..cside * ch],
18459 fctx,
18460 );
18461 }
18462 chroma_stamped_per_unit = false;
18463 } else if let Some(ls) = leaves.as_ref() {
18464 if lossless(fctx) {
18465 for &(row, col, _tw, _th) in ls {
18466 let tu_mi = (lmi.0 + row, lmi.1 + col);
18467 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
18468 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
18469 let (g, _) = read_inter_plane(
18470 dec,
18471 cdfs,
18472 if reduced_tx_set {
18473 TxbSet::Luma4Inter
18474 } else {
18475 TxbSet::Luma4InterSet1
18476 },
18477 &default_scan(4),
18478 0,
18479 neighbours.around_mi(tu_mi, 4)[0],
18480 0,
18481 y,
18482 tu_px,
18483 tu_py,
18484 4,
18485 base_q_idx,
18486 tu_pred,
18487 None,
18488 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
18489 fctx,
18490 )?;
18491 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
18492 }
18493 } else {
18494 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
18495 let tu_mi = (lmi.0 + row, lmi.1 + col);
18496 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
18497 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
18498 let (g, tt) = if tw == th {
18499 read_inter_plane(
18500 dec,
18501 cdfs,
18502 inter_txbset_for(tw, reduced_tx_set),
18503 &default_scan(tw.min(32)),
18504 0,
18505 neighbours.around_mi(tu_mi, tw)[0],
18506 0,
18507 y,
18508 tu_px,
18509 tu_py,
18510 tw,
18511 base_q_idx,
18512 tu_pred,
18513 None,
18514 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
18515 fctx,
18516 )?
18517 } else {
18518 read_inter_plane_rect(
18519 dec,
18520 cdfs,
18521 rect_inter_luma_set(tw, th, fctx)?,
18522 (tw, th),
18523 side,
18524 0,
18525 neighbours.around_mi_rect(tu_mi, tw, th)[0],
18526 0,
18527 y,
18528 tu_px,
18529 tu_py,
18530 tu_pred,
18531 None,
18532 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
18533 fctx,
18534 )?
18535 };
18536 if idx == 0 {
18537 luma_tx_type = tt;
18538 }
18539 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
18540 }
18541 }
18542 luma_grid = Grid::Zero(bw * bh);
18543 chroma_stamped_per_unit = has_chroma && lossless(fctx);
18544 if has_chroma && lossless(fctx) {
18545 let (mut uo, mut vo) = (Vec::new(), Vec::new());
18546 read_inter_chroma_lossless(
18547 dec,
18548 cdfs,
18549 neighbours,
18550 u,
18551 v,
18552 Pred::Inline(&pred_u, cside),
18553 Pred::Inline(&pred_v, cside),
18554 pair_mi,
18555 (cpx, cpy),
18556 (0, 0),
18557 (cw, ch),
18558 (cw, ch),
18559 cside,
18560 0,
18561 base_q_idx,
18562 &mut uo,
18563 &mut vo,
18564 fctx,
18565 )?;
18566 u_grid = if uo.is_empty() {
18567 Grid::Zero(cw * ch)
18568 } else {
18569 Grid::Own(uo)
18570 };
18571 v_grid = if vo.is_empty() {
18572 Grid::Zero(cw * ch)
18573 } else {
18574 Grid::Own(vo)
18575 };
18576 } else if has_chroma {
18577 // lane-av1422luma: the own-chroma route reads its context over its
18578 // OWN extent; at ss (1,0) it additionally goes through the
18579 // every-second-column gather (one chroma 4-px column spans two
18580 // luma mi columns, so the per-mi gather would count each column's
18581 // whole-unit dc sign twice and OR in cells the unit does not
18582 // cover) -- the same choice the `decode_rect4_16` chroma arm
18583 // makes at `decode.rs:19577`. 4:4:4 keeps the per-mi gather: at
18584 // ss_x 0 a chroma column IS a luma mi column, so sampling would
18585 // halve its own above span.
18586 let (gmi, gw, gh) = if own_chroma {
18587 (lmi, bw, bh)
18588 } else {
18589 (pair_mi, pw, ph)
18590 };
18591 let around = if own422 {
18592 neighbours.around_mi_422_chroma(gmi, gw, gh)
18593 } else {
18594 neighbours.around_mi_rect(gmi, gw, gh)
18595 };
18596 let (ug, _) = read_inter_plane_rect(
18597 dec,
18598 cdfs,
18599 rect_inter_chroma_set(cw, ch)?,
18600 (cw, ch),
18601 cside,
18602 1,
18603 around[1],
18604 0,
18605 u,
18606 cpx,
18607 cpy,
18608 Pred::Inline(&pred_u, cside),
18609 Some(luma_tx_type),
18610 None,
18611 fctx,
18612 )?;
18613 u_grid = ug;
18614 let (vg, _) = read_inter_plane_rect(
18615 dec,
18616 cdfs,
18617 rect_inter_chroma_set(cw, ch)?,
18618 (cw, ch),
18619 cside,
18620 2,
18621 around[2],
18622 0,
18623 v,
18624 cpx,
18625 cpy,
18626 Pred::Inline(&pred_v, cside),
18627 Some(luma_tx_type),
18628 None,
18629 fctx,
18630 )?;
18631 v_grid = vg;
18632 }
18633 } else {
18634 let around = neighbours.around_mi_rect(lmi, bw, bh);
18635 let (g, tt) = read_inter_plane_rect(
18636 dec,
18637 cdfs,
18638 rect_inter_luma_set(bw, bh, fctx)?,
18639 (bw, bh),
18640 side,
18641 0,
18642 around[0],
18643 0,
18644 y,
18645 px,
18646 py,
18647 Pred::Inline(&pred_y, side),
18648 None,
18649 None,
18650 fctx,
18651 )?;
18652 luma_tx_type = tt;
18653 luma_grid = g;
18654 chroma_stamped_per_unit = false;
18655 if has_chroma {
18656 // lane-av1422luma: as the lossless twin above -- own extent, and
18657 // the sampled gather at 4:2:2 only.
18658 let (gmi, gw, gh) = if own_chroma {
18659 (lmi, bw, bh)
18660 } else {
18661 (pair_mi, pw, ph)
18662 };
18663 let around = if own422 {
18664 neighbours.around_mi_422_chroma(gmi, gw, gh)
18665 } else {
18666 neighbours.around_mi_rect(gmi, gw, gh)
18667 };
18668 let (ug, _) = read_inter_plane_rect(
18669 dec,
18670 cdfs,
18671 rect_inter_chroma_set(cw, ch)?,
18672 (cw, ch),
18673 cside,
18674 1,
18675 around[1],
18676 0,
18677 u,
18678 cpx,
18679 cpy,
18680 Pred::Inline(&pred_u, cside),
18681 Some(luma_tx_type),
18682 None,
18683 fctx,
18684 )?;
18685 u_grid = ug;
18686 let (vg, _) = read_inter_plane_rect(
18687 dec,
18688 cdfs,
18689 rect_inter_chroma_set(cw, ch)?,
18690 (cw, ch),
18691 cside,
18692 2,
18693 around[2],
18694 0,
18695 v,
18696 cpx,
18697 cpy,
18698 Pred::Inline(&pred_v, cside),
18699 Some(luma_tx_type),
18700 None,
18701 fctx,
18702 )?;
18703 v_grid = vg;
18704 }
18705 }
18706 drop(restored);
18707
18708 if leaves.is_none() {
18709 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
18710 }
18711 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
18712 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18713 // lane-av1oddheightfork3: this body reads its own var-tx tree inline
18714 // (`read_var_tx_size` per child), so the bands are per-leaf already; the
18715 // whole-footprint publish overwrote them with the block's own size.
18716 neighbours.fill_lf_grid_rect_after_vartx(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18717 for cell in 0..mi_w {
18718 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18719 *slot = bw as u8;
18720 }
18721 }
18722 for cell in 0..mi_h {
18723 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18724 *slot = bh as u8;
18725 }
18726 }
18727 let mut last_uv = None;
18728 if has_chroma {
18729 hit!(RECT4_16_CHROMA_HITS);
18730 // lane-av1422luma: the uv-mode publication and the left/above skip
18731 // state below are the STRIP's own at 4:2:2 / 4:4:4 -- publishing the
18732 // pair extent (one mi row off, `ph`/`pw`) is what the NEXT block's
18733 // chroma skip context then reads.
18734 let (rmi, rw, rh) = if own_chroma {
18735 (lmi, bw, bh)
18736 } else {
18737 (pair_mi, pw, ph)
18738 };
18739 neighbours.record_uv_mode_mi(rmi.0, rmi.1, rw / MI, rh / MI, DC_PRED);
18740 if !chroma_stamped_per_unit {
18741 let u_state = neighbour_state(&u_grid);
18742 let v_state = neighbour_state(&v_grid);
18743 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18744 let bound_h = round_up_even(neighbours.mi_rows);
18745 let bound_w = round_up_even(neighbours.mi_cols);
18746 for cell in 0..(rh / MI) {
18747 if rmi.0 + cell < bound_h
18748 && let Some(slot) = neighbours.left.get_mut(rmi.0 + cell)
18749 {
18750 slot[1] = u_state;
18751 slot[2] = v_state;
18752 }
18753 }
18754 for cell in 0..(rw / MI) {
18755 if rmi.1 + cell < bound_w
18756 && let Some(slot) = neighbours.above.get_mut(rmi.1 + cell)
18757 {
18758 slot[1] = u_state;
18759 slot[2] = v_state;
18760 }
18761 }
18762 }
18763 last_uv = Some(DC_PRED);
18764 }
18765 if horz {
18766 hit!(RECT4_16_HORZ_HITS);
18767 } else {
18768 hit!(RECT4_16_VERT_HITS);
18769 }
18770 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
18771 if leaves.is_none() {
18772 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
18773 // with `skip && is_inter`, or the unsplit unit). A split tree already
18774 // published per leaf inside `read_var_tx_size`.
18775 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18776 }
18777 record_intrabc_mi_rect(
18778 lmi.0,
18779 lmi.1,
18780 mi_w,
18781 mi_h,
18782 Some((dv_row, dv_col)),
18783 neighbours,
18784 fctx,
18785 );
18786 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
18787}
18788
18789/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
18790/// including through `?`.
18791struct ReducedRestore<'a> {
18792 fctx: &'a crate::decode::FrameCtx,
18793 saved: bool,
18794}
18795impl Drop for ReducedRestore<'_> {
18796 fn drop(&mut self) {
18797 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
18798 }
18799}
18800fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
18801 ReducedRestore { fctx, saved }
18802}
18803
18804#[allow(clippy::too_many_arguments)]
18805fn decode_rect4_16_strip(
18806 dec: &mut SymbolDecoder,
18807 cdfs: &mut Cdfs,
18808 neighbours: &mut Neighbours,
18809 lmi: (usize, usize),
18810 horz: bool,
18811 has_chroma: bool,
18812 prev: Option<((usize, usize), usize)>,
18813 y: &mut PlaneBuf<'static>,
18814 u: &mut PlaneBuf<'static>,
18815 v: &mut PlaneBuf<'static>,
18816 enable_filter_intra: bool,
18817 allow_screen_content_tools: bool,
18818 base_q_idx: u8,
18819 tx_select: bool,
18820 reduced_tx_set: bool,
18821 fctx: &crate::decode::FrameCtx,
18822) -> Result<(usize, Option<usize>, (usize, usize))> {
18823 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
18824 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
18825 let (mi_w, mi_h) = (bw / MI, bh / MI);
18826 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
18827 let mut last_uv_mode: Option<usize> = None;
18828 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
18829 // aliases all four strips onto one entry, so the mi-exact map wins and
18830 // the previous strip stands in on the split axis.
18831 let mut above_mode = neighbours.above_mode[c];
18832 let mut left_mode = neighbours.left_mode[r];
18833 if let Some(((pr, pc), pmode)) = prev {
18834 if pc == lmi.1 && lmi.0 == pr + mi_h {
18835 above_mode = pmode;
18836 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
18837 left_mode = pmode;
18838 }
18839 }
18840 let (above_mode, left_mode) =
18841 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
18842 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
18843 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
18844 // off CDF row 0 and every cache hit off an empty cache.
18845 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
18846 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
18847 let (
18848 skip,
18849 mode,
18850 angle_delta_y,
18851 uv_mode,
18852 angle_delta_uv,
18853 alpha,
18854 filter_intra,
18855 palette_y,
18856 palette_uv,
18857 intrabc,
18858 ) = read_intra_mode_rect(
18859 dec,
18860 cdfs,
18861 above_mode,
18862 left_mode,
18863 true,
18864 has_chroma,
18865 bw,
18866 bh,
18867 enable_filter_intra,
18868 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
18869 allow_screen_content_tools,
18870 Some((palette_ctx, &palette_cache)),
18871 &palette_uv_cache,
18872 lmi.0,
18873 lmi.1,
18874 fctx,
18875 )?;
18876 if let Some(dv) = intrabc {
18877 return decode_rect4_16_intrabc(
18878 dec,
18879 cdfs,
18880 neighbours,
18881 lmi,
18882 horz,
18883 has_chroma,
18884 skip,
18885 dv,
18886 y,
18887 u,
18888 v,
18889 base_q_idx,
18890 tx_select,
18891 reduced_tx_set,
18892 fctx,
18893 );
18894 }
18895 if palette_y.is_some() || palette_uv.is_some() {
18896 hit!(RECT4_PALETTE_HITS);
18897 }
18898 // The colour-index map through the base colours IS the prediction.
18899 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
18900 // chroma transform this closing strip codes.
18901 let palette_y_buf: Option<Vec<u16>> = palette_y
18902 .as_ref()
18903 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
18904 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
18905 (
18906 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18907 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18908 )
18909 });
18910 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
18911 if smooth_neighbor {
18912 hit!(SMOOTH_LUMA_HITS);
18913 }
18914 if filter_intra.is_some() {
18915 hit!(FILTER_INTRA_RECT_HITS);
18916 }
18917 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
18918 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
18919 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
18920 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
18921 // lane-av1mixloss: the lossless-segment early return
18922 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
18923 // lossless-segment strip codes no depth symbol here either (class
18924 // sweep of the sub8 leaf's fix).
18925 let depth = if tx_select && !lossless(fctx) {
18926 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
18927 // (`get_tx_size_context`, libaom `pred_common.h:342`).
18928 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
18929 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
18930 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18931 eprintln!(
18932 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
18933 lmi.0,
18934 lmi.1,
18935 dec.debug_state().0
18936 );
18937 }
18938 d
18939 } else {
18940 0
18941 };
18942 if depth != 0 {
18943 hit!(TX_DEPTH_HITS);
18944 hit!(RECT4_16_SPLIT_HITS);
18945 }
18946 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18947 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18948 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18949 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
18950 if depth != 0 || lossless(fctx) {
18951 // [`decode_rect_split`]'s per-unit walk, inlined because the
18952 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
18953 // the strip (that function codes one chroma transform per block).
18954 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
18955 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
18956 // unit predicts off the units before it in raster order.
18957 let rect_unit = tx_w != tx_h;
18958 let zero_tu = vec![0i32; tx_w * tx_h];
18959 for tu_row in 0..bh / tx_h {
18960 for tu_col in 0..bw / tx_w {
18961 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
18962 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
18963 let tu_reach =
18964 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
18965 if let Some(b) = &palette_y_buf {
18966 let tu_buf: Vec<u16> = (0..tx_h)
18967 .flat_map(|i| {
18968 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
18969 b[base..base + tx_w].iter().copied()
18970 })
18971 .collect();
18972 set_palette_pred(tu_buf, fctx);
18973 }
18974 if skip {
18975 push_intra_rect(
18976 0,
18977 tu_px,
18978 tu_py,
18979 tx_w,
18980 tx_h,
18981 mode,
18982 angle_delta_y,
18983 tu_reach,
18984 &zero_tu,
18985 None,
18986 filter_intra,
18987 smooth_neighbor,
18988 fctx,
18989 );
18990 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
18991 } else if rect_unit {
18992 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
18993 // 32 coded positions and the `TX_4X4` `tx_type` row:
18994 // exactly [`TxbSet::LumaRect4x8`].
18995 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
18996 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
18997 let set = if reduced_tx_set {
18998 TxbSet::LumaRect4x8
18999 } else {
19000 TxbSet::LumaRect4x8Set1
19001 };
19002 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
19003 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
19004 let (tu_grid, tu_tx_type) = read_coeffs_rect(
19005 dec,
19006 &mut coding,
19007 tu_scan,
19008 tx_w,
19009 tx_h,
19010 tu_skip_ctx,
19011 dc_sign_ctx(tu_around.2),
19012 TxType::DctDct,
19013 0,
19014 )?;
19015 let residual = dequant_and_inverse_typed_wh(
19016 &tu_grid,
19017 tx_w,
19018 tx_h,
19019 crate::decode::bit_depth(fctx),
19020 block_q_idx(fctx),
19021 plane_q_delta(0, fctx).0,
19022 plane_q_delta(0, fctx).1,
19023 tu_tx_type,
19024 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
19025 );
19026 push_intra_rect(
19027 0,
19028 tu_px,
19029 tu_py,
19030 tx_w,
19031 tx_h,
19032 mode,
19033 angle_delta_y,
19034 tu_reach,
19035 &residual,
19036 None,
19037 filter_intra,
19038 smooth_neighbor,
19039 fctx,
19040 );
19041 if tu_grid.iter().any(|&l| l != 0) {
19042 hit!(RECT4_16_COEFF_HITS);
19043 }
19044 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
19045 } else {
19046 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
19047 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
19048 let tu_grid = read_plane(
19049 dec,
19050 cdfs,
19051 txbset_for(tx_w, reduced_tx_set),
19052 default_scan(tx_w),
19053 0,
19054 tu_around,
19055 mode,
19056 mode,
19057 angle_delta_y,
19058 tu_reach,
19059 y,
19060 tu_px,
19061 tu_py,
19062 tx_w,
19063 tx_w,
19064 base_q_idx,
19065 None,
19066 filter_intra,
19067 Some(tu_skip_ctx),
19068 smooth_neighbor,
19069 fctx,
19070 )?;
19071 if tu_grid.iter().any(|&l| l != 0) {
19072 hit!(RECT4_16_COEFF_HITS);
19073 }
19074 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
19075 }
19076 }
19077 }
19078 } else {
19079 let levels = if skip {
19080 let zeros = Grid::Zero(bw * bh);
19081 if let Some(b) = &palette_y_buf {
19082 set_palette_pred(b.clone(), fctx);
19083 }
19084 push_intra_rect(
19085 0,
19086 px,
19087 py,
19088 bw,
19089 bh,
19090 mode,
19091 angle_delta_y,
19092 reach,
19093 &zeros,
19094 None,
19095 filter_intra,
19096 smooth_neighbor,
19097 fctx,
19098 );
19099 zeros
19100 } else {
19101 // The strip's luma TU *is* the strip (`plane_bsize ==
19102 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
19103 // `txb_skip_ctx` at 0.
19104 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
19105 let set = if reduced_tx_set {
19106 TxbSet::LumaRect16x4
19107 } else {
19108 TxbSet::LumaRect16x4Set1
19109 };
19110 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
19111 let (levels, tx_type) = read_coeffs_rect(
19112 dec,
19113 &mut coding,
19114 scan,
19115 bw,
19116 bh,
19117 0,
19118 dc_sign_ctx(around.2),
19119 TxType::DctDct,
19120 0,
19121 )?;
19122 let residual = dequant_and_inverse_typed_wh(
19123 &levels,
19124 bw,
19125 bh,
19126 crate::decode::bit_depth(fctx),
19127 block_q_idx(fctx),
19128 plane_q_delta(0, fctx).0,
19129 plane_q_delta(0, fctx).1,
19130 tx_type,
19131 block_iqmatrix(fctx, 0, bw, bh, tx_type),
19132 );
19133 if let Some(b) = &palette_y_buf {
19134 set_palette_pred(b.clone(), fctx);
19135 }
19136 push_intra_rect(
19137 0,
19138 px,
19139 py,
19140 bw,
19141 bh,
19142 mode,
19143 angle_delta_y,
19144 reach,
19145 &residual,
19146 None,
19147 filter_intra,
19148 smooth_neighbor,
19149 fctx,
19150 );
19151 hit!(RECT4_16_COEFF_HITS);
19152 levels
19153 };
19154 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
19155 }
19156 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
19157 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
19158 // `update_partition_context` writes `partition_context_lookup[
19159 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
19160 // the left (mirrored under VERT_4).
19161 for cell in 0..mi_w {
19162 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
19163 *slot = bw as u8;
19164 }
19165 }
19166 for cell in 0..mi_h {
19167 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
19168 *slot = bh as u8;
19169 }
19170 }
19171 if has_chroma {
19172 hit!(RECT4_16_CHROMA_HITS);
19173 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
19174 // own chroma reference and codes its own 16x4 / 4x16 chroma
19175 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
19176 // ss 0/0, so the neighbour reads below anchor at the strip.)
19177 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
19178 (lmi, bw, bh)
19179 } else if ss_y(fctx) == 0 && horz {
19180 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
19181 // 16x4 strip is its own chroma reference (`is_chroma_reference`
19182 // at ss(1,0): bh == 1 mi, so the row clause reduces to
19183 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
19184 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
19185 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
19186 // the pair merge below -- its own chroma block
19187 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
19188 // walk proved such leaves exist, and libaom codes the pair's
19189 // chroma from the closing strip; the chunk lives in the
19190 // `chroma422_pair16` arm below.)
19191 (lmi, bw, bh)
19192 } else if horz {
19193 ((lmi.0 - 1, lmi.1), 16, 8)
19194 } else {
19195 ((lmi.0, lmi.1 - 1), 8, 16)
19196 };
19197 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
19198 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
19199 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
19200 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
19201 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
19202 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
19203 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
19204 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
19205 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
19206 // `decode_token_recon_block` walks unit_width =
19207 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
19208 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
19209 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
19210 // walks per unit: `predict_and_reconstruct_intra_block` predicts
19211 // every unit regardless of `skip_txfm`.
19212 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
19213 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
19214 DC_PRED
19215 } else {
19216 uv_mode
19217 };
19218 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
19219 hit!(RECT4_16_CHROMA_DIR_HITS);
19220 }
19221 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
19222 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
19223 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
19224 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
19225 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
19226 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
19227 // the pair's top-left luma mi, never this leaf's odd row/column.
19228 // Reading `lmi` here named the leaf directly above (a non-chroma
19229 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
19230 // SMOOTH neighbour: filt_type 0 instead of 1 turned
19231 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
19232 // directional chroma strip, moving 4 samples by 1.
19233 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
19234 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
19235 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
19236 // counter's mirror of the snapping form, and the shipped read offsets
19237 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
19238 //
19239 // lane-av1leftwit: this mirror is NOT evidence about the left read's
19240 // `+ss_y` term, whatever a report once said. It reads the leaf's own
19241 // (odd) mi row, which no decode call site does -- every one of them
19242 // uses the snapping form, whose base row is even -- and its result
19243 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
19244 // and worth keeping (the pair's chroma-reference read against the
19245 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
19246 // so it stays; the decode path's own reach for the `+ss_y` term is
19247 // `uv_left_1mi_split_hits()`.
19248 if smooth_neighbor_uv
19249 != neighbours.smooth_uv_neighbour_unsnapped(
19250 lmi.0,
19251 lmi.1,
19252 r,
19253 c,
19254 ss_x(fctx),
19255 ss_y(fctx),
19256 false,
19257 )
19258 {
19259 hit!(RECT4_16_UV_PAIR_FILT_HITS);
19260 }
19261 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
19262 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
19263 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
19264 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
19265 // the rect here consumed one symbol block too few and desynced
19266 // the next strip's `skip` (measured: lossless sb128 320x240,
19267 // mi(1,20) uv_mode matched, the following skip did not).
19268 let lossless_pair = lossless(fctx);
19269 let (u_levels, v_levels) = if lossless_pair {
19270 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
19271 if skip {
19272 for plane in 1..3usize {
19273 for rr in 0..ch / 4 {
19274 for cc in 0..cw / 4 {
19275 let (ox, oy) = (cc * 4, rr * 4);
19276 // The unit's origin and extent in LUMA pixels: `<< ss`
19277 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
19278 // at 4:4:4 -- the same form as the block-walk sibling
19279 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
19280 // only right at ss (1,1): at 4:4:4 it claims a 4x4
19281 // chroma unit is 8x8 luma, so `of_tu`'s
19282 // `col_off + tx_w < bw` test answers against a
19283 // footprint twice the real one and every unit past
19284 // the block's midpoint wrongly reports
19285 // `above_right = false` -- a directional chroma
19286 // strip then predicts from a neighbour libaom
19287 // never reads (measured: key frame 0, 4:4:4 lossless
19288 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
19289 // entropy bit-identical over 351109 EC_SYMR reads).
19290 // lane-av1422llpred r2: this site had the OTHER half
19291 // of the same shape -- `tu_reach` takes ONE size for
19292 // both axes, so a subsampled chroma unit's height
19293 // came from `<< ss_x` instead of `<< ss_y` (a TX_4x4
19294 // chroma unit is `4 << ss_x` luma px wide but
19295 // `4 << ss_y` tall). Identical at 4:2:0/4:4:4.
19296 let cu_reach = tu_reach_rect(
19297 pw,
19298 ph,
19299 ox << ss_x(fctx),
19300 oy << ss_y(fctx),
19301 4 << ss_x(fctx),
19302 4 << ss_y(fctx),
19303 pair_reach,
19304 ppx,
19305 ppy,
19306 y.width,
19307 y.height,
19308 fctx,
19309 );
19310 if let Some((ub, vb)) = &palette_uv_bufs {
19311 let buf = if plane == 1 { ub } else { vb };
19312 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
19313 }
19314 push_intra(
19315 plane,
19316 cpx + ox,
19317 cpy + oy,
19318 4,
19319 uv_predict_mode,
19320 angle_delta_uv,
19321 cu_reach,
19322 &ZERO_RESIDUAL[..16],
19323 None,
19324 None,
19325 smooth_neighbor_uv,
19326 fctx,
19327 );
19328 let cu_mi = (
19329 pair_mi.0 + (oy << ss_y(fctx)) / MI,
19330 pair_mi.1 + (ox << ss_x(fctx)) / MI,
19331 );
19332 neighbours.record_mi_chroma(
19333 cu_mi,
19334 4 << ss_x(fctx),
19335 4 << ss_y(fctx),
19336 plane,
19337 &ZERO_RESIDUAL[..16],
19338 );
19339 }
19340 }
19341 }
19342 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
19343 } else {
19344 let scan4 = default_scan(4);
19345 // `get_txb_ctx`: offset 10 (our tables store it at +3)
19346 // when the plane block is larger than the transform.
19347 let offset = Some(3usize);
19348 let mut uo = vec![0i32; cw * ch];
19349 let mut vo = vec![0i32; cw * ch];
19350 for plane in 1..3usize {
19351 for rr in 0..ch / 4 {
19352 for cc in 0..cw / 4 {
19353 let (ox, oy) = (cc * 4, rr * 4);
19354 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
19355 continue;
19356 }
19357 // The unit's stamp is its own span: aom
19358 // `av1_set_entropy_contexts` (blockd.c:29)
19359 // memsets exactly `tx_size_wide_unit` x
19360 // `tx_size_high_unit` cells at the unit's own
19361 // `(aoff, loff)` -- for TX_4X4 ONE above cell
19362 // and ONE left cell. `(oy / 2, ox / 2)` +
19363 // `(8, 8)` is the 4:2:0 subsampled form (one
19364 // chroma cell = 8 luma px = 2 mi cells); at
19365 // 4:4:4 a unit is ONE mi cell, and the 2x2
19366 // smear let a 4-wide strip's later units
19367 // overwrite the NEXT COLUMN's above cell with
19368 // their own state -- a column aom never sees
19369 // this block write -- so the following block's
19370 // `all_zero` read the wrong `txb_skip` row
19371 // (frame-0 read #452, the llkf named gap).
19372 let cu_mi = (
19373 pair_mi.0 + (oy << ss_y(fctx)) / MI,
19374 pair_mi.1 + (ox << ss_x(fctx)) / MI,
19375 );
19376 // One luma-mi cell: the chroma entropy arrays
19377 // are subsampled, and our bands replicate that
19378 // one entry over the unit's two cells
19379 // (`read_intra_chroma_lossless`).
19380 let cu_around = neighbours.around_mi(cu_mi, MI);
19381 // Same ss-aware luma footprint as the skip arm
19382 // above -- `ox * 2 / 8` is the 4:2:0-only form and
19383 // mis-answers `of_tu` at 4:4:4 (see there).
19384 // lane-av1422llpred r2: and the SKIP arm's fix
19385 // missed the other half of the same shape -- one
19386 // size for both axes makes the height come from
19387 // `<< ss_x`, so only 4:2:2 can reach it.
19388 let cu_reach = tu_reach_rect(
19389 pw,
19390 ph,
19391 ox << ss_x(fctx),
19392 oy << ss_y(fctx),
19393 4 << ss_x(fctx),
19394 4 << ss_y(fctx),
19395 pair_reach,
19396 ppx,
19397 ppy,
19398 y.width,
19399 y.height,
19400 fctx,
19401 );
19402 if let Some((ub, vb)) = &palette_uv_bufs {
19403 let buf = if plane == 1 { ub } else { vb };
19404 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
19405 }
19406 let buf: &mut PlaneBuf<'static> =
19407 if plane == 1 { &mut *u } else { &mut *v };
19408 let cu_grid = read_plane(
19409 dec,
19410 cdfs,
19411 TxbSet::Chroma4,
19412 &scan4,
19413 plane,
19414 cu_around[plane],
19415 mode,
19416 uv_predict_mode,
19417 angle_delta_uv,
19418 cu_reach,
19419 buf,
19420 cpx + ox,
19421 cpy + oy,
19422 4,
19423 4,
19424 base_q_idx,
19425 None,
19426 None,
19427 offset,
19428 smooth_neighbor_uv,
19429 fctx,
19430 )?;
19431 neighbours.record_mi_chroma(
19432 cu_mi,
19433 4 << ss_x(fctx),
19434 4 << ss_y(fctx),
19435 plane,
19436 &cu_grid,
19437 );
19438 hit!(CHROMA_SPLIT_TX_HITS);
19439 let dst = if plane == 1 { &mut uo } else { &mut vo };
19440 for row in 0..4 {
19441 let start = (oy + row) * cw + ox;
19442 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
19443 }
19444 }
19445 }
19446 }
19447 (Grid::Own(uo), Grid::Own(vo))
19448 }
19449 } else if skip {
19450 let zeros = Grid::Zero(cw * ch);
19451 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
19452 // ~1000) predicts EVERY plane and only guards the residual on
19453 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
19454 // DC + alpha * luma-AC. Dropping the CfL term here left a
19455 // chroma-only bounded box on ReelC's key frames.
19456 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19457 if alpha.is_some() {
19458 hit!(CHROMA_SKIP_CFL_HITS);
19459 }
19460 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
19461 if chroma422_pair16 {
19462 // lane-av1-422o: two TX_4X8 units, each predicted on
19463 // its own edges (the lower one off the upper one's
19464 // samples); no coefficients are coded, and libaom's
19465 // `set_entropy_context` zeroed the block's own cells,
19466 // so the pair-wide zero stamp below stays correct.
19467 for unit_row in 0..2usize {
19468 let unit_reach = tu_reach_rect(
19469 pw,
19470 ph,
19471 0,
19472 unit_row * 8,
19473 8,
19474 8,
19475 pair_reach,
19476 ppx,
19477 ppy,
19478 y.width,
19479 y.height,
19480 fctx,
19481 );
19482 if let Some((ub, vb)) = &palette_uv_bufs {
19483 let pbuf = if plane == 1 { ub } else { vb };
19484 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
19485 }
19486 push_intra_rect(
19487 plane,
19488 cpx,
19489 cpy + unit_row * 8,
19490 4,
19491 8,
19492 uv_predict_mode,
19493 angle_delta_uv,
19494 unit_reach,
19495 &ZERO_RESIDUAL[..4 * 8],
19496 alpha
19497 .zip(ac)
19498 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19499 None,
19500 smooth_neighbor_uv,
19501 fctx,
19502 );
19503 }
19504 } else {
19505 if let Some((ub, vb)) = &palette_uv_bufs {
19506 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
19507 }
19508 push_intra_rect(
19509 plane,
19510 cpx,
19511 cpy,
19512 cw,
19513 ch,
19514 uv_predict_mode,
19515 angle_delta_uv,
19516 pair_reach,
19517 &zeros,
19518 alpha
19519 .zip(ac)
19520 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19521 None,
19522 smooth_neighbor_uv,
19523 fctx,
19524 );
19525 }
19526 }
19527 (zeros.clone(), zeros)
19528 } else if chroma422_pair16 {
19529 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
19530 // per plane, plane-major (every U unit, then every V). Each
19531 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
19532 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
19533 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
19534 // offset comes from `num_pels_log2_lookup[plane_bsize] >
19535 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
19536 // BLOCK_INVALID (255), and the byte at that table's +255 in
19537 // the pinned Release oracle is 255 (`cmpb` against the
19538 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
19539 // arm: +3 on the offset-7-first chroma tables. No tx_type
19540 // symbol (only y plane's is transmitted); the unit's type is
19541 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
19542 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
19543 // are computed ONCE per block (`are_parameters_computed`)
19544 // over the pair's luma, shared by both units. Each unit is
19545 // predicted and recorded immediately, so the lower unit
19546 // reads the upper one's coefficient context.
19547 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19548 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
19549 for unit_row in 0..2usize {
19550 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
19551 let unit_reach = tu_reach_rect(
19552 pw,
19553 ph,
19554 0,
19555 unit_row * 8,
19556 8,
19557 8,
19558 pair_reach,
19559 ppx,
19560 ppy,
19561 y.width,
19562 y.height,
19563 fctx,
19564 );
19565 if let Some((ub, vb)) = &palette_uv_bufs {
19566 let pbuf = if plane == 1 { ub } else { vb };
19567 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
19568 }
19569 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
19570 let unit_grid = read_rect_chroma_unit(
19571 dec,
19572 cdfs,
19573 TxbSet::ChromaRect8x4,
19574 &SCAN_4X8,
19575 4,
19576 8,
19577 plane,
19578 chroma_around[plane],
19579 uv_predict_mode,
19580 angle_delta_uv,
19581 unit_reach,
19582 buf,
19583 cpx,
19584 cpy + unit_row * 8,
19585 base_q_idx,
19586 // lane-av1-422q: the offset-10 rows -- the same
19587 // measured rule as the 4x32 arm (plane_bsize
19588 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
19589 // num_pels_log2_lookup[255] = 0xff at the
19590 // 0xc0de70 copy -> +3 on the offset-7-first
19591 // chroma tables; see lanes/av1422q.report.md).
19592 Some(3),
19593 alpha
19594 .zip(ac)
19595 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19596 smooth_neighbor_uv,
19597 fctx,
19598 )?;
19599 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
19600 }
19601 }
19602 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
19603 } else {
19604 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
19605 // every second luma-mi cell
19606 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
19607 // chroma 4-px column spans two luma mi columns, and the
19608 // plain per-mi gather counts each column's whole-unit dc
19609 // sign twice). The left extent is unsubsampled at ss_y 0,
19610 // so its per-mi cells already line up one-to-one.
19611 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
19612 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
19613 } else {
19614 neighbours.around_mi_rect(pair_mi, pw, ph)
19615 };
19616 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
19617 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
19618 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
19619 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
19620 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
19621 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
19622 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
19623 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
19624 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
19625 // (4,16) never reaches this row; `chroma422_pair16`
19626 // intercepts it above and chunks it into TX_4X8 units.)
19627 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
19628 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
19629 // pair's height: an 8x8 SQUARE chroma block, the same
19630 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
19631 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
19632 // row is unreachable there. It is also the witness arm:
19633 // a restored `/2 chroma height` lands on (8,4) and the
19634 // counter reads 0.
19635 (8, 8) => {
19636 hit!(CHROMA422_SQUARE_HITS);
19637 (TxbSet::Chroma8, default_scan(8))
19638 }
19639 // lane-av1-422o: with the `chroma422_pair16` arm above,
19640 // the (2,16) own-strip shape and the 4:4:4 shapes are the
19641 // only residents; anything else is a named-lane gap.
19642 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
19643 };
19644 let mut planes = Vec::with_capacity(2);
19645 for plane in 1..3 {
19646 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
19647 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
19648 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19649 let (levels, tx_type) = read_chroma_coeffs_rect(
19650 dec,
19651 &mut coding,
19652 chroma_scan,
19653 cw,
19654 ch,
19655 skip_ctx,
19656 dc_sign_ctx(around[plane].2),
19657 default_tx,
19658 fctx,
19659 plane,
19660 )?;
19661 planes.push((levels, tx_type));
19662 }
19663 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
19664 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
19665 // CfL averages the luma of the WHOLE pair, the region this one
19666 // chroma transform covers.
19667 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19668 for (plane, _buf, levels, tx_type) in [
19669 (1usize, &mut *u, &u_levels, u_tx_type),
19670 (2, &mut *v, &v_levels, v_tx_type),
19671 ] {
19672 let residual = dequant_and_inverse_typed_wh(
19673 levels,
19674 cw,
19675 ch,
19676 crate::decode::bit_depth(fctx),
19677 block_q_idx(fctx),
19678 plane_q_delta(plane, fctx).0,
19679 plane_q_delta(plane, fctx).1,
19680 tx_type,
19681 block_iqmatrix(fctx, plane, cw, ch, tx_type),
19682 );
19683 if let Some((ub, vb)) = &palette_uv_bufs {
19684 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
19685 }
19686 push_intra_rect(
19687 plane,
19688 cpx,
19689 cpy,
19690 cw,
19691 ch,
19692 uv_predict_mode,
19693 angle_delta_uv,
19694 pair_reach,
19695 &residual,
19696 alpha
19697 .zip(ac)
19698 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19699 None,
19700 smooth_neighbor_uv,
19701 fctx,
19702 );
19703 }
19704 (u_levels, v_levels)
19705 };
19706 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
19707 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
19708 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
19709 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
19710 // the arm above (libaom's coefficient contexts are per
19711 // 4x4-cell); a pair-wide state would erase the unit boundary the
19712 // next block reads.
19713 if !lossless_pair && !chroma422_pair16 {
19714 // The chroma planes' coefficient context, over the PAIR's mi span
19715 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
19716 // the luma one rounded up to its 4x4 unit).
19717 let u_state = neighbour_state(&u_levels);
19718 let v_state = neighbour_state(&v_levels);
19719 let round_up_even = |n: usize| n.div_ceil(2) * 2;
19720 let bound_h = round_up_even(neighbours.mi_rows);
19721 let bound_w = round_up_even(neighbours.mi_cols);
19722 for cell in 0..(ph / MI) {
19723 if pair_mi.0 + cell < bound_h
19724 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
19725 {
19726 slot[1] = u_state;
19727 slot[2] = v_state;
19728 }
19729 }
19730 for cell in 0..(pw / MI) {
19731 if pair_mi.1 + cell < bound_w
19732 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
19733 {
19734 slot[1] = u_state;
19735 slot[2] = v_state;
19736 }
19737 }
19738 }
19739 last_uv_mode = Some(uv_predict_mode);
19740 }
19741 if horz {
19742 hit!(RECT4_16_HORZ_HITS);
19743 } else {
19744 hit!(RECT4_16_VERT_HITS);
19745 }
19746 let (pal_y_size, pal_y_colors) = palette_y
19747 .as_ref()
19748 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19749 let (pal_uv_size, pal_uv_colors) = palette_uv
19750 .as_ref()
19751 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19752 record_strip_palette(
19753 neighbours,
19754 lmi,
19755 bw,
19756 bh,
19757 pal_y_size,
19758 pal_y_colors,
19759 pal_uv_size,
19760 pal_uv_colors,
19761 );
19762 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19763 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19764 // frame): the above row records `tx_size_wide` over the block's width and
19765 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19766 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19767 // and it published neither band -- so the block after a 64x16 strip read
19768 // the row's init value 64 as its left transform height and took
19769 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19770 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19771 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19772 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
19773 Ok((mode, last_uv_mode, (tx_w, tx_h)))
19774}
19775
19776/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
19777/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
19778/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
19779/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
19780/// cap, so LUMA needs the same corner truncation [`decode_block`] already
19781/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
19782/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
19783/// this function's own charter/report), so both strips read a real 32x32
19784/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
19785/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
19786/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
19787/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
19788/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
19789/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
19790/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
19791/// that function, only the single-transform-unit (`tx_depth == 0`) case is
19792/// supported: a split transform refuses by name rather than guess-decode.
19793#[allow(clippy::too_many_arguments)]
19794fn decode_block_rect64(
19795 dec: &mut SymbolDecoder,
19796 cdfs: &mut Cdfs,
19797 neighbours: &mut Neighbours,
19798 at: (usize, usize),
19799 bw: usize,
19800 bh: usize,
19801 y: &mut PlaneBuf<'static>,
19802 u: &mut PlaneBuf<'static>,
19803 v: &mut PlaneBuf<'static>,
19804 enable_filter_intra: bool,
19805 allow_screen_content_tools: bool,
19806 base_q_idx: u8,
19807 tx_select: bool,
19808 reduced_tx_set: bool,
19809 fctx: &crate::decode::FrameCtx,
19810) -> Result<()> {
19811 let (r, c) = at;
19812 let (px, py) = (c * SUB, r * SUB);
19813 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
19814 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
19815 let palette_uv_cache = neighbours.palette_uv_cache(at);
19816 let (
19817 skip,
19818 mode,
19819 angle_delta_y,
19820 uv_mode,
19821 angle_delta_uv,
19822 alpha,
19823 filter_intra,
19824 palette_y,
19825 palette_uv,
19826 intrabc,
19827 ) = read_intra_mode_rect(
19828 dec,
19829 cdfs,
19830 nb_above_mode,
19831 nb_left_mode,
19832 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
19833 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
19834 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
19835 // correct), CFL must never be offered here -- passing `true`
19836 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
19837 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
19838 // from this block's very first symbol (lane-sbpart r3 bisect).
19839 false,
19840 true,
19841 bw,
19842 bh,
19843 enable_filter_intra,
19844 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
19845 allow_screen_content_tools,
19846 Some((palette_ctx, &palette_cache)),
19847 &palette_uv_cache,
19848 r * (SUB / MI),
19849 c * (SUB / MI),
19850 fctx,
19851 )?;
19852 if let Some((dv_row, dv_col)) = intrabc {
19853 return decode_intrabc_owned_rect(
19854 dec,
19855 cdfs,
19856 neighbours,
19857 (r * (SUB / MI), c * (SUB / MI)),
19858 (bw, bh),
19859 skip,
19860 (dv_row, dv_col),
19861 y,
19862 u,
19863 v,
19864 base_q_idx,
19865 tx_select,
19866 reduced_tx_set,
19867 fctx,
19868 );
19869 }
19870 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
19871 // lane-t900 r34: a non-skip palette block on a superblock-level strip
19872 // -- counted so its gate cannot go vacuous (this was a refusal until
19873 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
19874 // decodes_pixel_exact`).
19875 hit!(PALETTE_SB_STRIP_HITS);
19876 }
19877 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
19878 if smooth_neighbor {
19879 hit!(SMOOTH_LUMA_HITS);
19880 }
19881 let smooth_neighbor_uv =
19882 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
19883 if filter_intra.is_some() {
19884 // `filter_intra_size_class_rect` already returns `None` for both
19885 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
19886 // 32 on both axes), so this symbol is never read at this level --
19887 // kept only as the same defensive refusal [`decode_block_rect`] has.
19888 return Err(unsupported(
19889 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
19890 av1_filter_intra_allowed_bsize caps at 32x32)",
19891 ));
19892 }
19893 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
19894 DC_PRED
19895 } else {
19896 uv_mode
19897 };
19898 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
19899 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
19900 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
19901 // no depth symbol here either (class sweep of the sub8 leaf's fix).
19902 let depth = if tx_select && !lossless(fctx) {
19903 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
19904 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
19905 // intra-only frame publishes them from every block too
19906 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
19907 // 1920x792 128-superblock stream,
19908 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
19909 // `tx_size_cat2` row 1 where libaom reads row 2.
19910 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
19911 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
19912 // counts `sub_tx_size_map` steps from the block's own max rect
19913 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
19914 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
19915 // steps, so this level's category is 3 (the same one a 64x64 square
19916 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
19917 // here was a wrong-table read of a real symbol.
19918 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
19919 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19920 eprintln!(
19921 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
19922 dec.debug_state().0
19923 );
19924 }
19925 d
19926 } else {
19927 0
19928 };
19929 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
19930 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
19931 publish_txfm_bands_if_in_inter(
19932 neighbours,
19933 (mi_r, mi_c),
19934 depth_to_tx_wh(bw, bh, depth, fctx),
19935 (bw, bh),
19936 fctx,
19937 );
19938 if depth != 0 || lossless(fctx) {
19939 hit!(TX_DEPTH_HITS);
19940 // lane-rectsplit r1/r4: the superblock-level strip splits its
19941 // transform through the very same per-unit path as its 32x32-level
19942 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
19943 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
19944 // measured the old square formula mis-tiling exactly that strip).
19945 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
19946 if bw.max(bh) / bw.min(bh) == 4 {
19947 let which = if depth == 1 {
19948 &RECT4_SPLIT_DEPTH1_HITS
19949 } else {
19950 &RECT4_SPLIT_DEPTH2_HITS
19951 };
19952 hit_do! { which.with(|c| c.set(c.get() + 1)); }
19953 }
19954 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19955 eprintln!(
19956 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
19957 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
19958 angle_y={angle_delta_y}"
19959 );
19960 }
19961 let modes = RectStripModes {
19962 skip,
19963 mode,
19964 angle_delta_y,
19965 uv_predict_mode,
19966 angle_delta_uv,
19967 alpha,
19968 filter_intra,
19969 smooth_neighbor,
19970 smooth_neighbor_uv,
19971 palette_y: palette_y
19972 .as_ref()
19973 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
19974 palette_uv: palette_uv.as_ref().map(|p| {
19975 (
19976 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
19977 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
19978 )
19979 }),
19980 };
19981 if palette_y.is_some() || palette_uv.is_some() {
19982 hit!(PALETTE_SPLIT_TX_HITS);
19983 }
19984 decode_rect_split(
19985 dec,
19986 cdfs,
19987 neighbours,
19988 (mi_r, mi_c),
19989 bw,
19990 bh,
19991 tx_w,
19992 tx_h,
19993 &modes,
19994 y,
19995 u,
19996 v,
19997 base_q_idx,
19998 reduced_tx_set,
19999 fctx,
20000 )?;
20001 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
20002 // (lane-palette2 r10): this return skips the fn's own tail, so a
20003 // split-tx superblock strip would otherwise leave the above/left
20004 // palette arrays holding a dead block's colours.
20005 let (py_size, py_colors) = palette_y
20006 .as_ref()
20007 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
20008 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
20009 let (puv_size, puv_colors) = palette_uv
20010 .as_ref()
20011 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
20012 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
20013 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
20014 // return skips the fn's own tail, so a SPLIT superblock-level strip
20015 // published no TXFM_CONTEXT band and the next block read the row's init
20016 // value 64 as its left transform height. Measured on the 10-bit
20017 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
20018 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
20019 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
20020 // bands carry the SPLIT unit's size, not the block's.
20021 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
20022 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
20023 hit!(RECT_PARTITION_HITS);
20024 return Ok(());
20025 }
20026 let (tx_w, tx_h) = (bw, bh);
20027 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
20028 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
20029 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
20030 if let Some(ref pyv) = palette_y {
20031 let buf: Vec<u16> = pyv
20032 .map
20033 .iter()
20034 .map(|&idx| pyv.colors[idx as usize])
20035 .collect();
20036 set_palette_pred(buf, fctx);
20037 }
20038 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
20039 (
20040 puv.map
20041 .iter()
20042 .map(|&idx| puv.u_colors[idx as usize])
20043 .collect(),
20044 puv.map
20045 .iter()
20046 .map(|&idx| puv.v_colors[idx as usize])
20047 .collect(),
20048 )
20049 });
20050 if skip {
20051 push_intra_rect(
20052 0,
20053 px,
20054 py,
20055 bw,
20056 bh,
20057 mode,
20058 angle_delta_y,
20059 reach,
20060 &ZERO_RESIDUAL[..bw * bh],
20061 None,
20062 filter_intra,
20063 smooth_neighbor,
20064 fctx,
20065 );
20066 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
20067 if let Some((ub, _)) = &palette_uv_bufs {
20068 set_palette_pred(ub.clone(), fctx);
20069 }
20070 push_intra_rect(
20071 1,
20072 cpx,
20073 cpy,
20074 chroma_w,
20075 chroma_h,
20076 uv_predict_mode,
20077 angle_delta_uv,
20078 reach,
20079 &ZERO_RESIDUAL[..chroma_w * chroma_h],
20080 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
20081 None,
20082 smooth_neighbor_uv,
20083 fctx,
20084 );
20085 if let Some((_, vb)) = &palette_uv_bufs {
20086 set_palette_pred(vb.clone(), fctx);
20087 }
20088 push_intra_rect(
20089 2,
20090 cpx,
20091 cpy,
20092 chroma_w,
20093 chroma_h,
20094 uv_predict_mode,
20095 angle_delta_uv,
20096 reach,
20097 &ZERO_RESIDUAL[..chroma_w * chroma_h],
20098 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
20099 None,
20100 smooth_neighbor_uv,
20101 fctx,
20102 );
20103 neighbours.record_rect(
20104 at,
20105 bw,
20106 bh,
20107 mode,
20108 uv_predict_mode,
20109 &[
20110 &ZERO_RESIDUAL[..bw * bh],
20111 &ZERO_RESIDUAL[..chroma_w * chroma_h],
20112 &ZERO_RESIDUAL[..chroma_w * chroma_h],
20113 ],
20114 );
20115 } else {
20116 let around = neighbours.around_rect(at, bw, bh);
20117 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
20118 // (see this function's own doc comment). A 64-length axis codes only
20119 // its low 32 coefficients, so the corner is `min(bw, 32)` x
20120 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
20121 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
20122 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
20123 let scan32 = default_scan(TX32);
20124 if coeff_trace_on() {
20125 let (rng, _) = dec.debug_state();
20126 eprintln!(
20127 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
20128 );
20129 }
20130 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
20131 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
20132 read_coeffs(
20133 dec,
20134 &mut luma_coding,
20135 &scan32,
20136 0,
20137 dc_sign_ctx(around[0].2),
20138 TxType::DctDct,
20139 Some((bw, bh)),
20140 )?
20141 } else {
20142 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
20143 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
20144 // (`scan.c`) gives both the very same `default_scan_32x16` /
20145 // `default_scan_16x32` the 2:1 sizes use ("Half of the
20146 // coefficients of tx64 at higher frequencies are set to zeros. So
20147 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
20148 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
20149 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
20150 // 512-position eob group) -- BOTH identical to TX_32X16, so the
20151 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
20152 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
20153 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
20154 // what `base_ctx_rect` computes at (32, 16).
20155 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
20156 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
20157 read_coeffs_rect(
20158 dec,
20159 &mut luma_coding,
20160 luma_scan,
20161 luma_cw,
20162 luma_ch,
20163 0,
20164 dc_sign_ctx(around[0].2),
20165 TxType::DctDct,
20166 0,
20167 )?
20168 };
20169 if coeff_trace_on() {
20170 let (rng, _) = dec.debug_state();
20171 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
20172 }
20173 let mut luma_levels = vec![0i32; bw * bh];
20174 for row in 0..luma_ch {
20175 luma_levels[row * bw..][..luma_cw]
20176 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
20177 }
20178 {
20179 let cur = block_q_idx(fctx);
20180 if cur != i32::from(base_q_idx) {
20181 hit!(RECT64_QIDX_DRIFT_HITS);
20182 }
20183 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20184 eprintln!(
20185 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
20186 );
20187 }
20188 }
20189 let luma_residual = dequant_and_inverse_typed_wh(
20190 &luma_levels,
20191 bw,
20192 bh,
20193 crate::decode::bit_depth(fctx),
20194 block_q_idx(fctx),
20195 plane_q_delta(0, fctx).0,
20196 plane_q_delta(0, fctx).1,
20197 luma_tx_type,
20198 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
20199 );
20200 push_intra_rect(
20201 0,
20202 px,
20203 py,
20204 bw,
20205 bh,
20206 mode,
20207 angle_delta_y,
20208 reach,
20209 &luma_residual,
20210 None,
20211 filter_intra,
20212 smooth_neighbor,
20213 fctx,
20214 );
20215 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
20216 let leftcol: Vec<u16> = if px > 0 {
20217 (py..py + bh)
20218 .map(|row| y.data[row * y.width + px - 1])
20219 .collect()
20220 } else {
20221 vec![]
20222 };
20223 eprintln!(
20224 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
20225 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
20226 luma_corner.iter().any(|&v| v != 0),
20227 &y.data[py * y.width + px..][..bw],
20228 leftcol,
20229 );
20230 }
20231 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
20232 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
20233 // is larger than that, so it is tiled into 32-capped units.
20234 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
20235 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
20236 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
20237 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
20238 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
20239 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
20240 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
20241 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
20242 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
20243 _ => {
20244 return Err(unsupported(
20245 "a 64-axis strip whose chroma unit has no coefficient table",
20246 ));
20247 }
20248 };
20249 let bigger = nw * nh > 1;
20250 // lane-av1444palw: the reach census for the horizontal arm of this
20251 // walk. `EC_PALWALK=1` prints, per rect64 block, the plane-block
20252 // geometry, the unit grid it was tiled into, and whether a chroma
20253 // palette was present -- so a fixture search can tell `nw >= 2` (the
20254 // arm nothing had reached) from `nh >= 2` (the arm the corpus census
20255 // already covered), and can see WHY a candidate block did not fire.
20256 // Diagnostic only; no decode behaviour depends on it.
20257 if crate::envflags::env_flag!("EC_PALWALK") {
20258 eprintln!(
20259 "EC_PALWALK mi={r},{c} px={px} py={py} bw={bw} bh={bh} cw={chroma_w} \
20260 ch={chroma_h} uw={uw} uh={uh} nw={nw} nh={nh} ast={allow_screen_content_tools} \
20261 puv={} py_pal={}",
20262 palette_uv.is_some() as i32,
20263 palette_y.is_some() as i32
20264 );
20265 }
20266 let mut u_levels = vec![0i32; chroma_w * chroma_h];
20267 let mut v_levels = vec![0i32; chroma_w * chroma_h];
20268 // The tiled units below stamp their own coefficient context
20269 // immediately, then the whole-strip `record_rect` rewrite paints
20270 // every chroma cell with ONE whole-strip state and the per-unit DC
20271 // signs and levels are lost (class `override-slot-on-one-arm`, same
20272 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
20273 // here and replayed after that record, the c8 `mu_chroma_units` way.
20274 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
20275 for plane_idx in 1..=2 {
20276 for cu_row in 0..nh {
20277 for cu_col in 0..nw {
20278 let cu_around = if nw == 1 && nh == 1 {
20279 around
20280 } else {
20281 let lsx = uw << ss_x(fctx);
20282 let lsy = uh << ss_y(fctx);
20283 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
20284 // lane-av1422llintra: same ss (1, 0) above-column
20285 // double-count as 12735 -- one chroma column spans two
20286 // luma mi columns, libaom reads one. Identical number
20287 // at 4:2:0 and 4:4:4.
20288 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20289 neighbours.around_mi_422_chroma(cu_mi, lsx, lsy)
20290 } else {
20291 neighbours.around_mi_rect(cu_mi, lsx, lsy)
20292 }
20293 };
20294 let lsx = uw << ss_x(fctx);
20295 let lsy = uh << ss_y(fctx);
20296 let cfl = alpha.map(|(au, av)| {
20297 let a = if plane_idx == 1 { au } else { av };
20298 (
20299 a,
20300 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
20301 )
20302 });
20303 let levels = if uw == uh {
20304 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
20305 if let Some((ub, vb)) = &palette_uv_bufs {
20306 let pbuf = if plane_idx == 1 { ub } else { vb };
20307 set_palette_pred(
20308 palette_window(pbuf, chroma_w, cu_col * uw, cu_row * uh, uw, uh),
20309 fctx,
20310 );
20311 // Counted only when the window is a STRICT sub-slice of the
20312 // block's buffer, i.e. when the 32-cap actually tiled the
20313 // block: at nw * nh == 1 the window is a re-stride copy of
20314 // the whole buffer and windowing is load-bearing for
20315 // nothing. The `bigger` guard is what makes a hit PROOF
20316 // that the tiled arm ran, rather than proof that some
20317 // palette chroma block existed.
20318 if bigger {
20319 hit!(CHROMA_PALETTE_WINDOW_HITS);
20320 }
20321 }
20322 read_plane(
20323 dec,
20324 cdfs,
20325 chroma_set,
20326 chroma_scan,
20327 plane_idx,
20328 cu_around[plane_idx],
20329 mode,
20330 uv_predict_mode,
20331 angle_delta_uv,
20332 reach,
20333 plane,
20334 cpx + cu_col * uw,
20335 cpy + cu_row * uh,
20336 uw,
20337 uw,
20338 base_q_idx,
20339 cfl,
20340 None,
20341 bigger.then_some(3),
20342 smooth_neighbor_uv,
20343 fctx,
20344 )?
20345 } else {
20346 let skip_ctx = usize::from(cu_around[plane_idx].0)
20347 + usize::from(cu_around[plane_idx].1)
20348 + usize::from(bigger) * 3;
20349 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
20350 let (levels, tx_type) = read_chroma_coeffs_rect(
20351 dec,
20352 &mut coding,
20353 chroma_scan,
20354 uw,
20355 uh,
20356 skip_ctx,
20357 dc_sign_ctx(cu_around[plane_idx].2),
20358 TxType::DctDct,
20359 fctx,
20360 plane_idx,
20361 )?;
20362 let residual = dequant_and_inverse_typed_wh(
20363 &levels,
20364 uw,
20365 uh,
20366 crate::decode::bit_depth(fctx),
20367 block_q_idx(fctx),
20368 plane_q_delta(plane_idx, fctx).0,
20369 plane_q_delta(plane_idx, fctx).1,
20370 tx_type,
20371 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
20372 );
20373 if let Some((ub, vb)) = &palette_uv_bufs {
20374 let pbuf = if plane_idx == 1 { ub } else { vb };
20375 set_palette_pred(
20376 palette_window(pbuf, chroma_w, cu_col * uw, cu_row * uh, uw, uh),
20377 fctx,
20378 );
20379 // Counted only when the window is a STRICT sub-slice of the
20380 // block's buffer, i.e. when the 32-cap actually tiled the
20381 // block: at nw * nh == 1 the window is a re-stride copy of
20382 // the whole buffer and windowing is load-bearing for
20383 // nothing. The `bigger` guard is what makes a hit PROOF
20384 // that the tiled arm ran, rather than proof that some
20385 // palette chroma block existed.
20386 if bigger {
20387 hit!(CHROMA_PALETTE_WINDOW_HITS);
20388 }
20389 }
20390 push_intra_rect(
20391 plane_idx,
20392 cpx + cu_col * uw,
20393 cpy + cu_row * uh,
20394 uw,
20395 uh,
20396 uv_predict_mode,
20397 angle_delta_uv,
20398 reach,
20399 &residual,
20400 cfl,
20401 None,
20402 smooth_neighbor_uv,
20403 fctx,
20404 );
20405 levels
20406 };
20407 let dst = if plane_idx == 1 {
20408 &mut u_levels
20409 } else {
20410 &mut v_levels
20411 };
20412 for row in 0..uh {
20413 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
20414 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
20415 }
20416 if bigger {
20417 neighbours.record_mi_chroma(
20418 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
20419 lsx,
20420 lsy,
20421 plane_idx,
20422 &levels,
20423 );
20424 tiled_chroma_units.push((
20425 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
20426 plane_idx,
20427 levels.clone(),
20428 lsx,
20429 lsy,
20430 ));
20431 }
20432 }
20433 }
20434 }
20435 neighbours.record_rect(
20436 at,
20437 bw,
20438 bh,
20439 mode,
20440 uv_predict_mode,
20441 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
20442 );
20443 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
20444 // chroma cells from the assembled grids' one whole-strip state,
20445 // overwriting exactly the stamps the tiled loop just made.
20446 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
20447 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
20448 }
20449 hit!(RECT_COEFF_HITS);
20450 }
20451 let (py_size, py_colors) = palette_y
20452 .as_ref()
20453 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
20454 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
20455 let (puv_size, puv_colors) = palette_uv
20456 .as_ref()
20457 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
20458 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
20459 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
20460 neighbours.fill_lf_grid_rect(
20461 (mi_r, mi_c),
20462 bw / MI,
20463 bh / MI,
20464 tx_w as u8,
20465 tx_h as u8,
20466 0,
20467 fctx,
20468 );
20469 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
20470 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
20471 // frame): the above row records `tx_size_wide` over the block's width and
20472 // the left column `tx_size_high` over its height. This 1:4 strip reader is
20473 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
20474 // and it published neither band -- so the block after a 64x16 strip read
20475 // the row's init value 64 as its left transform height and took
20476 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
20477 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
20478 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
20479 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
20480 hit!(SB_RECT_HITS);
20481 match (bw, bh) {
20482 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
20483 (16, 64) => hit!(SB_RECT4_VERT_HITS),
20484 _ => {}
20485 }
20486 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20487 let (rng, _) = dec.debug_state();
20488 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
20489 }
20490 Ok(())
20491}
20492
20493/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
20494/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
20495/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
20496/// it lands away from zero, for gate tests to prove a real stream fired one.
20497fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
20498 let symbol = dec.symbol(cdf);
20499 if symbol != ANGLE_DELTA_ZERO {
20500 hit!(ANGLE_DELTA_HITS);
20501 }
20502 symbol as i32 - ANGLE_DELTA_ZERO as i32
20503}
20504
20505#[allow(clippy::too_many_arguments)]
20506fn read_intra_mode(
20507 dec: &mut SymbolDecoder,
20508 cdfs: &mut Cdfs,
20509 above_mode: usize,
20510 left_mode: usize,
20511 cfl: bool,
20512 side: usize,
20513 enable_filter_intra: bool,
20514 skip_ctx: usize,
20515 allow_screen_content_tools: bool,
20516 allow_intrabc: bool,
20517 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
20518 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
20519 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
20520 // `None` at the excluded call sites (the 8x8-leaf path), which still read
20521 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
20522 // decoder reads either way -- but refuse by name the moment it fires,
20523 // exactly the old behaviour.
20524 palette: Option<(usize, &[u16])>,
20525 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
20526 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
20527 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
20528 // `use_palette_y`, not a neighbour lookup).
20529 palette_uv_cache: &[u16],
20530 mi_r: usize,
20531 mi_c: usize,
20532 fctx: &crate::decode::FrameCtx,
20533) -> Result<(
20534 bool,
20535 usize,
20536 i32,
20537 usize,
20538 i32,
20539 Option<(i32, i32)>,
20540 Option<usize>,
20541 Option<PaletteY>,
20542 Option<PaletteUv>,
20543)> {
20544 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
20545 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
20546 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
20547 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
20548 // line against the instrumented aomdec, not just `tell()`.
20549 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
20550 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
20551 if ec_istep {
20552 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
20553 // (decodemv.c:818), printed at the same point: before the first
20554 // mode-info symbol of the block, so a cross-decoder range ladder can
20555 // be keyed on the BLOCK, not just on the symbol sequence.
20556 eprintln!(
20557 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
20558 dec.debug_state().0
20559 );
20560 }
20561 macro_rules! istep {
20562 ($name:literal, $val:expr) => {
20563 if ec_istep {
20564 let (rng, _) = dec.debug_state();
20565 eprintln!(
20566 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
20567 $name, $val
20568 );
20569 }
20570 };
20571 }
20572 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
20573 // point every square caller routes through (see `read_intra_mode_rect`).
20574 let cfl = if cfl && side > 32 {
20575 hit!(NOCFL_UV_MODE_HITS);
20576 false
20577 } else {
20578 cfl
20579 };
20580 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
20581 // `skip` when `SegIdPreSkip`, and after it otherwise.
20582 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
20583 if seg_id_pre_skip(fctx) {
20584 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
20585 }
20586 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
20587 if trace {
20588 eprintln!(
20589 "TRACE skip value={} rng={}",
20590 skip as i32,
20591 dec.debug_state().0
20592 );
20593 }
20594 istep!("skip", skip as i32);
20595 if !seg_id_pre_skip(fctx) {
20596 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
20597 }
20598 // spec order (see the comment below on `read_intrabc_info`): `skip`,
20599 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
20600 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
20601 istep!("cdef", 0);
20602 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
20603 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
20604 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
20605 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
20606 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
20607 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
20608 istep!("dq", 0);
20609 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
20610 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
20611 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
20612 // intra frame whose header set `allow_intrabc`. Actual intra block copy
20613 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
20614 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
20615 // draws the line at consuming this one flag symbol and refusing by name
20616 // when it fires, so the arithmetic decoder still resyncs for a stream
20617 // that merely allows (but never uses) intrabc.
20618 if allow_intrabc {
20619 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
20620 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
20621 eprintln!(
20622 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
20623 u8::from(use_intrabc),
20624 dec.debug_state().0
20625 );
20626 }
20627 if trace {
20628 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
20629 }
20630 if use_intrabc {
20631 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
20632 if trace {
20633 eprintln!("TRACE intrabc dv={dv:?}");
20634 }
20635 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
20636 hit!(INTRABC_HITS);
20637 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
20638 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
20639 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
20640 // `DC_PRED` (which is also what the neighbour mode contexts and
20641 // the loop filter then see).
20642 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
20643 }
20644 }
20645 let above_ctx = INTRA_MODE_CTX[above_mode];
20646 let left_ctx = INTRA_MODE_CTX[left_mode];
20647 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
20648 if trace {
20649 eprintln!(
20650 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
20651 dec.debug_state().0
20652 );
20653 }
20654 istep!("mode", mode as i32);
20655 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
20656 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
20657 if trace {
20658 eprintln!(
20659 "TRACE angle_delta value={}",
20660 delta + ANGLE_DELTA_ZERO as i32
20661 );
20662 }
20663 delta
20664 } else {
20665 0
20666 };
20667 istep!("angle_y", angle_delta_y);
20668 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
20669 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
20670 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
20671 // gates its chroma symbols on.
20672 let has_chroma = !mono(fctx);
20673 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
20674 let uv_mode = if !has_chroma {
20675 DC_PRED
20676 } else if cfl {
20677 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20678 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
20679 } else {
20680 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20681 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
20682 };
20683 if trace {
20684 eprintln!(
20685 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
20686 dec.debug_state().0
20687 );
20688 }
20689 istep!("uv_mode", uv_mode as i32);
20690 let alpha = if cfl && uv_mode == UV_CFL_PRED {
20691 Some(read_cfl_alphas(dec, cdfs))
20692 } else {
20693 None
20694 };
20695 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
20696 // from this lane's directional chroma: a corner block with neither
20697 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
20698 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
20699 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
20700 // bug in that fallback this lane's own scope does not cover. Keep it
20701 // refused here rather than ship a silently-wrong decode.
20702 if (9..=12).contains(&uv_mode) {
20703 hit!(SMOOTH_UV_HITS);
20704 }
20705 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
20706 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
20707 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
20708 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
20709 // the `else` branch below and never reads one either way.
20710 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
20711 hit!(DIRECTIONAL_UV_HITS);
20712 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
20713 } else {
20714 0
20715 };
20716 istep!("angle_uv", angle_delta_uv);
20717 if angle_delta_uv != 0 {
20718 hit!(UV_ANGLE_DELTA_HITS);
20719 }
20720 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
20721 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
20722 // gated by `av1_allow_palette` (blockd.h -- size bound only,
20723 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
20724 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
20725 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
20726 // read the same CDF row whenever every neighbour really is non-palette).
20727 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
20728 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
20729 // neighbour lookup at all), so it is exact even at the excluded call
20730 // sites once Y decodes real syntax there too.
20731 //
20732 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
20733 // inline from `read_palette_mode_info` -- it runs later, from
20734 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
20735 // after the WHOLE mode-info read for the block, including UV palette
20736 // mode_info (`read_palette_mode_info`'s own second half, right below)
20737 // and `read_filter_intra_mode_info`. So this branch now only reads
20738 // mode/size/colours for both planes (deferring the two colour-index-map
20739 // decodes to after `filter_intra`, below) -- r6's range trace pinned
20740 // this exact ordering bug (`compare-range-not-tell`: ranges matched
20741 // bit-for-bit through the Y colours, diverged only at the old inline
20742 // `decode_color_index_map` call).
20743 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
20744 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
20745 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
20746 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
20747 if mode == DC_PRED {
20748 if trace {
20749 let (rng, _) = dec.debug_state();
20750 eprintln!(
20751 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
20752 );
20753 }
20754 }
20755 let use_palette_y =
20756 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
20757 if mode == DC_PRED && trace {
20758 let (rng, _) = dec.debug_state();
20759 eprintln!(
20760 "TRACE palette_y_mode value={} rng={rng}",
20761 use_palette_y as i32
20762 );
20763 }
20764 if use_palette_y {
20765 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
20766 if trace {
20767 let (rng, _) = dec.debug_state();
20768 eprintln!("TRACE palette_y_size n={n} rng={rng}");
20769 }
20770 let colors = read_palette_colors_y(dec, n, cache, fctx);
20771 if trace {
20772 let (rng, _) = dec.debug_state();
20773 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
20774 }
20775 palette_y_pending = Some((n, colors));
20776 }
20777 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
20778 // unconditionally at this bit position whenever `uv_mode ==
20779 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
20780 // scope always reconstructs chroma alongside luma (`decode_block`
20781 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
20782 // is always true here and does not need threading in.
20783 //
20784 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
20785 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
20786 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
20787 // symbol even at this chroma-owning square block.
20788 let palette_uv_mode_ctx = usize::from(use_palette_y);
20789 if has_chroma
20790 && uv_mode == DC_PRED
20791 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
20792 {
20793 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
20794 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
20795 palette_uv_pending = Some((n, u_colors, v_colors));
20796 }
20797 }
20798 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
20799 // `use_filter_intra` symbol this decoder never read at all until
20800 // lane-av1real r10 -- silently skipping it left every bit past a
20801 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
20802 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
20803 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
20804 // symbol's bits were never consumed).
20805 let mut filter_intra = None;
20806 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
20807 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
20808 // `use_filter_intra` symbol for a Y-palette block, and reading one here
20809 // desynced every screen-content stream from the first palette block on
20810 // (it surfaced as a bogus "partition below 8x8" refusal further down the
20811 // tile).
20812 if mode == DC_PRED
20813 && enable_filter_intra
20814 && palette_y_pending.is_none()
20815 && let Some(class) = filter_intra_size_class(side)
20816 {
20817 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
20818 if trace {
20819 eprintln!(
20820 "TRACE use_filter_intra side={side} rng={} value={}",
20821 dec.debug_state().0,
20822 use_filter_intra as i32
20823 );
20824 }
20825 istep!("use_filter_intra", use_filter_intra as i32);
20826 if use_filter_intra {
20827 hit!(FILTER_INTRA_HITS);
20828 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
20829 if trace {
20830 eprintln!("TRACE filter_intra_mode value={fi_mode}");
20831 }
20832 istep!("filter_intra_mode", fi_mode as i32);
20833 filter_intra = Some(fi_mode);
20834 }
20835 }
20836 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
20837 // shared U/V map) -- the same order libaom's own loop visits them in.
20838 let palette_y = palette_y_pending.map(|(n, colors)| {
20839 let map = decode_color_index_map(
20840 dec,
20841 cdfs,
20842 n,
20843 side,
20844 palette_onscreen(mi_r, mi_c, side, side, fctx),
20845 false,
20846 );
20847 hit!(PALETTE_HITS);
20848 if trace {
20849 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
20850 }
20851 PaletteY {
20852 size: n,
20853 colors,
20854 map,
20855 }
20856 });
20857 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
20858 let on = palette_onscreen_uv(
20859 (side, side),
20860 palette_onscreen(mi_r, mi_c, side, side, fctx),
20861 (side >> ss_x(fctx), side >> ss_y(fctx)),
20862 (ss_x(fctx), ss_y(fctx)),
20863 );
20864 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
20865 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
20866 // square call's `(side >> ss_x)`-squared (4x4), which left a
20867 // 16-entry map for a 32-sample unit and panicked the reconstruct.
20868 let map = decode_color_index_map_wh(
20869 dec,
20870 cdfs,
20871 n,
20872 side >> ss_x(fctx),
20873 side >> ss_y(fctx),
20874 on,
20875 true,
20876 );
20877 hit!(PALETTE_UV_HITS);
20878 if trace {
20879 eprintln!(
20880 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
20881 &u_colors[..n],
20882 &v_colors[..n]
20883 );
20884 }
20885 PaletteUv {
20886 size: n,
20887 u_colors,
20888 v_colors,
20889 map,
20890 }
20891 });
20892 Ok((
20893 skip,
20894 mode,
20895 angle_delta_y,
20896 uv_mode,
20897 angle_delta_uv,
20898 alpha,
20899 filter_intra,
20900 palette_y,
20901 palette_uv,
20902 ))
20903}
20904
20905/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
20906/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
20907/// intra modes.
20908const UV_CFL_PRED: usize = 13;
20909
20910/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
20911/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
20912/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
20913/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
20914/// joint sign the same way. Returns each plane's final signed `alpha_q3`
20915/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
20916fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
20917 hit!(CFL_BLOCK_HITS);
20918 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
20919 let sign_u = ((joint_sign + 1) * 11) >> 5;
20920 let sign_v = (joint_sign + 1) - 3 * sign_u;
20921 let alpha_u = if sign_u == 0 {
20922 0
20923 } else {
20924 let ctx_u = (joint_sign + 1 - 3) as usize;
20925 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
20926 if sign_u == 2 { mag } else { -mag }
20927 };
20928 let alpha_v = if sign_v == 0 {
20929 0
20930 } else {
20931 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
20932 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
20933 if sign_v == 2 { mag } else { -mag }
20934 };
20935 (alpha_u, alpha_v)
20936}
20937
20938/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
20939/// the reconstructed luma samples under a `side`-square block, subsampled
20940/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
20941/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
20942/// to give the AC values [`cfl_scaled`] scales by alpha.
20943fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
20944 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
20945 i32::from(y.data[ly * y.width + lx])
20946 })
20947}
20948
20949/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
20950/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
20951/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
20952/// reconstruction through THIS function rather than a second transcription of
20953/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
20954/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
20955/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
20956fn cfl_ac_ss(
20957 y: &PlaneBuf<'_>,
20958 px: usize,
20959 py: usize,
20960 bw: usize,
20961 bh: usize,
20962 ss_x: usize,
20963 ss_y: usize,
20964) -> Vec<i32> {
20965 if ss_x == 0 && ss_y == 0 {
20966 hit!(CFL_AC_444_HITS);
20967 let mut ac = vec![0i32; bw * bh];
20968 let mut sum = 0i32;
20969 for row in 0..bh {
20970 for col in 0..bw {
20971 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
20972 ac[row * bw + col] = q3;
20973 sum += q3;
20974 }
20975 }
20976 let num_pel = (bw * bh) as i32;
20977 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20978 ac.iter_mut().for_each(|v| *v -= avg);
20979 ac
20980 } else if ss_x == 1 && ss_y == 0 {
20981 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
20982 // averages the HORIZONTAL luma pair above it, at full chroma height
20983 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
20984 // is square here, and the 4:2:0 rect/square helpers below would halve
20985 // the height it must keep.
20986 hit!(CFL_AC_422_HITS);
20987 let (cw, ch) = (bw >> 1, bh);
20988 let mut ac = vec![0i32; cw * ch];
20989 let mut sum = 0i32;
20990 for row in 0..ch {
20991 for col in 0..cw {
20992 let (lx, ly) = (px + col * 2, py + row);
20993 let q3 = (i32::from(y.data[ly * y.width + lx])
20994 + i32::from(y.data[ly * y.width + lx + 1]))
20995 << 2;
20996 ac[row * cw + col] = q3;
20997 sum += q3;
20998 }
20999 }
21000 let num_pel = (cw * ch) as i32;
21001 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
21002 ac.iter_mut().for_each(|v| *v -= avg);
21003 ac
21004 } else if bw == bh {
21005 hit!(CFL_AC_420_SQ_HITS);
21006 cfl_ac_q3(y, px, py, bw)
21007 } else {
21008 hit!(CFL_AC_420_RECT_HITS);
21009 cfl_ac_q3_rect(y, px, py, bw, bh)
21010 }
21011}
21012
21013pub(crate) fn cfl_ac_q3_at(
21014 px: usize,
21015 py: usize,
21016 bw: usize,
21017 bh: usize,
21018 sample: impl Fn(usize, usize) -> i32,
21019) -> Vec<i32> {
21020 hit!(CFL_AC_Q3_AT_HITS);
21021 if crate::envflags::env_flag!("EC_HALVSWEEP") {
21022 eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
21023 }
21024 let (cw, ch) = (bw / 2, bh / 2);
21025 let mut ac = vec![0i32; cw * ch];
21026 let mut sum = 0i32;
21027 for cy in 0..ch {
21028 for cx in 0..cw {
21029 let (lx, ly) = (px + cx * 2, py + cy * 2);
21030 let q3 =
21031 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
21032 << 1;
21033 ac[cy * cw + cx] = q3;
21034 sum += q3;
21035 }
21036 }
21037 let num_pel = (cw * ch) as i32;
21038 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
21039 ac.iter_mut().for_each(|v| *v -= avg);
21040 ac
21041}
21042
21043/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
21044/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
21045/// ties away from zero on the shifted-out sign).
21046pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
21047 let v = alpha_q3 * ac_q3;
21048 if v >= 0 {
21049 (v + 32) >> 6
21050 } else {
21051 -((-v + 32) >> 6)
21052 }
21053}
21054
21055/// One plane's reconstruction buffer, `width * height` samples, and the
21056/// prediction/residual reads and writes into it — the decode-side twin of
21057/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
21058/// (own-edge and reach clamps both), passing what it gathers straight to
21059/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
21060/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
21061/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
21062/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
21063/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
21064/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
21065/// lane-mc64 r1: the decode-order index the stage dumps below key their file
21066/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
21067/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
21068/// without this every frame overwrote `.f0` and a per-frame bisection silently
21069/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
21070#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21071fn stage_dump_idx() -> usize {
21072 PREFILT_PICTURE_IDX
21073 .load(std::sync::atomic::Ordering::SeqCst)
21074 .saturating_sub(1)
21075}
21076
21077fn dump_stage16(
21078 var: &str,
21079 y: &PlaneBuf<'_>,
21080 u: &PlaneBuf<'_>,
21081 v: &PlaneBuf<'_>,
21082 fw: usize,
21083 fh: usize,
21084) {
21085 use std::io::Write;
21086 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
21087 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
21088 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
21089 // not be read out at all.
21090 if let Ok(path) = crate::envflags::var(var)
21091 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
21092 {
21093 for (p, w, h) in [
21094 (y, fw, fh),
21095 (u, fw.div_ceil(2), fh.div_ceil(2)),
21096 (v, fw.div_ceil(2), fh.div_ceil(2)),
21097 ] {
21098 for row in 0..h {
21099 let mut bytes = Vec::with_capacity(w * 2);
21100 for &s in &p.data[row * p.width..][..w] {
21101 bytes.extend_from_slice(&s.to_le_bytes());
21102 }
21103 let _ = f.write_all(&bytes);
21104 }
21105 }
21106 }
21107}
21108
21109/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
21110/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
21111/// every frame overwrote the previous one and only the LAST frame survived,
21112/// which silently defeats any per-frame filter-stage bisection.
21113fn dump_stage_idx(var: &str) -> usize {
21114 use std::collections::HashMap;
21115 use std::sync::{Mutex, OnceLock};
21116 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
21117 let mut m = IDX
21118 .get_or_init(|| Mutex::new(HashMap::new()))
21119 .lock()
21120 .unwrap();
21121 let e = m.entry(var.to_string()).or_insert(0);
21122 let i = *e;
21123 *e += 1;
21124 i
21125}
21126
21127fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
21128 use std::io::Write;
21129 if let Ok(path) = crate::envflags::var(var)
21130 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
21131 {
21132 for p in [y, u, v] {
21133 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
21134 let _ = f.write_all(&narrow);
21135 }
21136 }
21137}
21138
21139/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
21140/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
21141/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
21142/// `uv_width`/`uv_height`), so the two can be diffed directly.
21143///
21144/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
21145/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
21146/// measurement traps, and the second one is why the first went unnoticed:
21147/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
21148/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
21149/// inter frame had no pre-filter rung to compare against and got attributed to
21150/// reconstruction when the oracle could not see it. The `static` also restarted
21151/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
21152/// per-frame bisection silently compared the LAST decoded frame. The counter
21153/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
21154/// the inter path (skipped when the filter pipeline is active, which has
21155/// already deblocked by the time the tile tail runs -- same condition
21156/// `capture_filter_replay` guards itself with).
21157fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
21158 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
21159 return;
21160 };
21161 use std::io::Write;
21162 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
21163 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
21164 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
21165 for row in 0..plane.true_height {
21166 out.extend(
21167 plane.data[row * plane.width..][..plane.true_width]
21168 .iter()
21169 .map(|&s| s as u8),
21170 );
21171 }
21172 out
21173 };
21174 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
21175 let _ = f.write_all(&crop(y));
21176 let _ = f.write_all(&crop(u));
21177 let _ = f.write_all(&crop(v));
21178 }
21179}
21180
21181/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
21182/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
21183/// at most 4095), so a decode that hashes identically under the flag proves
21184/// the output does not depend on the plane buffer's initial content.
21185const PLANE_SENTINEL: u16 = 0xDEAD;
21186
21187/// A frame plane's own backing store, `n` samples, UNINITIALISED.
21188///
21189/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
21190/// by the tile walk's reconstruction before anything reads it, so the
21191/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
21192/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
21193/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
21194/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
21195/// ways (see the lane report) and the two agree, which is the proof that no
21196/// unwritten sample reaches the output.
21197fn fresh_plane(n: usize) -> Vec<u16> {
21198 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
21199 return vec![PLANE_SENTINEL; n];
21200 }
21201 let mut v: Vec<u16> = Vec::with_capacity(n);
21202 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
21203 // capacity was just reserved, so the vector owns `n` initialised-or-not
21204 // `u16` slots. Every one is written by reconstruction before it is read
21205 // (proven by the sentinel gate above).
21206 #[allow(unsafe_code)]
21207 unsafe {
21208 v.set_len(n);
21209 }
21210 v
21211}
21212
21213#[derive(Clone)]
21214struct PlaneBuf<'a> {
21215 data: std::borrow::Cow<'a, [u16]>,
21216 width: usize,
21217 height: usize,
21218 /// The frame's true, decodable extent in this plane's own units — past
21219 /// this, samples are the padded coding surface's invented tail, never a
21220 /// real decoder's edge or reach reads.
21221 true_width: usize,
21222 true_height: usize,
21223 /// This plane's own tile's top-left pixel origin (spec: intra prediction
21224 /// never reaches across a tile boundary even though an earlier-decoded
21225 /// tile's real pixels sit right there in the shared buffer) — set via
21226 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
21227 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
21228 /// is threaded (the two-tile column-split stage 1 fixture's tile always
21229 /// ends at the frame's own right/bottom edge); a non-last tile's own
21230 /// right/bottom reach bound is still open, tracked in the report.
21231 tile_x0: usize,
21232 tile_y0: usize,
21233 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
21234 /// (exclusive) -- a non-last tile column/row's own reach must stop at
21235 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
21236 /// full padded extent) for the single-tile/last-tile case, matching the
21237 /// old unclipped behaviour exactly.
21238 tile_x1: usize,
21239 tile_y1: usize,
21240}
21241
21242/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
21243/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
21244/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
21245/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
21246/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
21247/// `ALTREF2`/`ALTREF`).
21248// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
21249// prints one PIXWRITE line per reconstruction store landing on that sample,
21250// naming the store site, the value it replaces and the one it leaves. Re-anchored
21251// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
21252// now live in `reconstruct_mc_rect`).
21253static PIXPROBE_ON: std::sync::LazyLock<bool> =
21254 std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
21255
21256static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> = std::sync::LazyLock::new(|| {
21257 crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
21258 let (x, y) = v.split_once(',')?;
21259 Some((
21260 x.trim().parse::<usize>().ok()?,
21261 y.trim().parse::<usize>().ok()?,
21262 ))
21263 })
21264});
21265
21266#[inline]
21267fn pix_write(
21268 site: &str,
21269 bx: usize,
21270 by: usize,
21271 bside: usize,
21272 x: usize,
21273 y: usize,
21274 prev: u16,
21275 val: u16,
21276) {
21277 if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
21278 eprintln!(
21279 "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
21280 std::panic::Location::caller()
21281 );
21282 }
21283}
21284
21285impl PlaneBuf<'_> {
21286 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
21287 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
21288 /// are already in this plane's own units (luma pixels for `y`, chroma
21289 /// pixels — halved — for `u`/`v`).
21290 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
21291 self.tile_x0 = x0;
21292 self.tile_y0 = y0;
21293 self.tile_x1 = x1;
21294 self.tile_y1 = y1;
21295 }
21296
21297 fn edges(
21298 &self,
21299 x: usize,
21300 y: usize,
21301 side: usize,
21302 reach: Reach,
21303 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
21304 let own_across = x + side.min(self.true_width.saturating_sub(x));
21305 let across = if reach.above_right {
21306 own_across + side.min(self.true_width.saturating_sub(own_across))
21307 } else {
21308 own_across
21309 }
21310 .min(self.width)
21311 .min(self.tile_x1);
21312 let own_down = y + side.min(self.true_height.saturating_sub(y));
21313 let down = if reach.below_left {
21314 own_down + side.min(self.true_height.saturating_sub(own_down))
21315 } else {
21316 own_down
21317 }
21318 .min(self.height)
21319 .min(self.tile_y1);
21320 let above = (y > self.tile_y0 && across > x)
21321 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
21322 let left = (x > self.tile_x0 && down > y).then(|| {
21323 (y..down)
21324 .map(|row| self.data[row * self.width + x - 1])
21325 .collect::<Vec<_>>()
21326 });
21327 let corner =
21328 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
21329 (above, left, corner)
21330 }
21331
21332 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
21333 /// the above/left reach each extend by their OWN axis (`bw` across,
21334 /// `bh` down), not one shared `side`.
21335 fn edges_rect(
21336 &self,
21337 x: usize,
21338 y: usize,
21339 bw: usize,
21340 bh: usize,
21341 reach: Reach,
21342 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
21343 let own_across = x + bw.min(self.true_width.saturating_sub(x));
21344 let across = if reach.above_right {
21345 own_across + bw.min(self.true_width.saturating_sub(own_across))
21346 } else {
21347 own_across
21348 }
21349 .min(self.width)
21350 .min(self.tile_x1);
21351 let own_down = y + bh.min(self.true_height.saturating_sub(y));
21352 let down = if reach.below_left {
21353 own_down + bh.min(self.true_height.saturating_sub(own_down))
21354 } else {
21355 own_down
21356 }
21357 .min(self.height)
21358 .min(self.tile_y1);
21359 let above = (y > self.tile_y0 && across > x)
21360 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
21361 let left = (x > self.tile_x0 && down > y).then(|| {
21362 (y..down)
21363 .map(|row| self.data[row * self.width + x - 1])
21364 .collect::<Vec<_>>()
21365 });
21366 let corner =
21367 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
21368 if matches!((bw, bh), (16, 8) | (8, 16)) {
21369 hit!(RECT_STRIP_PRED_HITS);
21370 if across > own_across || down > own_down {
21371 hit!(RECT_STRIP_REACH_HITS);
21372 }
21373 }
21374 (above, left, corner)
21375 }
21376
21377 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
21378 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
21379 /// already-rect-capable `(bw, bh)` pair.
21380 #[allow(clippy::too_many_arguments)]
21381 #[track_caller]
21382 fn reconstruct_rect(
21383 &mut self,
21384 x: usize,
21385 y: usize,
21386 bw: usize,
21387 bh: usize,
21388 mode: usize,
21389 angle_delta: i32,
21390 reach: Reach,
21391 residual: &[i32],
21392 cfl: Option<(i32, &[i32])>,
21393 filter_intra: Option<usize>,
21394 smooth_neighbor: bool,
21395 // lane-wave1 step (i): the palette/intrabc prediction override, taken
21396 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
21397 // than by this replay.
21398 pred: Option<Vec<u16>>,
21399 fctx: &crate::decode::FrameCtx,
21400 ) {
21401 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
21402 // (lane-palette2 r4): a palette block's prediction is the
21403 // reconstructed colour-index map, needing no edge pixels at all.
21404 let prediction = if let Some(buf) = pred {
21405 buf
21406 } else {
21407 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
21408 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
21409 eprintln!(
21410 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
21411 above.as_ref().map(|a| (a.len(), a[0])),
21412 left.as_ref().map(|l| l.len()),
21413 left.as_ref().map(|l| l[0]),
21414 self.tile_x0,
21415 self.tile_y0,
21416 self.true_width,
21417 self.true_height
21418 );
21419 }
21420 let mut prediction = vec![0u16; bw * bh];
21421 if let Some(fi_mode) = filter_intra {
21422 crate::intra::predict_filter_intra(
21423 fi_mode,
21424 above.as_deref(),
21425 left.as_deref(),
21426 corner,
21427 bw,
21428 bh,
21429 &mut prediction,
21430 fctx,
21431 );
21432 } else {
21433 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
21434 predict(
21435 mode as u8,
21436 angle_delta,
21437 above.as_deref(),
21438 left.as_deref(),
21439 corner,
21440 bw,
21441 bh,
21442 enable_edge_filter,
21443 smooth_neighbor,
21444 &mut prediction,
21445 fctx,
21446 );
21447 }
21448 prediction
21449 };
21450 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
21451 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
21452 if crate::envflags::env_flag!("EC_PRED") {
21453 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
21454 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
21455 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
21456 eprintln!(
21457 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
21458 std::panic::Location::caller(),
21459 recon_plane(),
21460 i32::from(smooth_neighbor)
21461 );
21462 }
21463 let residual = dense_residual(residual, bw * bh);
21464 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
21465 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
21466 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
21467 eprintln!(
21468 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
21469 );
21470 }
21471 for row in 0..bh {
21472 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
21473 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
21474 // whose padded width is not superblock aligned hangs past it.
21475 if y + row >= self.height {
21476 break;
21477 }
21478 for col in 0..bw {
21479 if x + col >= self.width {
21480 break;
21481 }
21482 let idx = row * bw + col;
21483 let mut base = i32::from(prediction[idx]);
21484 if let Some((alpha_q3, ac_q3)) = cfl {
21485 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
21486 }
21487 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
21488 pix_write(
21489 "reconstruct_rect",
21490 x,
21491 y,
21492 bw,
21493 x + col,
21494 y + row,
21495 self.data[(y + row) * self.width + x + col],
21496 sample,
21497 );
21498 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
21499 }
21500 }
21501 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
21502 // -- a block whose prediction matches the oracle's but whose written
21503 // samples do not is either a residual defect or a later overwrite, and
21504 // only this print separates the two.
21505 if crate::envflags::env_flag!("EC_PRED") {
21506 let row0: Vec<u16> = (0..bw.min(8))
21507 .map(|c| self.data[y * self.width + x + c])
21508 .collect();
21509 let col0: Vec<u16> = (0..bh.min(8))
21510 .map(|r| self.data[(y + r) * self.width + x])
21511 .collect();
21512 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
21513 }
21514 }
21515
21516 /// Predicts under `mode` then adds `residual` (side*side, raster),
21517 /// writing the clamped reconstruction back into the plane at `(x, y)`.
21518 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
21519 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
21520 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
21521 /// order (cfl.c).
21522 #[track_caller]
21523 fn reconstruct(
21524 &mut self,
21525 x: usize,
21526 y: usize,
21527 side: usize,
21528 mode: usize,
21529 angle_delta: i32,
21530 reach: Reach,
21531 residual: &[i32],
21532 cfl: Option<(i32, &[i32])>,
21533 filter_intra: Option<usize>,
21534 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
21535 // libaom `get_filt_type`): true when the block's above OR left
21536 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
21537 // Callers pass their own plane's neighbour-mode check
21538 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
21539 // callers until a smooth/paeth `uv_mode` can reach this call at all
21540 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
21541 // keeps `false` exact for chroma without this fn needing to know why.
21542 smooth_neighbor: bool,
21543 // lane-wave1 step (i): the palette/intrabc prediction override, taken
21544 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
21545 // than by this replay.
21546 pred: Option<Vec<u16>>,
21547 fctx: &crate::decode::FrameCtx,
21548 ) {
21549 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
21550 // takes priority over `predict()`/`predict_filter_intra` entirely --
21551 // palette prediction needs no edge pixels at all.
21552 let prediction = if let Some(buf) = pred {
21553 buf
21554 } else {
21555 let (above, left, corner) = self.edges(x, y, side, reach);
21556 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
21557 eprintln!(
21558 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
21559 above.as_deref(),
21560 left.as_deref(),
21561 );
21562 }
21563 let mut prediction = vec![0u16; side * side];
21564 if let Some(fi_mode) = filter_intra {
21565 crate::intra::predict_filter_intra(
21566 fi_mode,
21567 above.as_deref(),
21568 left.as_deref(),
21569 corner,
21570 side,
21571 side,
21572 &mut prediction,
21573 fctx,
21574 );
21575 } else {
21576 // `enable_intra_edge_filter` is the sequence header's own flag
21577 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
21578 // call, never per-block) -- threading it through every
21579 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
21580 // dozen sites for a value that never changes mid-decode, so it
21581 // rides a thread-local instead (this decoder is single-threaded
21582 // per stream).
21583 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
21584 predict(
21585 mode as u8,
21586 angle_delta,
21587 above.as_deref(),
21588 left.as_deref(),
21589 corner,
21590 side,
21591 side,
21592 enable_edge_filter,
21593 smooth_neighbor,
21594 &mut prediction,
21595 fctx,
21596 );
21597 }
21598 prediction
21599 };
21600 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
21601 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
21602 if crate::envflags::env_flag!("EC_PRED") {
21603 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
21604 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
21605 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
21606 eprintln!(
21607 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
21608 std::panic::Location::caller(),
21609 recon_plane(),
21610 i32::from(smooth_neighbor)
21611 );
21612 }
21613 let residual = dense_residual(residual, side * side);
21614 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
21615 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
21616 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
21617 eprintln!(
21618 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
21619 cfl.is_some()
21620 );
21621 }
21622 for row in 0..side {
21623 // lane-sb128c r8: libaom's frame buffer is superblock
21624 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
21625 // transform unit of a 128x64 block at the BOTTOM frame edge
21626 // can hang past the last padded row (1920x792: a unit at
21627 // y=768 wants 832 rows of an 800-row buffer, which panicked
21628 // the film's key frames). Those samples are outside the
21629 // frame: never output, and no block below ever references
21630 // them.
21631 if y + row >= self.height {
21632 break;
21633 }
21634 for col in 0..side {
21635 if x + col >= self.width {
21636 break;
21637 }
21638 let idx = row * side + col;
21639 let mut base = i32::from(prediction[idx]);
21640 if let Some((alpha_q3, ac_q3)) = cfl {
21641 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
21642 }
21643 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
21644 pix_write(
21645 "reconstruct",
21646 x,
21647 y,
21648 side,
21649 x + col,
21650 y + row,
21651 self.data[(y + row) * self.width + x + col],
21652 sample,
21653 );
21654 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
21655 }
21656 }
21657 }
21658}
21659
21660/// Reads one plane's transform block, reconstructs it into `plane` at
21661/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
21662#[allow(clippy::too_many_arguments)]
21663fn read_plane(
21664 dec: &mut SymbolDecoder,
21665 cdfs: &mut Cdfs,
21666 set: TxbSet,
21667 scan: &[u16],
21668 plane_idx: usize,
21669 around: (bool, bool, i32),
21670 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
21671 // it for every plane's `txb` lookup (it is what an intra transform type's
21672 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
21673 tx_mode: usize,
21674 predict_mode: usize,
21675 angle_delta: i32,
21676 reach: Reach,
21677 // lane-wave1 step (i): unread -- this reader records its write
21678 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
21679 // stays in the signature so every call site still proves the plane is
21680 // exclusively held while its coefficients are parsed.
21681 _plane: &mut PlaneBuf<'static>,
21682 x: usize,
21683 y: usize,
21684 side: usize,
21685 tx_side: usize,
21686 base_q_idx: u8,
21687 cfl: Option<(i32, CflSrc)>,
21688 filter_intra: Option<usize>,
21689 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
21690 // smaller than its own block (spec `get_txb_ctx_general`'s
21691 // `plane_bsize != tx_size` branch), carrying the already-looked-up
21692 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
21693 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
21694 // formula below.
21695 luma_skip_ctx: Option<usize>,
21696 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
21697 smooth_neighbor: bool,
21698 fctx: &crate::decode::FrameCtx,
21699) -> Result<Grid> {
21700 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
21701 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
21702 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
21703 // no chroma write is recorded. Return the all-zero grid the caller's
21704 // neighbour bookkeeping reads, without consuming a bit.
21705 if plane_idx > 0 && mono(fctx) {
21706 return Ok(Grid::Zero(side * side));
21707 }
21708 // lane-av1readcensus: the units read from here on are this plane's.
21709 set_census_plane(plane_idx);
21710 let skip_ctx = if plane_idx == 0 {
21711 luma_skip_ctx.unwrap_or(0)
21712 } else {
21713 // libaom `get_txb_ctx`: a chroma unit's context is
21714 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
21715 // plane block is bigger than the transform. Our chroma tables hold the
21716 // offset-7 rows first, so the caller adds 3 for the bigger-block case
21717 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
21718 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
21719 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
21720 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
21721 };
21722 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
21723 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
21724 // not by the block's ordinary `mode` (which is always DC_PRED whenever
21725 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
21726 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
21727 // filter-intra in AV1).
21728 // lane-av1444chr: per-TU mode trace with the PLANE named. `PlaneBuf`'s own
21729 // `OUR_PRED` rung cannot carry it (reconstruction does not know its
21730 // plane), and a rung whose plane has to be guessed from the values has
21731 // already produced wrong claims twice this session -- `read_coeffs_rect`
21732 // labelling its unit `plane=0`, and a sweep reading a second-luma-unit
21733 // phantom out of that label (class `rung-mislabels-plane`). Diagnostic
21734 // only: no gate asserts decode behaviour off this line.
21735 if crate::envflags::env_flag!("EC_TRACE_MODE") {
21736 eprintln!(
21737 "OUR_MODE plane={plane_idx} x={x} y={y} side={side} mode={predict_mode} \
21738 ad={angle_delta} fi={filter_intra:?} reach={reach:?}"
21739 );
21740 }
21741 let tx_mode = if plane_idx == 0 {
21742 fi_tx_row(tx_mode, filter_intra)
21743 } else {
21744 tx_mode
21745 };
21746 let mut coding = cdfs.txb(set, tx_mode);
21747 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
21748 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
21749 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
21750 // plane of a lossless block (the residual then goes through the WHT, so
21751 // the type only picks the scan, which is the default one).
21752 if lossless(fctx) {
21753 coding.tx_type = None;
21754 }
21755 // A chroma plane's `tx_type` is *never* its own coded symbol
21756 // (`coding.tx_type` is always `None` for every `TxbSet::Chroma*`), so it is
21757 // resolved, not read. Three cases, in libaom's own order
21758 // (`av1_get_tx_type` / `av1_get_ext_tx_set_type`, `blockd.h`):
21759 //
21760 // * **intra** chroma: `intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV)` -- the
21761 // plane's own predicted mode (`default_intra_tx_type`) -- then clamped by
21762 // `av1_get_ext_tx_set_type`. At 32 points and up that set is
21763 // `EXT_TX_SET_DCTONLY` (the `is_inter ? EXT_TX_SET_DCT_IDTX :
21764 // EXT_TX_SET_DCTONLY` line), which forces `DCT_DCT` no matter what the
21765 // mode-indexed table said. `TxbSet::Chroma8`/`Chroma16` never hit this --
21766 // every value `default_intra_tx_type` can produce is already a member of
21767 // both `TX_SET_INTRA_1`/`_2`, so nothing narrows there -- only
21768 // `Chroma32` and up do.
21769 // * **inter** chroma, i.e. [`INTRABC_CHROMA_TX`]: the same
21770 // `xd->tx_type_map` cell the luma unit stamped (`blk_row <<=
21771 // pd->subsampling_y`, `blk_col <<= pd->subsampling_x`), reduced by the
21772 // INTER transform set. At **32 points** that set is
21773 // `EXT_TX_SET_DCT_IDTX`, NOT `EXT_TX_SET_DCTONLY` -- so a 32-point
21774 // inter chroma unit inherits the luma's coded `IDTX`, and the identity
21775 // transform (a plain copy) is what libaom actually runs.
21776 // [`reduce_inherited_chroma_tx_type`] is that reduction verbatim.
21777 // * 64 points and up is `EXT_TX_SET_DCTONLY` for both, which the same
21778 // reduction already yields.
21779 //
21780 // The `side >= 32` -> `DCT_DCT` clamp this replaces was written for the
21781 // intra case (and read as libaom's clamp at `tx_size_sqr_up >= TX_32X32`),
21782 // but libaom's cap is `txsize_sqr_up_map[tx_size] > TX_32X32` -- 64 and up
21783 // -- so it also swallowed a 32-point INTER chroma unit's inherited `IDTX`
21784 // and ran `DCT_DCT` where libaom ran the identity transform.
21785 // Sub-32 units keep the raw inherited type exactly as before.
21786 let default_tx_type = if plane_idx == 0 {
21787 TxType::DctDct
21788 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
21789 if side >= 32 {
21790 reduce_inherited_chroma_tx_type(inherited, side, side, fctx)
21791 } else {
21792 inherited
21793 }
21794 } else if side >= 32 {
21795 TxType::DctDct
21796 } else {
21797 default_intra_tx_type(predict_mode as u8)
21798 };
21799 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
21800 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
21801 let default_tx_type = if lossless(fctx) {
21802 TxType::DctDct
21803 } else {
21804 default_tx_type
21805 };
21806 let (grid, tx_type) = read_coeffs(
21807 dec,
21808 &mut coding,
21809 scan,
21810 skip_ctx,
21811 dc_sign_ctx(around.2),
21812 default_tx_type,
21813 None,
21814 )?;
21815 note_chroma_class1(plane_idx, tx_type);
21816 if plane_idx == 0 {
21817 fctx.luma_tx_type.with(|c| c.set(tx_type));
21818 }
21819 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
21820 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
21821 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
21822 // guard also assumes.
21823 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
21824 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
21825 // keyed by that true size, not the coded corner's -- so the corner
21826 // goes into the top-left of a `side`-sized grid, not the reverse.
21827 let levels = extend_corner(grid, tx_side, tx_side, side, side);
21828 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
21829 let tx = TxParams {
21830 plane: plane_idx,
21831 w: side,
21832 h: side,
21833 bit_depth: bit_depth(fctx),
21834 q_idx: block_q_idx(fctx),
21835 dc_delta,
21836 ac_delta,
21837 tx_type,
21838 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
21839 stride: 0,
21840 lossless: lossless(fctx),
21841 };
21842 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21843 let residual = tx.run(&levels);
21844 eprintln!(
21845 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
21846 &*levels,
21847 );
21848 }
21849 push_intra_tx(
21850 plane_idx,
21851 x,
21852 y,
21853 side,
21854 side,
21855 false,
21856 predict_mode,
21857 angle_delta,
21858 reach,
21859 tx,
21860 &levels,
21861 cfl,
21862 filter_intra,
21863 smooth_neighbor,
21864 fctx,
21865 );
21866 // `record`'s neighbour state only reads whether *the coded grid* (not the
21867 // residual) has nonzero entries, so the levels this function already
21868 // built are what it wants back -- both arms of the old `tx_side == side`
21869 // branch returned exactly that, one of them through a full `to_vec` copy
21870 // of the grid per intra transform unit (lane-coefbuf).
21871 Ok(levels)
21872}
21873
21874/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
21875/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
21876/// block's own rect shape, and the `rect` flag selects
21877/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
21878#[allow(clippy::too_many_arguments)]
21879fn push_intra_unit(
21880 plane: usize,
21881 x: usize,
21882 y: usize,
21883 w: usize,
21884 h: usize,
21885 mode: usize,
21886 angle_delta: i32,
21887 reach: Reach,
21888 residual: &[i32],
21889 cfl: Option<(i32, CflSrc)>,
21890 filter_intra: Option<usize>,
21891 smooth_neighbor: bool,
21892 fctx: &crate::decode::FrameCtx,
21893) {
21894 if w == h {
21895 push_intra(
21896 plane,
21897 x,
21898 y,
21899 w,
21900 mode,
21901 angle_delta,
21902 reach,
21903 residual,
21904 cfl,
21905 filter_intra,
21906 smooth_neighbor,
21907 fctx,
21908 );
21909 } else {
21910 push_intra_rect(
21911 plane,
21912 x,
21913 y,
21914 w,
21915 h,
21916 mode,
21917 angle_delta,
21918 reach,
21919 residual,
21920 cfl,
21921 filter_intra,
21922 smooth_neighbor,
21923 fctx,
21924 );
21925 }
21926}
21927
21928/// ONE RECT chroma transform unit of a square block's uv plane
21929/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
21930/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
21931/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
21932/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
21933/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
21934/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
21935/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
21936/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
21937/// predicted mode supplies the mode-derived default `tx_type` unless an armed
21938/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
21939/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
21940/// ([`read_plane`]'s `side >= 32` clamp).
21941#[allow(clippy::too_many_arguments)]
21942fn read_rect_chroma_unit(
21943 dec: &mut SymbolDecoder,
21944 cdfs: &mut Cdfs,
21945 set: TxbSet,
21946 scan: &[u16],
21947 w: usize,
21948 h: usize,
21949 plane_idx: usize,
21950 around: (bool, bool, i32),
21951 uv_predict_mode: usize,
21952 angle_delta_uv: i32,
21953 reach: Reach,
21954 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
21955 // the plane exclusively while the unit's coefficients are parsed.
21956 _plane: &mut PlaneBuf<'static>,
21957 x: usize,
21958 y: usize,
21959 // Signature parity with [`read_plane`]; the dequant reads its q index
21960 // off `block_q_idx(fctx)` like every other reader here.
21961 _base_q_idx: u8,
21962 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
21963 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
21964 // where `ctx_offset` is 10 when the plane block is bigger than the
21965 // transform and 7 otherwise. The port stores the offset-7 rows at
21966 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
21967 // (lane-av1-422b), so a unit SMALLER than its plane block passes
21968 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
21969 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
21970 // rect unit except in the chunk arms.
21971 chroma_skip_offset: Option<usize>,
21972 cfl: Option<(i32, CflSrc)>,
21973 smooth_neighbor_uv: bool,
21974 fctx: &crate::decode::FrameCtx,
21975) -> Result<Grid> {
21976 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
21977 hit!(CHROMA422_RECT_HITS);
21978 }
21979 // The same three cases as [`read_plane`], for the same reason: at 32 points
21980 // an INTER chroma unit's transform set is `EXT_TX_SET_DCT_IDTX` (the luma's
21981 // coded `IDTX` survives) where the intra set is `EXT_TX_SET_DCTONLY`, and
21982 // an armed [`INTRABC_CHROMA_TX`] slot means the block IS an inter block.
21983 let default_tx = if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
21984 if w.max(h) >= 32 {
21985 reduce_inherited_chroma_tx_type(inherited, w, h, fctx)
21986 } else {
21987 inherited
21988 }
21989 } else if w.max(h) >= 32 {
21990 TxType::DctDct
21991 } else {
21992 default_intra_tx_type(uv_predict_mode as u8)
21993 };
21994 let mut coding = cdfs.txb(set, uv_predict_mode);
21995 let (levels, tx_type) = read_coeffs_rect(
21996 dec,
21997 &mut coding,
21998 scan,
21999 w,
22000 h,
22001 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
22002 dc_sign_ctx(around.2),
22003 default_tx,
22004 plane_idx,
22005 )?;
22006 let residual = dequant_and_inverse_typed_wh(
22007 &levels,
22008 w,
22009 h,
22010 crate::decode::bit_depth(fctx),
22011 block_q_idx(fctx),
22012 plane_q_delta(plane_idx, fctx).0,
22013 plane_q_delta(plane_idx, fctx).1,
22014 tx_type,
22015 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
22016 );
22017 push_intra_rect(
22018 plane_idx,
22019 x,
22020 y,
22021 w,
22022 h,
22023 uv_predict_mode,
22024 angle_delta_uv,
22025 reach,
22026 &residual,
22027 cfl,
22028 None,
22029 smooth_neighbor_uv,
22030 fctx,
22031 );
22032 Ok(levels)
22033}
22034
22035/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
22036/// three planes, reconstructing them into `y`/`u`/`v` and updating
22037/// `neighbours`.
22038#[allow(clippy::too_many_arguments)]
22039fn decode_block(
22040 dec: &mut SymbolDecoder,
22041 cdfs: &mut Cdfs,
22042 neighbours: &mut Neighbours,
22043 at: (usize, usize),
22044 side: usize,
22045 luma_set: TxbSet,
22046 chroma_set: TxbSet,
22047 luma_tx: usize,
22048 chroma_tx: usize,
22049 scans: (&[u16], &[u16]),
22050 cfl: bool,
22051 y: &mut PlaneBuf<'static>,
22052 u: &mut PlaneBuf<'static>,
22053 v: &mut PlaneBuf<'static>,
22054 base_q_idx: u8,
22055 enable_filter_intra: bool,
22056 allow_screen_content_tools: bool,
22057 allow_intrabc: bool,
22058 scan32: &[u16],
22059 scan16: &[u16],
22060 scan8: &[u16],
22061 scan4: &[u16],
22062 tx_select: bool,
22063 reduced_tx_set: bool,
22064 fctx: &crate::decode::FrameCtx,
22065) -> Result<()> {
22066 let (r, c) = at;
22067 let (px, py) = (c * SUB, r * SUB);
22068 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
22069 let palette_uv_cache = neighbours.palette_uv_cache(at);
22070 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22071 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
22072 let (
22073 skip,
22074 mode,
22075 angle_delta_y,
22076 uv_mode,
22077 angle_delta_uv,
22078 alpha,
22079 filter_intra,
22080 palette_y,
22081 palette_uv,
22082 ) = read_intra_mode(
22083 dec,
22084 cdfs,
22085 nb_above_mode,
22086 nb_left_mode,
22087 cfl,
22088 side,
22089 enable_filter_intra,
22090 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
22091 allow_screen_content_tools,
22092 allow_intrabc,
22093 Some((palette_ctx, &palette_cache)),
22094 &palette_uv_cache,
22095 r * (SUB / MI),
22096 c * (SUB / MI),
22097 fctx,
22098 )?;
22099 if at_tile_left && palette_y.is_some() {
22100 hit!(PALETTE_TILE_LEFT_HITS);
22101 }
22102 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
22103 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
22104 // tables/scans are replaced by the 4x4 ones and the block always takes the
22105 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
22106 // sit at the TOP of the function -- before `read_intra_mode`, which is
22107 // where the block's own `segment_id` is read -- so a mixed frame resolved
22108 // every block's geometry against the PREVIOUS block's segment (a lossless
22109 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
22110 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
22111 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
22112 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
22113 // rewrite (which sat above `read_intra_mode`) rides along here -- same
22114 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
22115 // segment like the lossless arm above it.
22116 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
22117 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
22118 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
22119 let tx = if side >= 64 { 32 } else { side };
22120 let (set, scan): (TxbSet, &[u16]) = match tx {
22121 32 => (TxbSet::Chroma32, scan32),
22122 16 => (TxbSet::Chroma16, scan16),
22123 8 => (TxbSet::Chroma8, scan8),
22124 _ => (TxbSet::Chroma4, scan4),
22125 };
22126 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
22127 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22128 // lane-av1-422f: the uv plane block is the (side/2, side) rect
22129 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
22130 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
22131 // the RECT that fills the plane block, NOT the square transform of
22132 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
22133 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
22134 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
22135 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
22136 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
22137 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
22138 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
22139 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
22140 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
22141 let (tx_w, tx_h) = match side {
22142 4 => (4, 4),
22143 8 => (4, 8),
22144 16 => (8, 16),
22145 32 => (16, 32),
22146 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
22147 _ => (32, 32),
22148 };
22149 let (set, scan): (TxbSet, &[u16]) = match side {
22150 4 => (TxbSet::Chroma4, scan4),
22151 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
22152 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
22153 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
22154 _ => (TxbSet::Chroma32, scan32),
22155 };
22156 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
22157 } else {
22158 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
22159 };
22160 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
22161 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
22162 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
22163 // actual chroma-from-luma correlation, same as this decoder always did.
22164 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22165 DC_PRED
22166 } else {
22167 uv_mode
22168 };
22169 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22170 if smooth_neighbor {
22171 hit!(SMOOTH_LUMA_HITS);
22172 }
22173 let smooth_neighbor_uv =
22174 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
22175 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22176 eprintln!(
22177 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
22178 angle_delta_uv={angle_delta_uv}"
22179 );
22180 }
22181 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
22182 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
22183 // block, skipped or not. `logical_tx` is what the loop filter's edge
22184 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
22185 // transform size -- 64 even for the 64x64 corner-scanned case, spec
22186 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
22187 // which only differs from it at that one corner case.
22188 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
22189 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
22190 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
22191 // intrabc block reads NO tx-size symbol at all -- it takes
22192 // `maxRectTxSize` -- while every ordinary skipped intra block does read
22193 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
22194 // the tile from that block on (class `equal-range-means-unread`).
22195 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
22196 // tree instead (`read_var_tx_size`), the same syntax the inter block path
22197 // has always read -- libaom's `parse_decode_block` dispatches on
22198 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
22199 // intrabc block as inter.
22200 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
22201 // libaom `parse_decode_block`'s var-tx tree condition carries
22202 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
22203 // block inside a LOSSLESS segment of a mixed frame reads NO
22204 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
22205 // hands back TX_4X4. Invisible while every lossless frame was also
22206 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
22207 // is why the mixed frame is the first stream to reach it.
22208 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
22209 let intrabc_leaves = if intrabc_vartx {
22210 let max_tx = side.min(64);
22211 // `max_block_wide`/`max_block_high`: the frame's own mi grid
22212 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
22213 // right/bottom edge reads no split symbol for the units outside it.
22214 let mi_cols = 2 * y.true_width.div_ceil(8);
22215 let mi_rows = 2 * y.true_height.div_ceil(8);
22216 let side_mi = side / MI;
22217 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
22218 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
22219 let mut leaves = Vec::new();
22220 for row in (0..side_mi).step_by(max_tx / MI) {
22221 for col in (0..side_mi).step_by(max_tx / MI) {
22222 read_var_tx_size(
22223 dec,
22224 cdfs,
22225 neighbours,
22226 (mi_r, mi_c),
22227 side,
22228 (max_w_mi, max_h_mi),
22229 (max_tx, max_tx),
22230 0,
22231 row,
22232 col,
22233 &mut leaves,
22234 );
22235 }
22236 }
22237 hit!(INTRABC_VARTX_HITS);
22238 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
22239 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
22240 // longer refused -- the luma reconstruct below walks the tree's own
22241 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
22242 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
22243 // transform unit), so mixed sizes reconstruct at their own stride.
22244 // The counter marks the shape so a gate can prove a witness actually
22245 // carries a mixed tree and not merely another uniform one.
22246 let uniform = leaves.first().is_some_and(|f| {
22247 leaves
22248 .iter()
22249 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
22250 });
22251 if !uniform {
22252 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
22253 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
22254 eprintln!(
22255 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
22256 dv={intrabc_dv:?} leaves={leaves:?}"
22257 );
22258 }
22259 }
22260 Some(leaves)
22261 } else {
22262 None
22263 };
22264 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
22265 (tx, if tx == 64 { 32 } else { tx })
22266 } else if tx_select && !intrabc_skip_tx {
22267 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
22268 (resolved, if resolved == 64 { 32 } else { resolved })
22269 } else {
22270 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
22271 // TX_64X64, so a 128x128 block is always FOUR luma transform units
22272 // even with `tx_select` off -- the TU loop below, never the
22273 // single-unit path.
22274 (lossless_tx(side.min(64), fctx), luma_tx)
22275 };
22276 if tx_select && logical_tx < side && uv_mode != DC_PRED {
22277 hit!(SQ_CHROMA_TX_HITS);
22278 }
22279 let luma_set = if tx_select {
22280 txbset_for(logical_tx, reduced_tx_set)
22281 } else {
22282 luma_set
22283 };
22284 let luma_set = if intrabc_dv.is_some() {
22285 inter_txbset_for(logical_tx, reduced_tx_set)
22286 } else {
22287 luma_set
22288 };
22289 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
22290 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
22291 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22292 let chroma_side = side >> ss_x(fctx);
22293 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
22294 // `side / 2` at 4:2:0.
22295 let chroma_height = side >> ss_y(fctx);
22296 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
22297 // frame's own pre-loop-filter reconstruction (all loop filters are off
22298 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
22299 // block vector, with the BILINEAR kernel libaom forces for intrabc --
22300 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
22301 // odd, which is exactly what the bilinear taps then interpolate.
22302 flush_recon(fctx, y, u, v);
22303 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
22304 let mut yb = vec![0u16; side * side];
22305 mc::predict_with_filter(
22306 &y.data,
22307 y.width,
22308 y.true_width,
22309 y.true_height,
22310 mv_to_q4(px, dv_col, 0),
22311 mv_to_q4(py, dv_row, 0),
22312 side,
22313 side,
22314 mc::InterpFilterKind::Bilinear,
22315 &mut yb,
22316 fctx,
22317 );
22318 let mut ub = vec![0u16; chroma_side * chroma_height];
22319 mc::predict_with_filter(
22320 &u.data,
22321 u.width,
22322 u.true_width,
22323 u.true_height,
22324 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22325 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22326 chroma_side,
22327 chroma_height,
22328 mc::InterpFilterKind::Bilinear,
22329 &mut ub,
22330 fctx,
22331 );
22332 let mut vb = vec![0u16; chroma_side * chroma_height];
22333 mc::predict_with_filter(
22334 &v.data,
22335 v.width,
22336 v.true_width,
22337 v.true_height,
22338 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22339 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22340 chroma_side,
22341 chroma_height,
22342 mc::InterpFilterKind::Bilinear,
22343 &mut vb,
22344 fctx,
22345 );
22346 (yb, ub, vb)
22347 });
22348 // A palette-Y block's own prediction is the reconstructed colour-index
22349 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
22350 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
22351 // parameter through this function's dozen `y.reconstruct`/`read_plane`
22352 // sites. A split luma transform (`tx_select && logical_tx != side`)
22353 // would need the map sliced per-TU -- untested against a real
22354 // `--enable-palette=1` stream this round, so refuse by name rather than
22355 // guess at the slicing (charter's own named-acceptable fallback).
22356 let palette_y_buf: Option<Vec<u16>> = palette_y
22357 .as_ref()
22358 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
22359 // lane-t900 r32: the intrabc luma prediction rides the very same
22360 // whole-block override slot, so the multi-TU loop below windows it per
22361 // transform unit exactly like a palette map -- setting it once up front
22362 // handed the whole `side`x`side` buffer to the FIRST unit and left every
22363 // later one predicting off block edges (the var-tx tree above is what
22364 // first makes `logical_tx < side` reachable for an intrabc block).
22365 let palette_y_buf = match &intrabc_bufs {
22366 Some((yb, _, _)) => Some(yb.clone()),
22367 None => palette_y_buf,
22368 };
22369 // With one luma transform unit the whole `side`x`side` map is the
22370 // prediction; with several (`logical_tx != side`) each unit takes its own
22371 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
22372 // below (lane-palette2 r7) -- setting the full-block buffer here would be
22373 // taken by the FIRST unit and indexed at the wrong stride.
22374 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
22375 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
22376 // `split_tx_skip` walk), so its map must be armed here even when the
22377 // transform is split. Gating the arm on `logical_tx == side` alone left a
22378 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
22379 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
22380 // key frame; class override-slot-on-one-arm). Neither prediction is
22381 // edge-derived, so the whole-block buffer at the block's own stride is
22382 // exactly what that single call wants.
22383 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
22384 // that reaches this block apart from one that never does (class
22385 // gate-blind-to-feature).
22386 if palette_y_buf.is_some() && skip && logical_tx < side {
22387 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
22388 }
22389 if let Some(buf) = &palette_y_buf
22390 && (logical_tx == side || skip)
22391 {
22392 set_palette_pred(buf.clone(), fctx);
22393 }
22394 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
22395 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
22396 // plane's own `reconstruct`/`read_plane` call below (never both planes at
22397 // once), since Y's own set-then-take already emptied the slot by the time
22398 // either of these run.
22399 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
22400 (
22401 puv.map
22402 .iter()
22403 .map(|&idx| puv.u_colors[idx as usize])
22404 .collect(),
22405 puv.map
22406 .iter()
22407 .map(|&idx| puv.v_colors[idx as usize])
22408 .collect(),
22409 )
22410 });
22411 // The chroma half of the intrabc prediction rides the same per-plane
22412 // override slot the UV-palette buffers do (set fresh before each plane's
22413 // own `reconstruct`/`read_plane` call below).
22414 let palette_uv_bufs = match &intrabc_bufs {
22415 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
22416 None => palette_uv_bufs,
22417 };
22418 if skip {
22419 // A skipped block codes no residual syntax at all (spec 5.11.34):
22420 // straight prediction, on every plane.
22421 //
22422 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
22423 // is skipped (only an INTER skip forces the largest transform), and
22424 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
22425 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
22426 // already written left/above of it inside this same block. Predicting
22427 // the whole `side`x`side` at once gives a different (uniformly off by
22428 // ~1) answer, which is exactly the residue this lane was chasing.
22429 // The palette/intrabc override path keeps the single-call shape (its
22430 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
22431 // untested for skip and unreachable in these streams).
22432 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
22433 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
22434 // per-unit prediction is keyed on the transform being smaller than
22435 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
22436 // narrower meaning (a READ split tx depth).
22437 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
22438 if split_tx_skip {
22439 if tx_select {
22440 hit!(SKIP_SPLIT_TX_HITS);
22441 }
22442 let n_axis = side / logical_tx;
22443 for tu_row in 0..n_axis {
22444 for tu_col in 0..n_axis {
22445 let tu_px = px + tu_col * logical_tx;
22446 let tu_py = py + tu_row * logical_tx;
22447 if tu_px >= y.true_width || tu_py >= y.true_height {
22448 continue;
22449 }
22450 let tu_reach = tu_reach(
22451 side,
22452 side,
22453 tu_col * logical_tx,
22454 tu_row * logical_tx,
22455 logical_tx,
22456 reach,
22457 px,
22458 py,
22459 y.width,
22460 y.height,
22461 fctx,
22462 );
22463 push_intra(
22464 0,
22465 tu_px,
22466 tu_py,
22467 logical_tx,
22468 mode,
22469 angle_delta_y,
22470 tu_reach,
22471 &ZERO_RESIDUAL[..logical_tx * logical_tx],
22472 None,
22473 filter_intra,
22474 smooth_neighbor,
22475 fctx,
22476 );
22477 }
22478 }
22479 } else {
22480 push_intra(
22481 0,
22482 px,
22483 py,
22484 side,
22485 mode,
22486 angle_delta_y,
22487 reach,
22488 &ZERO_RESIDUAL[..side * side],
22489 None,
22490 filter_intra,
22491 smooth_neighbor,
22492 fctx,
22493 );
22494 }
22495 let ac = alpha.map(|_| cfl_src(px, py, side));
22496 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
22497 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
22498 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
22499 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
22500 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
22501 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
22502 // reads ONE unit per plane, the whole plane block).
22503 let cn_cols = (chroma_side / chroma_tx).max(1);
22504 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22505 let luma_span_x = chroma_tx << ss_x(fctx);
22506 let luma_span_y = chroma_tx_h << ss_y(fctx);
22507 for cu_row in 0..cn_rows {
22508 for cu_col in 0..cn_cols {
22509 let cu_r = if cn_rows == 1 && cn_cols == 1 {
22510 reach
22511 } else {
22512 tu_reach_rect(
22513 side,
22514 side,
22515 cu_col * luma_span_x,
22516 cu_row * luma_span_y,
22517 luma_span_x,
22518 luma_span_y,
22519 reach,
22520 px,
22521 py,
22522 y.width,
22523 y.height,
22524 fctx,
22525 )
22526 };
22527 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22528 // lane-av1chromadc: the chroma override is a whole
22529 // `chroma_side x chroma_height` buffer and
22530 // `PlaneBuf::reconstruct` uses the buffer it takes as the
22531 // UNIT's own `chroma_tx x chroma_tx_h` prediction, so a
22532 // multi-unit plane block must hand each unit its own window of
22533 // it. Handing the whole buffer (the pre-fix shape) made every
22534 // unit predict from the top-left one: at 4:2:0 the chroma plane
22535 // block is a single 32x32 unit, so the whole buffer IS that
22536 // unit's window and the bug is invisible -- which is why every
22537 // 4:2:0 gate stayed green -- and at 4:4:4 a 64x64 block's 64x64
22538 // plane block is a 2x2 grid whose right and bottom columns were
22539 // a copy of its top-left unit.
22540 // MEASURED on `fixtures/r512.obu` (4:4:4 8-bit 512x512, three
22541 // frames): frame 0's skipped 64x64 intra-BC block at
22542 // `mi=(112,80)` `px=(320,448)` reconstructed its `cu=(1,0)`
22543 // unit at `px=(352,448)` as a flat 241 where the oracle has
22544 // 202 -- byte-identical to its `cu=(0,0)` prediction, sum
22545 // 882176 and all -- and the coded 64x64 to its right then read
22546 // 202/175 against the oracle's 165/166. Gate:
22547 // `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`.
22548 let chroma_window = |buf: &[u16]| -> Vec<u16> {
22549 if cn_cols == 1 && cn_rows == 1 {
22550 return buf.to_vec();
22551 }
22552 let mut window = Vec::with_capacity(chroma_tx * chroma_tx_h);
22553 for row in 0..chroma_tx_h {
22554 let at = (cu_row * chroma_tx_h + row) * chroma_side + cu_col * chroma_tx;
22555 window.extend_from_slice(&buf[at..at + chroma_tx]);
22556 }
22557 window
22558 };
22559 if let Some((ub, _)) = &palette_uv_bufs {
22560 if cn_cols * cn_rows > 1 {
22561 hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS);
22562 }
22563 set_palette_pred(chroma_window(ub), fctx);
22564 }
22565 push_intra_unit(
22566 1,
22567 cu_x,
22568 cu_y,
22569 chroma_tx,
22570 chroma_tx_h,
22571 uv_predict_mode,
22572 angle_delta_uv,
22573 cu_r,
22574 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
22575 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22576 None,
22577 smooth_neighbor_uv,
22578 fctx,
22579 );
22580 if let Some((_, vb)) = &palette_uv_bufs {
22581 set_palette_pred(chroma_window(vb), fctx);
22582 }
22583 push_intra_unit(
22584 2,
22585 cu_x,
22586 cu_y,
22587 chroma_tx,
22588 chroma_tx_h,
22589 uv_predict_mode,
22590 angle_delta_uv,
22591 cu_r,
22592 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
22593 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22594 None,
22595 smooth_neighbor_uv,
22596 fctx,
22597 );
22598 }
22599 }
22600 let luma_grid = vec![0i32; side * side];
22601 let u_grid = vec![0i32; chroma_side * chroma_side];
22602 let v_grid = vec![0i32; chroma_side * chroma_side];
22603 neighbours.record(
22604 at,
22605 side,
22606 mode,
22607 uv_predict_mode,
22608 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22609 );
22610 } else if logical_tx == side {
22611 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
22612 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
22613 // that arm was redundant -- and wrong at 128, where
22614 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
22615 // block is four units whether or not `tx_select` is on.
22616 // A single luma transform unit -- the old path, unchanged (including
22617 // the 64x64 corner case, `logical_tx == side == 64` with
22618 // `coeff_tx_side == 32`).
22619 let around = neighbours.around(at, side);
22620 let luma_grid = read_plane(
22621 dec,
22622 cdfs,
22623 luma_set,
22624 luma_scan,
22625 0,
22626 around[0],
22627 mode,
22628 mode,
22629 angle_delta_y,
22630 reach,
22631 y,
22632 px,
22633 py,
22634 side,
22635 coeff_tx_side,
22636 base_q_idx,
22637 None,
22638 filter_intra,
22639 None,
22640 smooth_neighbor,
22641 fctx,
22642 )?;
22643 let ac = alpha.map(|_| cfl_src(px, py, side));
22644 // Armed for exactly this block's two chroma reads (see
22645 // [`INTRABC_CHROMA_TX`]); the luma call above just set
22646 // [`LUMA_TX_TYPE`] to the type it coded.
22647 if intrabc_dv.is_some() {
22648 fctx.intrabc_chroma_tx
22649 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
22650 }
22651 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
22652 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
22653 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
22654 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
22655 // (every U, then every V) — the same loop the multi-TU arm runs.
22656 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
22657 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
22658 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
22659 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
22660 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
22661 // unit is the plane block's own rect.
22662 let cn_cols = (chroma_side / chroma_tx).max(1);
22663 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22664 let luma_span_x = chroma_tx << ss_x(fctx);
22665 let luma_span_y = chroma_tx_h << ss_y(fctx);
22666 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
22667 if chroma_tx == chroma_tx_h {
22668 if let Some((ub, _)) = &palette_uv_bufs {
22669 set_palette_pred(ub.clone(), fctx);
22670 }
22671 let u_grid = read_plane(
22672 dec,
22673 cdfs,
22674 chroma_set,
22675 scans.1,
22676 1,
22677 around[1],
22678 mode,
22679 uv_predict_mode,
22680 angle_delta_uv,
22681 reach,
22682 u,
22683 cpx,
22684 cpy,
22685 chroma_side,
22686 chroma_tx,
22687 base_q_idx,
22688 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22689 None,
22690 None,
22691 smooth_neighbor_uv,
22692 fctx,
22693 )?;
22694 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22695 eprintln!(
22696 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
22697 &u.data[cpy * u.width + cpx..][..chroma_side]
22698 );
22699 }
22700 if let Some((_, vb)) = &palette_uv_bufs {
22701 set_palette_pred(vb.clone(), fctx);
22702 }
22703 let v_grid = read_plane(
22704 dec,
22705 cdfs,
22706 chroma_set,
22707 scans.1,
22708 2,
22709 around[2],
22710 mode,
22711 uv_predict_mode,
22712 angle_delta_uv,
22713 reach,
22714 v,
22715 cpx,
22716 cpy,
22717 chroma_side,
22718 chroma_tx,
22719 base_q_idx,
22720 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22721 None,
22722 None,
22723 smooth_neighbor_uv,
22724 fctx,
22725 )?;
22726 (u_grid, v_grid, Vec::new())
22727 } else {
22728 // lane-av1-422f: the one unit is a RECT filling the plane
22729 // block -- the square-shaped [`read_plane`] cannot express
22730 // it, so both planes go through [`read_rect_chroma_unit`]
22731 // (U, then V, the same order the square arm reads). The
22732 // chroma context reads per chroma 4-px cell (see
22733 // [`Neighbours::around_mi_422_chroma`]).
22734 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
22735 if let Some((ub, _)) = &palette_uv_bufs {
22736 set_palette_pred(ub.clone(), fctx);
22737 }
22738 let u_grid = read_rect_chroma_unit(
22739 dec,
22740 cdfs,
22741 chroma_set,
22742 scans.1,
22743 chroma_tx,
22744 chroma_tx_h,
22745 1,
22746 chroma_around[1],
22747 uv_predict_mode,
22748 angle_delta_uv,
22749 reach,
22750 u,
22751 cpx,
22752 cpy,
22753 base_q_idx,
22754 None,
22755 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22756 smooth_neighbor_uv,
22757 fctx,
22758 )?;
22759 if let Some((_, vb)) = &palette_uv_bufs {
22760 set_palette_pred(vb.clone(), fctx);
22761 }
22762 let v_grid = read_rect_chroma_unit(
22763 dec,
22764 cdfs,
22765 chroma_set,
22766 scans.1,
22767 chroma_tx,
22768 chroma_tx_h,
22769 2,
22770 chroma_around[2],
22771 uv_predict_mode,
22772 angle_delta_uv,
22773 reach,
22774 v,
22775 cpx,
22776 cpy,
22777 base_q_idx,
22778 None,
22779 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22780 smooth_neighbor_uv,
22781 fctx,
22782 )?;
22783 (u_grid, v_grid, Vec::new())
22784 }
22785 } else {
22786 let chroma_ctx_offset = Some(3);
22787 let mut u_pass: Vec<Grid> = Vec::new();
22788 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22789 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22790 for plane_pass in 1..=2usize {
22791 let mut pass_idx = 0usize;
22792 for cu_row in 0..cn_rows {
22793 for cu_col in 0..cn_cols {
22794 let cu_mi = (
22795 mi_r + cu_row * (luma_span_y / MI),
22796 mi_c + cu_col * (luma_span_x / MI),
22797 );
22798 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22799 // lane-av1-422f: chroma-only loop; per-chroma-cell
22800 // above votes (see [`Neighbours::around_mi_422_chroma`]).
22801 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
22802 } else {
22803 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
22804 };
22805 let cu_reach = tu_reach_rect(
22806 side,
22807 side,
22808 cu_col * luma_span_x,
22809 cu_row * luma_span_y,
22810 luma_span_x,
22811 luma_span_y,
22812 reach,
22813 px,
22814 py,
22815 y.width,
22816 y.height,
22817 fctx,
22818 );
22819 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22820 if let Some((ub, vb)) = &palette_uv_bufs {
22821 let pbuf = if plane_pass == 1 { ub } else { vb };
22822 set_palette_pred(
22823 palette_window(
22824 pbuf,
22825 chroma_side,
22826 cu_col * chroma_tx,
22827 cu_row * chroma_tx_h,
22828 chroma_tx,
22829 chroma_tx_h,
22830 ),
22831 fctx,
22832 );
22833 }
22834 let buf: &mut PlaneBuf<'static> =
22835 if plane_pass == 1 { &mut *u } else { &mut *v };
22836 let cu_grid = read_plane(
22837 dec,
22838 cdfs,
22839 chroma_set,
22840 scans.1,
22841 plane_pass,
22842 cu_around[plane_pass],
22843 mode,
22844 uv_predict_mode,
22845 angle_delta_uv,
22846 cu_reach,
22847 buf,
22848 cu_x,
22849 cu_y,
22850 chroma_tx,
22851 chroma_tx,
22852 base_q_idx,
22853 alpha
22854 .zip(ac)
22855 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
22856 None,
22857 chroma_ctx_offset,
22858 smooth_neighbor_uv,
22859 fctx,
22860 )?;
22861 hit!(CHROMA_SPLIT_TX_HITS);
22862 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22863 hit!(CHROMA422_SQUARE_HITS);
22864 }
22865 // Immediately, so the next unit of this block reads this
22866 // one's coefficient context. `record` below stamps one
22867 // chroma state across the whole block; the replay after
22868 // it puts the per-unit state back.
22869 neighbours.record_mi_chroma(
22870 cu_mi,
22871 luma_span_x,
22872 luma_span_y,
22873 plane_pass,
22874 &cu_grid,
22875 );
22876 if plane_pass == 1 {
22877 u_pass.push(cu_grid);
22878 } else {
22879 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22880 units.push((
22881 cu_mi,
22882 luma_span_x,
22883 luma_span_y,
22884 u_grid.clone(),
22885 cu_grid.clone(),
22886 ));
22887 last_grids = [u_grid, cu_grid];
22888 }
22889 pass_idx += 1;
22890 }
22891 }
22892 }
22893 (last_grids[0].clone(), last_grids[1].clone(), units)
22894 };
22895 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22896 neighbours.record(
22897 at,
22898 side,
22899 mode,
22900 uv_predict_mode,
22901 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22902 );
22903 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
22904 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
22905 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
22906 }
22907 } else {
22908 // Several luma transform units, raster order (spec
22909 // `transform_block`'s loop): the block's resolved transform is
22910 // genuinely smaller than its own side, so each tile of it predicts
22911 // and codes independently, its own context read fresh off whatever
22912 // the earlier tiles in this same block already wrote -- the same
22913 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
22914 let n_axis = side / logical_tx;
22915 // lane-av1-422f: unit width/height per axis, like walk 2 above --
22916 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
22917 // chunk, the whole plane block.
22918 let cn_cols = (chroma_side / chroma_tx).max(1);
22919 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22920 let luma_span_x = chroma_tx << ss_x(fctx);
22921 let luma_span_y = chroma_tx_h << ss_y(fctx);
22922 // libaom's transform-block loop is over 64x64 luma "mu" chunks
22923 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
22924 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
22925 // before moving to the next one. Below 128 a block is a single chunk,
22926 // so this is byte-for-byte the all-luma-then-all-chroma order that has
22927 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
22928 // and reading all four luma units first desyncs the tile at the second
22929 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
22930 let nchunk = (side / 64).max(1);
22931 // `cn > 1` means the uv plane block is larger than the uv transform,
22932 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
22933 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
22934 let tpc = (n_axis / nchunk).max(1);
22935 let cpc_rows = (cn_rows / nchunk).max(1);
22936 let cpc_cols = (cn_cols / nchunk).max(1);
22937 // The block's luma transform units, raster order inside each mu
22938 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
22939 // tree's own leaf list -- mixed sizes included, exactly what libaom's
22940 // `decode_token_recon_block` token loop reconstructs (one
22941 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
22942 // while every other block's list is the uniform `logical_tx` grid
22943 // this loop has always walked, generated here in the same order.
22944 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
22945 if let Some(leaves) = &intrabc_leaves {
22946 for &(lr, lc, tw, _th) in leaves {
22947 let (off_y, off_x) = (lr * MI, lc * MI);
22948 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
22949 }
22950 } else {
22951 for tu_row in 0..n_axis {
22952 for tu_col in 0..n_axis {
22953 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
22954 tu_row * logical_tx,
22955 tu_col * logical_tx,
22956 logical_tx,
22957 ));
22958 }
22959 }
22960 }
22961 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22962 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22963 for ch_row in 0..nchunk {
22964 for ch_col in 0..nchunk {
22965 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
22966 // type of the co-located luma position (`av1_get_tx_type`,
22967 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
22968 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
22969 // luma unit covering it). Inside a mu chunk that is the chunk's
22970 // FIRST luma unit in raster order (the chunk origin is always the
22971 // first leaf's own origin). Captured right after that unit's read;
22972 // the single-TU arm below does the same for a whole-block unit.
22973 let mut first_leaf_tx: Option<TxType> = None;
22974 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
22975 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
22976 let tu_px = px + tu_off_x;
22977 let tu_py = py + tu_off_y;
22978 // Same libaom clip as `decode_rect_split`'s loop above; a
22979 // square block only hangs off the frame when the frame's mi
22980 // dimensions are odd at the block's own level.
22981 if tu_px >= y.true_width || tu_py >= y.true_height {
22982 continue;
22983 }
22984 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
22985 // A transform unit inside a block is NOT a block at that
22986 // position (lane-palette2 r12): `Reach::of` granted the
22987 // top-right 8x8 unit of a 16x16 D203 block bottom-left
22988 // pixels libaom refuses outright (`col_off > 0`), which is
22989 // the diagonal wedge seed 46 reconstructed wrong.
22990 let tu_reach = tu_reach(
22991 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
22992 fctx,
22993 );
22994 // This transform unit's own bsize (`tu_tx`) is smaller
22995 // than the block it sits in (`side`), so `txb_skip_ctx` is
22996 // the neighbour-magnitude table, not the lone-TU 0 (spec
22997 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
22998 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
22999 // An intrabc unit's CDF set and scan follow the unit's OWN
23000 // resolved size (`get_txsize_entropy_ctx` /
23001 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
23002 // uniform grid's precomputed pair already matches because
23003 // `tu_tx == logical_tx` there.
23004 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
23005 (
23006 inter_txbset_for(tu_tx, reduced_tx_set),
23007 scan_for(
23008 if tu_tx == 64 { 32 } else { tu_tx },
23009 scan32,
23010 scan16,
23011 scan8,
23012 scan4,
23013 ),
23014 )
23015 } else {
23016 (luma_set, luma_scan)
23017 };
23018 if let Some(buf) = &palette_y_buf {
23019 hit!(PALETTE_SPLIT_TX_HITS);
23020 let mut window = vec![0u16; tu_tx * tu_tx];
23021 for row in 0..tu_tx {
23022 let src = (tu_off_y + row) * side + tu_off_x;
23023 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
23024 }
23025 set_palette_pred(window, fctx);
23026 }
23027 let tu_grid = read_plane(
23028 dec,
23029 cdfs,
23030 tu_set,
23031 tu_scan,
23032 0,
23033 tu_around,
23034 mode,
23035 mode,
23036 angle_delta_y,
23037 tu_reach,
23038 y,
23039 tu_px,
23040 tu_py,
23041 tu_tx,
23042 // The unit's own COEFFICIENT grid, half its side at
23043 // TX_64X64 (a 64-point transform codes nothing past 32);
23044 // identical to `tu_tx` at every smaller size
23045 // (lane-sb128b r1).
23046 if tu_tx == 64 { 32 } else { tu_tx },
23047 base_q_idx,
23048 None,
23049 filter_intra,
23050 Some(tu_skip_ctx),
23051 smooth_neighbor,
23052 fctx,
23053 )?;
23054 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23055 eprintln!(
23056 "TRACE tu_bitpos mi=({},{}) tell={}",
23057 tu_mi.0,
23058 tu_mi.1,
23059 dec.debug_bitpos()
23060 );
23061 }
23062 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
23063 if first_leaf_tx.is_none() {
23064 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
23065 }
23066 }
23067 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
23068 // this still runs after every luma unit of the block.
23069 let ac = alpha.map(|_| cfl_src(px, py, side));
23070 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
23071 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
23072 // branch sets before its own chroma reads.
23073 if intrabc_dv.is_some() {
23074 if let Some(t) = first_leaf_tx {
23075 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
23076 }
23077 }
23078 // The block's uv plane block is `chroma_side` across but its uv
23079 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
23080 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
23081 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
23082 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
23083 // FOUR units (lane-sb128b r2) -- one per mu chunk.
23084 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
23085 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
23086 // the chunk, then every V unit. At one unit per plane per chunk --
23087 // every non-lossless case this decoder reaches -- that is the same
23088 // symbol order as the interleaved pair this loop used to read; a
23089 // lossless frame's 4x4 chroma units are the case where it differs
23090 // (lane-lossless2).
23091 let mut u_pass: Vec<Grid> = Vec::new();
23092 for plane_pass in 1..=2usize {
23093 let mut pass_idx = 0usize;
23094 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
23095 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
23096 // libaom `decode_reconstruct_tx`'s frame-edge clip
23097 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
23098 // >= max_blocks_wide` returns before ANY symbol is read): a
23099 // transform unit whose 4x4 origin sits outside the frame's mi
23100 // grid is not coded at all. The luma loop above carries the
23101 // same clip; its absence here read `txb_skip` (+coeffs) for
23102 // chroma units libaom never wrote -- the lossless 64x64 block
23103 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
23104 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
23105 // eight (lane-av1-loss64; 48 chroma units per plane in
23106 // aomdec's EC_COEFF census vs the 64 this loop read).
23107 // `max_block_wide/high` (av1_common_int.h:1565): the plane
23108 // block's pixel span (4:2:0 halves the luma span, clamped to
23109 // 4 by `set_plane_n4`) plus the negative overhang
23110 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
23111 // units.
23112 let span_mi = side / MI;
23113 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
23114 - mi_c as i32
23115 - span_mi as i32;
23116 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
23117 - mi_r as i32
23118 - span_mi as i32;
23119 // `max_block_wide/high` in chroma pixels: the plane block's
23120 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
23121 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
23122 // block's coded units and desynced the tile) plus the
23123 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
23124 // chroma-px scale is `MI >> ss` per mi.
23125 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
23126 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
23127 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
23128 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
23129 // lane-av1-422f: the shared halved formula in the `else` counts
23130 // the plane span in 4-px units through the 2-px-per-mi
23131 // subsampled height, which a 4:2:2 plane does not have (ss_y
23132 // 0) -- its span is the full luma mi count, so a keyed
23133 // formula clips the same units libaom's `max_block_high`
23134 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
23135 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
23136 // pre-ss form spelled).
23137 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
23138 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
23139 } else {
23140 ((plane_px + over_h_px) >> 2).max(0) as usize
23141 };
23142 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
23143 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
23144 hit!(CHROMA_EDGE_TU_CLIP_HITS);
23145 continue;
23146 }
23147 // The chroma context arrays are indexed in LUMA mi, so this
23148 // unit's anchor is its own luma quadrant (lane-av1-422b: the
23149 // quadrant spans `chroma_tx << ss_x` luma px wide by
23150 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
23151 // one unit's quadrant is the whole block).
23152 let cu_mi = (
23153 mi_r + cu_row * (luma_span_y / MI),
23154 mi_c + cu_col * (luma_span_x / MI),
23155 );
23156 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
23157 // lane-av1-422f: chroma-only loop; per-chroma-cell above
23158 // votes (see [`Neighbours::around_mi_422_chroma`]).
23159 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
23160 } else {
23161 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
23162 };
23163 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
23164 reach
23165 } else {
23166 tu_reach_rect(
23167 side,
23168 side,
23169 cu_col * luma_span_x,
23170 cu_row * luma_span_y,
23171 luma_span_x,
23172 luma_span_y,
23173 reach,
23174 px,
23175 py,
23176 y.width,
23177 y.height,
23178 fctx,
23179 )
23180 };
23181 let (cu_x, cu_y) =
23182 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
23183 if let Some((ub, vb)) = &palette_uv_bufs {
23184 let pbuf = if plane_pass == 1 { ub } else { vb };
23185 set_palette_pred(
23186 palette_window(
23187 pbuf,
23188 chroma_side,
23189 cu_col * chroma_tx,
23190 cu_row * chroma_tx_h,
23191 chroma_tx,
23192 chroma_tx_h,
23193 ),
23194 fctx,
23195 );
23196 }
23197 let buf: &mut PlaneBuf<'static> =
23198 if plane_pass == 1 { &mut *u } else { &mut *v };
23199 let cu_grid = if chroma_tx == chroma_tx_h {
23200 read_plane(
23201 dec,
23202 cdfs,
23203 chroma_set,
23204 scans.1,
23205 plane_pass,
23206 cu_around[plane_pass],
23207 mode,
23208 uv_predict_mode,
23209 angle_delta_uv,
23210 cu_reach,
23211 buf,
23212 cu_x,
23213 cu_y,
23214 chroma_tx,
23215 chroma_tx,
23216 base_q_idx,
23217 alpha.zip(ac).map(|((au, av), ac)| {
23218 (if plane_pass == 1 { au } else { av }, ac)
23219 }),
23220 None,
23221 chroma_ctx_offset,
23222 smooth_neighbor_uv,
23223 fctx,
23224 )?
23225 } else {
23226 // lane-av1-422f: the whole plane block as one rect unit;
23227 // `chroma_ctx_offset` is `None` there (the unit covers
23228 // the plane block, so the offset-7 skip rows are right).
23229 read_rect_chroma_unit(
23230 dec,
23231 cdfs,
23232 chroma_set,
23233 scans.1,
23234 chroma_tx,
23235 chroma_tx_h,
23236 plane_pass,
23237 cu_around[plane_pass],
23238 uv_predict_mode,
23239 angle_delta_uv,
23240 cu_reach,
23241 buf,
23242 cu_x,
23243 cu_y,
23244 base_q_idx,
23245 None,
23246 alpha.zip(ac).map(|((au, av), ac)| {
23247 (if plane_pass == 1 { au } else { av }, ac)
23248 }),
23249 smooth_neighbor_uv,
23250 fctx,
23251 )?
23252 };
23253 if cn_rows * cn_cols > 1 {
23254 hit!(CHROMA_SPLIT_TX_HITS);
23255 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
23256 hit!(CHROMA422_SQUARE_HITS);
23257 }
23258 // Immediately, so the NEXT unit of this same block reads
23259 // this one's coefficient context (libaom's chroma
23260 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
23261 // 1 from this left neighbour -- measured against aomdec).
23262 // The same writes are replayed after `record_split_luma`
23263 // below, which would otherwise clobber them whole-block.
23264 neighbours.record_mi_chroma(
23265 cu_mi,
23266 luma_span_x,
23267 luma_span_y,
23268 plane_pass,
23269 &cu_grid,
23270 );
23271 }
23272 if plane_pass == 1 {
23273 u_pass.push(cu_grid);
23274 } else {
23275 let u_grid =
23276 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
23277 if cn_rows * cn_cols > 1 {
23278 units.push((
23279 cu_mi,
23280 luma_span_x,
23281 luma_span_y,
23282 u_grid.clone(),
23283 cu_grid.clone(),
23284 ));
23285 }
23286 last_grids = [u_grid, cu_grid];
23287 }
23288 pass_idx += 1;
23289 }
23290 }
23291 }
23292 }
23293 if intrabc_dv.is_some() {
23294 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23295 }
23296 }
23297 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
23298 // context write; at `cn > 1` the per-unit writes above are what the
23299 // next block reads, so they run after this (last writer wins).
23300 neighbours.record_split_luma(
23301 at,
23302 side,
23303 mode,
23304 uv_predict_mode,
23305 [&last_grids[0], &last_grids[1]],
23306 );
23307 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
23308 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
23309 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
23310 }
23311 }
23312 // Unconditional, `size == 0` for a non-palette block: clears any stale
23313 // neighbour palette state the same way [`Neighbours::record`] always
23314 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
23315 // (the split-luma-TU branch above always refuses before reaching here
23316 // when `palette_y` is `Some`, so it is never live for that branch).
23317 let (py_size, py_colors) = palette_y
23318 .as_ref()
23319 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
23320 neighbours.record_palette_y(at, side, py_size, py_colors);
23321 let (puv_size, puv_colors) = palette_uv
23322 .as_ref()
23323 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
23324 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
23325 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
23326 neighbours.fill_lf_grid(
23327 (r * (SUB / MI), c * (SUB / MI)),
23328 side / MI,
23329 logical_tx as u8,
23330 0,
23331 fctx,
23332 );
23333 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
23334 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
23335 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
23336 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
23337 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
23338 // intrabc block publish its BLOCK size instead, intrabc being the only
23339 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
23340 // stays the authority wherever one can appear; with `allow_intrabc` unset
23341 // it writes exactly what the grid already did.
23342 if allow_intrabc {
23343 set_txfm_ctxs(
23344 neighbours,
23345 (mi_r, mi_c),
23346 logical_tx,
23347 side / MI,
23348 side / MI,
23349 skip && intrabc_dv.is_some(),
23350 );
23351 }
23352 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
23353 Ok(())
23354}
23355
23356thread_local! {
23357 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
23358 /// root's HORZ arm, and 64x128 ones at its VERT arm.
23359 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23360 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23361 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
23362 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
23363 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
23364 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
23365 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
23366 /// inter frame) -- (128x64, 64x128).
23367 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
23368 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
23369 /// handed back var-tx leaves, so the per-transform-unit luma publication
23370 /// loop never ran and the block has to clear its own luma coefficient
23371 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
23372 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
23373 /// non-vacuous.
23374 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23375 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
23376 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
23377 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
23378 /// shape non-vacuous -- a stream that never codes one reads 0.
23379 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23380 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
23381 /// intra block re-stamped by the end-of-block replay
23382 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
23383 /// walk published, so every unit replays its own state after it). A
23384 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
23385 /// of them, so this reads 0 on any stream that never codes one -- the
23386 /// non-vacuity anchor for the replay's own gate.
23387 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23388 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
23389 /// height differs from the unit's own LUMA-MI height -- the signature of the
23390 /// width passed to both axes (`luma_span` where the in-loop stamp used
23391 /// `luma_span_h`). Zero on every stream this decoder admits: both
23392 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
23393 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
23394 /// at the sequence header (`stream::decode_frame`), so the arm is
23395 /// defensive until that format is ported. The counter turns a future
23396 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
23397 /// of silent mi-state corruption.
23398 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23399}
23400
23401/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
23402pub fn skip_vartx_luma_reset_hits() -> usize {
23403 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
23404}
23405
23406/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
23407pub(crate) fn intra128_lossless_hits() -> usize {
23408 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
23409}
23410
23411/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
23412pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
23413 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
23414}
23415
23416/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
23417/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
23418pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
23419 (
23420 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
23421 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
23422 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
23423 )
23424}
23425
23426/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
23427/// `decode_block_128rect`'s end-of-block replay) and
23428/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
23429/// not the unit's own), for a gate's own before/after delta.
23430pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
23431 (
23432 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
23433 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
23434 )
23435}
23436
23437/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
23438/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
23439/// `decode_inter_block`'s own rect path).
23440///
23441/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
23442/// transform unit, with the 128-specific geometry:
23443/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
23444/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
23445/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
23446/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
23447/// same CDF a 64x64 square block reads).
23448/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
23449/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
23450/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
23451/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
23452/// a chunk before moving to the next (the interleave lane-sb128b r3
23453/// measured at the 128x128 NONE root).
23454/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
23455/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
23456/// No CfL, no filter intra (both cap at 32x32) and no palette
23457/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
23458/// reader's own size gates already say so, and the guard below is defensive.
23459///
23460/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
23461/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
23462/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
23463/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
23464/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
23465/// units, plane-major inside each 64x64 mu chunk exactly as
23466/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
23467/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
23468/// this lane closed); the geometry and the unit walks below are normalized on
23469/// `lossless_frame`.
23470#[allow(clippy::too_many_arguments)]
23471fn decode_block_128rect(
23472 dec: &mut SymbolDecoder,
23473 cdfs: &mut Cdfs,
23474 neighbours: &mut Neighbours,
23475 at: (usize, usize),
23476 bw: usize,
23477 bh: usize,
23478 y: &mut PlaneBuf<'static>,
23479 u: &mut PlaneBuf<'static>,
23480 v: &mut PlaneBuf<'static>,
23481 base_q_idx: u8,
23482 enable_filter_intra: bool,
23483 allow_screen_content_tools: bool,
23484 tx_select: bool,
23485 reduced_tx_set: bool,
23486 fctx: &crate::decode::FrameCtx,
23487) -> Result<()> {
23488 let (r, c) = at;
23489 let (px, py) = (c * SUB, r * SUB);
23490 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
23491 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
23492 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
23493 let palette_uv_cache = neighbours.palette_uv_cache(at);
23494 let (
23495 skip,
23496 mode,
23497 angle_delta_y,
23498 uv_mode,
23499 angle_delta_uv,
23500 alpha,
23501 filter_intra,
23502 palette_y,
23503 palette_uv,
23504 intrabc,
23505 ) = read_intra_mode_rect(
23506 dec,
23507 cdfs,
23508 nb_above_mode,
23509 nb_left_mode,
23510 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
23511 // 13-symbol no-CFL CDF here, never the 14-symbol one.
23512 false,
23513 true,
23514 bw,
23515 bh,
23516 enable_filter_intra,
23517 neighbours.skip_txfm_ctx(mi_r, mi_c),
23518 allow_screen_content_tools,
23519 Some((palette_ctx, &palette_cache)),
23520 &palette_uv_cache,
23521 mi_r,
23522 mi_c,
23523 fctx,
23524 )?;
23525 if let Some((dv_row, dv_col)) = intrabc {
23526 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
23527 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
23528 // from this frame's own reconstruction and runs the INTER residual
23529 // walk (`decode_token_recon_block`'s else arm) over it.
23530 return decode_intrabc_128rect(
23531 dec,
23532 cdfs,
23533 neighbours,
23534 (mi_r, mi_c),
23535 (bw, bh),
23536 skip,
23537 (dv_row, dv_col),
23538 y,
23539 u,
23540 v,
23541 base_q_idx,
23542 fctx,
23543 );
23544 }
23545 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
23546 return Err(unsupported(
23547 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
23548 their size gates caps at 64x64 or below, so none of these symbols exists there)",
23549 ));
23550 }
23551 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23552 DC_PRED
23553 } else {
23554 uv_mode
23555 };
23556 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
23557 if smooth_neighbor {
23558 hit!(SMOOTH_LUMA_HITS);
23559 }
23560 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
23561 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
23562 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
23563 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
23564 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
23565 // before the symbol is even considered (`decodeframe.c:141`) and
23566 // `read_tx_size` returns `TX_4X4` before it looks at anything
23567 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
23568 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
23569 let lossless_frame = lossless(fctx);
23570 let in_inter = fctx
23571 .intra_in_inter_mode
23572 .with(std::cell::Cell::get)
23573 .is_some();
23574 let depth = if tx_select && !lossless_frame {
23575 // lane-inter128intra r1: `get_tx_size_context` compares the bands
23576 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
23577 // TX_64X64 for every 128-axis block, hence the `min(64)`.
23578 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
23579 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
23580 } else {
23581 0
23582 };
23583 if depth != 0 {
23584 hit!(TX_DEPTH_HITS);
23585 }
23586 hit_do! {
23587 INTRA_SB128_DEPTH_HITS.with(|c| {
23588 let mut h = c.get();
23589 h[depth.min(2)] += 1;
23590 c.set(h);
23591 });
23592 }
23593 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
23594 if lossless_frame {
23595 hit!(INTRA128_LOSSLESS_HITS);
23596 }
23597 // A 64-point transform codes nothing past its low 32 coefficients.
23598 let coeff_tx_side = logical_tx.min(32);
23599 let luma_set = if lossless_frame {
23600 TxbSet::Luma4
23601 } else {
23602 txbset_for(logical_tx, reduced_tx_set)
23603 };
23604 let luma_scan = default_scan(coeff_tx_side);
23605 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
23606 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
23607 let chroma_tx = if lossless_frame { 4 } else { 32 };
23608 let chroma_set = if lossless_frame {
23609 TxbSet::Chroma4
23610 } else {
23611 TxbSet::Chroma32
23612 };
23613 let chroma_scan = default_scan(chroma_tx);
23614 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
23615 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
23616 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
23617 let (nch_x, nch_y) = (bw / 64, bh / 64);
23618 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
23619 // `decode_token_recon_block` clips each vector's walk to
23620 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
23621 // codes nothing.
23622 let mi_cols = 2 * y.true_width.div_ceil(8);
23623 let mi_rows = 2 * y.true_height.div_ceil(8);
23624 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
23625 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
23626 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
23627 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
23628 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
23629 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
23630 debug_assert!(
23631 lossless_frame
23632 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
23633 == (
23634 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
23635 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
23636 )
23637 );
23638 let tpc = 64 / logical_tx;
23639 let zero_tu = vec![0i32; logical_tx * logical_tx];
23640 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
23641 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
23642 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
23643 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
23644 // every chunk shares this luma span (2 chroma pixels per luma unit).
23645 let luma_span = chroma_tx << ss_x(fctx);
23646 let luma_span_h = chroma_tx << ss_y(fctx);
23647 for ch_row in 0..nch_y {
23648 for ch_col in 0..nch_x {
23649 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
23650 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
23651 let tu_mi = (
23652 mi_r + tu_row * (logical_tx / MI),
23653 mi_c + tu_col * (logical_tx / MI),
23654 );
23655 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
23656 // libaom clips the transform loop to
23657 // `max_blocks_wide/high`: a unit whose top-left sample is
23658 // outside the frame is never coded.
23659 if tu_px >= y.true_width || tu_py >= y.true_height {
23660 continue;
23661 }
23662 // Edge availability of a unit INSIDE a block, with the
23663 // 128 geometry -- `has_top_right` is false for a block
23664 // whose largest side is > 64, which [`Reach::of_rect`]
23665 // already answered for the block and [`tu_reach`] carries
23666 // down to the units on its own top row.
23667 let tu_r = tu_reach(
23668 bw,
23669 bh,
23670 tu_col * logical_tx,
23671 tu_row * logical_tx,
23672 logical_tx,
23673 reach,
23674 px,
23675 py,
23676 y.width,
23677 y.height,
23678 fctx,
23679 );
23680 if skip {
23681 push_intra(
23682 0,
23683 tu_px,
23684 tu_py,
23685 logical_tx,
23686 mode,
23687 angle_delta_y,
23688 tu_r,
23689 &zero_tu,
23690 None,
23691 None,
23692 smooth_neighbor,
23693 fctx,
23694 );
23695 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
23696 continue;
23697 }
23698 // The unit is smaller than its block, so `txb_skip_ctx`
23699 // is the neighbour-magnitude table, never the lone-TU 0.
23700 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
23701 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
23702 let tu_grid = read_plane(
23703 dec,
23704 cdfs,
23705 luma_set,
23706 &luma_scan,
23707 0,
23708 tu_around,
23709 mode,
23710 mode,
23711 angle_delta_y,
23712 tu_r,
23713 y,
23714 tu_px,
23715 tu_py,
23716 logical_tx,
23717 coeff_tx_side,
23718 base_q_idx,
23719 None,
23720 None,
23721 Some(tu_skip_ctx),
23722 smooth_neighbor,
23723 fctx,
23724 )?;
23725 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
23726 }
23727 }
23728 // Transform units per axis inside this mu chunk's chroma span:
23729 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
23730 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
23731 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
23732 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
23733 // chroma plane block is 32x64 there, so the two axes' counts
23734 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
23735 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
23736 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
23737 // libaom's per-chunk `unit_width/height` (plane-mi units of the
23738 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
23739 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
23740 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
23741 let stepc = (chroma_tx / 4).max(1);
23742 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
23743 // unit of the chunk, then every V unit. At one unit per plane per
23744 // chunk (every non-lossless 128-axis block) that is the same
23745 // symbol order the interleaved pair used to read; a lossless
23746 // frame's 4x4 chroma units are where it becomes observable.
23747 for plane_pass in 1..=2usize {
23748 for ci_row in 0..cn_h {
23749 for ci_col in 0..cn {
23750 // The clamp strides are the CHUNK's chroma mi extent
23751 // per axis: 16 luma mi >> the axis's own ss.
23752 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
23753 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
23754 {
23755 continue;
23756 }
23757 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
23758 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
23759 let cu_mi = (
23760 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
23761 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
23762 );
23763 let cu_r = tu_reach_rect(
23764 bw,
23765 bh,
23766 ch_col * 64 + ci_col * luma_span,
23767 ch_row * 64 + ci_row * luma_span_h,
23768 luma_span,
23769 luma_span_h,
23770 reach,
23771 px,
23772 py,
23773 y.width,
23774 y.height,
23775 fctx,
23776 );
23777 if skip {
23778 push_intra(
23779 plane_pass,
23780 cu_x,
23781 cu_y,
23782 chroma_tx,
23783 uv_predict_mode,
23784 angle_delta_uv,
23785 cu_r,
23786 &zero_cu,
23787 None,
23788 None,
23789 smooth_neighbor_uv,
23790 fctx,
23791 );
23792 continue;
23793 }
23794 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
23795 let buf: &mut PlaneBuf<'static> =
23796 if plane_pass == 1 { &mut *u } else { &mut *v };
23797 let grid = read_plane(
23798 dec,
23799 cdfs,
23800 chroma_set,
23801 &chroma_scan,
23802 plane_pass,
23803 cu_around[plane_pass],
23804 mode,
23805 uv_predict_mode,
23806 angle_delta_uv,
23807 cu_r,
23808 buf,
23809 cu_x,
23810 cu_y,
23811 chroma_tx,
23812 chroma_tx,
23813 base_q_idx,
23814 None,
23815 None,
23816 Some(3),
23817 smooth_neighbor_uv,
23818 fctx,
23819 )?;
23820 last_grids[plane_pass - 1] = grid.clone();
23821 // Immediately, so the NEXT unit of this same block
23822 // reads this one's coefficient context; replayed after
23823 // `record_split_luma_rect` below, which would otherwise
23824 // clobber them whole-block.
23825 neighbours.record_mi_chroma(
23826 cu_mi,
23827 luma_span,
23828 luma_span_h,
23829 plane_pass,
23830 &grid,
23831 );
23832 units.push((plane_pass, cu_mi, grid));
23833 }
23834 }
23835 }
23836 if !skip {
23837 hit!(CHROMA_SPLIT_TX_HITS);
23838 }
23839 }
23840 }
23841 if skip {
23842 neighbours.record_rect(
23843 at,
23844 bw,
23845 bh,
23846 mode,
23847 uv_predict_mode,
23848 &[
23849 &ZERO_RESIDUAL[..bw * bh],
23850 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23851 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23852 ],
23853 );
23854 } else {
23855 neighbours.record_split_luma_rect(
23856 at,
23857 bw,
23858 bh,
23859 mode,
23860 uv_predict_mode,
23861 [&last_grids[0], &last_grids[1]],
23862 );
23863 // lane-av1-128rectspan: the replay must re-stamp each unit over the
23864 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
23865 // height drives `left[]` and its width `above[]`, and the walk used
23866 // the per-axis `luma_span_h`. Passing the width on both axes doubled
23867 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
23868 // rows below the block on the last unit of a 128x64/64x128 strip and
23869 // smearing a neighbour chunk's unit over its neighbour's rows.
23870 //
23871 // DEFENSIVE at the decoder's current capability set: both admitted
23872 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
23873 // (0,0)), so the two spans are equal and this line is a no-op on
23874 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
23875 // format where they differ -- is refused by name at the sequence
23876 // header, so the arm is unreachable there. It stays per-axis because
23877 // the walk it replays is per-axis, and a 4:2:2 port must not have to
23878 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
23879 // day that changes.
23880 if luma_span != luma_span_h {
23881 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
23882 }
23883 for (plane, cu_mi, grid) in &units {
23884 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
23885 hit!(SB128RECT_CHROMA_REPLAY_HITS);
23886 }
23887 }
23888 // No palette exists at this size; the unconditional stamp clears any
23889 // stale neighbour palette state, as every other block path does.
23890 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
23891 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
23892 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
23893 neighbours.fill_lf_grid_rect(
23894 (mi_r, mi_c),
23895 bw / MI,
23896 bh / MI,
23897 logical_tx as u8,
23898 logical_tx as u8,
23899 0,
23900 fctx,
23901 );
23902 if in_inter || allow_intrabc_frame(fctx) {
23903 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
23904 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
23905 // inter frame, intra ones included: an intra block stamps its
23906 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
23907 // A key frame reads those bands only when it allows intrabc
23908 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
23909 // stamps here too -- lane-av1-intrabc r3.
23910 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
23911 }
23912 if in_inter {
23913 hit_do! {
23914 INTRA128_IN_INTER_HITS.with(|c| {
23915 let mut h = c.get();
23916 h[usize::from(bw < bh)] += 1;
23917 c.set(h);
23918 });
23919 }
23920 } else if bw > bh {
23921 hit!(INTRA_SB128_HORZ_HITS);
23922 } else {
23923 hit!(INTRA_SB128_VERT_HITS);
23924 }
23925 Ok(())
23926}
23927
23928/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
23929/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
23930/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
23931/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
23932/// just-decoded mode, not the enclosing slot's stale one, is the true
23933/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
23934/// units, which is what its coefficient context (finer than [`SUB`]) is read
23935/// at. Returns the mode this leaf decoded, for the caller's own
23936/// `prev_leaf`/final mode-writeback bookkeeping.
23937#[allow(clippy::too_many_arguments)]
23938/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
23939/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
23940/// `above_mode[col]`, and its true above neighbour is the mi directly above
23941/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
23942/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
23943/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
23944/// (bottom-right) into both, as this path did, is right only when all four
23945/// leaves happen to share a mode. `done` may be short at the true frame edge
23946/// (the straddle caller filters positions off the frame), so each side falls
23947/// back to the last leaf actually decoded.
23948fn write_back_split_modes(
23949 neighbours: &mut Neighbours,
23950 done: &[((usize, usize), usize)],
23951 parent_mi: (usize, usize),
23952 slot: (usize, usize),
23953) {
23954 let (sr, sc) = slot;
23955 let Some(&(_, last)) = done.last() else {
23956 return;
23957 };
23958 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
23959 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
23960 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
23961}
23962
23963fn decode_leaf8(
23964 dec: &mut SymbolDecoder,
23965 cdfs: &mut Cdfs,
23966 neighbours: &mut Neighbours,
23967 outer_at: (usize, usize),
23968 leaf_mi: (usize, usize),
23969 scans: (&[u16], &[u16]),
23970 prev_leaf: Option<((usize, usize), usize)>,
23971 y: &mut PlaneBuf<'static>,
23972 u: &mut PlaneBuf<'static>,
23973 v: &mut PlaneBuf<'static>,
23974 base_q_idx: u8,
23975 enable_filter_intra: bool,
23976 allow_screen_content_tools: bool,
23977 allow_intrabc: bool,
23978 tx_select: bool,
23979 reduced_tx_set: bool,
23980 fctx: &crate::decode::FrameCtx,
23981) -> Result<usize> {
23982 let (r, c) = outer_at;
23983 // lane-modectx r1: the group's own availability-correct fallback pair, not
23984 // the raw coarse bands (which leak across a tile edge -- see
23985 // `modes_above_left`).
23986 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
23987 if let Some(((pr, pc), pmode)) = prev_leaf {
23988 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
23989 above_mode = pmode;
23990 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
23991 left_mode = pmode;
23992 }
23993 }
23994 // The mi-exact neighbour wins over both the coarse 16x16 slot and
23995 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
23996 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
23997 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
23998 // lane-rectsplitx r2 swept this arm into
23999 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
24000 // "no neighbour" at a tile edge, where the coarse cell holds the block
24001 // above/left of it inside the same 16x16.
24002 let (above_mode, left_mode) =
24003 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
24004 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
24005 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
24006 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
24007 // this leaf's `smooth_neighbor` is built from -- passing `false` here
24008 // filtered a directional chroma block's edge at the wrong strength
24009 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
24010 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
24011 // with the coarse [`SUB`] slot as the fallback when no block recorded
24012 // that exact mi cell.
24013 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
24014 if smooth_neighbor {
24015 hit!(SMOOTH_LUMA_HITS);
24016 }
24017 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
24018 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
24019 // `decode_block` caller at 16x16 and up.
24020 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
24021 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
24022 // `read_palette_mode_info`), at its REAL mi position -- passing
24023 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
24024 // moment a real 8x8 palette block fired, which is where

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