forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

decode.rs24328 lines, 2.4 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.
1607#[allow(clippy::too_many_arguments)]
1608fn tu_reach_rect(
1609 bw: usize,
1610 bh: usize,
1611 col_off: usize,
1612 row_off: usize,
1613 tx_w: usize,
1614 tx_h: usize,
1615 block: Reach,
1616 px: usize,
1617 py: usize,
1618 width: usize,
1619 height: usize,
1620 fctx: &crate::decode::FrameCtx,
1621) -> Reach {
1622 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);
1623 if tx_w == tx_h {
1624 let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx);
1625 if fixed != standalone {
1626 hit!(SPLIT_TU_REACH_FIX_HITS);
1627 }
1628 }
1629 fixed
1630}
1631
1632// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1633// across every call on the current thread -- lane-chroma r3's own before/after
1634// counter, proving a stream actually exercised chroma's smooth/paeth
1635// predictor (the previously-refused round-2 gap) rather than every block
1636// landing on DC/CFL/directional.
1637thread_local! {
1638 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1639 const { std::cell::Cell::new(0) };
1640}
1641
1642/// Current value of [`SMOOTH_UV_HITS`].
1643#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1644pub(crate) fn smooth_uv_hits() -> usize {
1645 SMOOTH_UV_HITS.with(|c| c.get())
1646}
1647
1648// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1649// full superblock walk over, across every call on the current thread --
1650// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1651// multi-tile stream must prove more than one tile actually fired, not just
1652// that the stream carried tile_info.cols > 1.
1653thread_local! {
1654 static TILE_HITS: std::cell::Cell<usize> =
1655 const { std::cell::Cell::new(0) };
1656}
1657/// Current value of [`TILE_HITS`].
1658#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1659pub(crate) fn tile_hits() -> usize {
1660 TILE_HITS.with(|c| c.get())
1661}
1662
1663// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1664// selected for filtering, across every call on the current thread -- the same
1665// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1666// exercised `apply_deblock` rather than every edge landing on level 0.
1667thread_local! {
1668 static DEBLOCK_HITS: std::cell::Cell<usize> =
1669 const { std::cell::Cell::new(0) };
1670}
1671/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1672/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1673/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1674static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1675
1676/// Current value of [`DEBLOCK_HITS`].
1677#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1678pub(crate) fn deblock_hits() -> usize {
1679 DEBLOCK_HITS.with(|c| c.get())
1680}
1681
1682// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1683// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1684// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1685// stream built with `--enable-onesided-comp=1` really exercised the
1686// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1687thread_local! {
1688 static UNI_COMP_HITS: std::cell::Cell<usize> =
1689 const { std::cell::Cell::new(0) };
1690}
1691
1692/// Current value of [`UNI_COMP_HITS`].
1693#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1694pub(crate) fn uni_comp_hits() -> usize {
1695 UNI_COMP_HITS.with(|c| c.get())
1696}
1697
1698// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1699// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1700// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1701// blend and not only the wedge arm.
1702thread_local! {
1703 static DIFFWTD_HITS: std::cell::Cell<usize> =
1704 const { std::cell::Cell::new(0) };
1705}
1706
1707/// Current value of [`DIFFWTD_HITS`].
1708#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1709pub(crate) fn diffwtd_hits() -> usize {
1710 DIFFWTD_HITS.with(|c| c.get())
1711}
1712
1713// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1714// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1715// this decoder's square inter path reaches), so no `compound_type` symbol is
1716// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1717// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1718thread_local! {
1719 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1720 const { std::cell::Cell::new(0) };
1721}
1722
1723/// Current value of [`DIFFWTD_INFERRED_HITS`].
1724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1725pub(crate) fn diffwtd_inferred_hits() -> usize {
1726 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1727}
1728
1729// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1730// with `show_frame == 0`, output later by a `show_existing_frame` header
1731// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1732// `stream::decode_stream`, which is where the frame header is consumed; the
1733// gate's proof that the on-value really reached the bitstream rather than
1734// being dropped by the rate control.
1735thread_local! {
1736 static FWD_KF_HITS: std::cell::Cell<usize> =
1737 const { std::cell::Cell::new(0) };
1738}
1739
1740/// Current value of [`FWD_KF_HITS`].
1741#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1742pub(crate) fn fwd_kf_hits() -> usize {
1743 FWD_KF_HITS.with(|c| c.get())
1744}
1745
1746/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1747pub(crate) fn note_fwd_kf() {
1748 hit!(FWD_KF_HITS);
1749}
1750
1751// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1752// the block's own side, across every call on the current thread -- the same
1753// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1754// actually exercised a *split* transform under `TxMode::Select` rather than
1755// every block coincidentally resolving `depth=0` (indistinguishable from
1756// `TxMode::Largest` pixel-wise).
1757thread_local! {
1758 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1759 const { std::cell::Cell::new(0) };
1760}
1761
1762// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1763// transform smaller than their own side (`tx_depth != 0`) while coding a
1764// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1765// only exercises with aomenc's tx-size search left ON (its default), which
1766// every older recipe in this file pins off. Counted at the block, so a stream
1767// where RD happened to give every split-transform block a DC chroma mode
1768// reads as zero rather than silently passing for free.
1769thread_local! {
1770 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1771 const { std::cell::Cell::new(0) };
1772}
1773
1774/// Current value of [`SQ_CHROMA_TX_HITS`].
1775#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1776pub(crate) fn sq_chroma_tx_hits() -> usize {
1777 SQ_CHROMA_TX_HITS.with(|c| c.get())
1778}
1779
1780/// Current value of [`TX_DEPTH_HITS`].
1781#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1782pub(crate) fn tx_depth_hits() -> usize {
1783 TX_DEPTH_HITS.with(|c| c.get())
1784}
1785
1786// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1787// read, and how many of those actually took the split, on the current thread
1788// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1789// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1790// coincidentally coding one whole-block transform.
1791thread_local! {
1792 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1793 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1794 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1795 // strips coded one whole-block rect transform unit, and how many split
1796 // their rect max transform into square sub-transforms.
1797 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1798 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1799 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1800 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1801 // truncated low-32 corner.
1802 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1803 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1804 // inter strip, `[32x8, 8x32]`.
1805 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1806 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1807 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1808 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1809 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1810 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1811 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1812 // frame -- 16x8 and 8x16 inter leaves.
1813 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1814 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1815 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1816 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1817 // `decode_inter_block` already carries forty parameters and both are
1818 // frame-constant.
1819 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1820 // frame-constant like the two above and stashed the same way -- an intra
1821 // block inside an inter frame reads `use_filter_intra` under it.
1822}
1823
1824/// Current value of [`TXFM_SPLIT_READS`].
1825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1826pub(crate) fn txfm_split_reads() -> usize {
1827 TXFM_SPLIT_READS.with(|c| c.get())
1828}
1829
1830/// Current value of [`TXFM_SPLIT_HITS`].
1831#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1832pub(crate) fn txfm_split_hits() -> usize {
1833 TXFM_SPLIT_HITS.with(|c| c.get())
1834}
1835
1836/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1838pub(crate) fn inter_leaf16_horz_hits() -> usize {
1839 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1840}
1841
1842/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1844pub(crate) fn inter_leaf16_vert_hits() -> usize {
1845 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1846}
1847
1848/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1849pub(crate) fn rect_inter_tu_hits() -> usize {
1850 RECT_INTER_TU_HITS.with(|c| c.get())
1851}
1852
1853/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1854pub(crate) fn rect_inter_txsplit_hits() -> usize {
1855 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1856}
1857
1858/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1859pub(crate) fn rect64_inter_tu_hits() -> usize {
1860 RECT64_INTER_TU_HITS.with(|c| c.get())
1861}
1862
1863/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1864/// whole-block luma units of a 32x32-level 1:4 inter strip.
1865pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1866 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1867}
1868
1869/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1870/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1871pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1872 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1873}
1874
1875/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1876/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1877pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1878 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1879}
1880
1881/// Records one rectangular var-tx leaf.
1882fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1883 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1884 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1885 }
1886 let cell = if tw.min(th) == 4 {
1887 &VARTX_RECT_LEAF4_HITS
1888 } else {
1889 &VARTX_RECT_LEAF_HITS
1890 };
1891 cell.with(|c| {
1892 let mut h = c.get();
1893 h[usize::from(th > tw)] += 1;
1894 c.set(h);
1895 });
1896}
1897
1898/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1899/// [`ENABLE_FILTER_INTRA_INTER`].
1900pub(crate) fn set_inter_tx_mode(
1901 tx_select: bool,
1902 reduced_tx_set: bool,
1903 enable_filter_intra: bool,
1904 fctx: &crate::decode::FrameCtx,
1905) {
1906 fctx.tx_select_inter.with(|c| c.set(tx_select));
1907 fctx.intra_only.with(|c| c.set(false));
1908 fctx.tx_select_frame.with(|c| c.set(tx_select));
1909 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1910 fctx.enable_filter_intra_inter
1911 .with(|c| c.set(enable_filter_intra));
1912}
1913
1914// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1915// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1916// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1917// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1918// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1919// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1920// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1921// path above).
1922thread_local! {
1923 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1924 const { std::cell::Cell::new(0) };
1925}
1926
1927/// Current value of [`VERT_B_INTRA_HITS`].
1928#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1929pub(crate) fn vert_b_intra_hits() -> usize {
1930 VERT_B_INTRA_HITS.with(|c| c.get())
1931}
1932
1933// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1934// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1935// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1936// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1937// every arm separately so a run where aomenc's RD only picked one cannot
1938// pass as proof of four.
1939thread_local! {
1940 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1941}
1942
1943// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1944thread_local! {
1945 /// 4x4 transform units decoded inside an 8x8 square of a
1946 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1947 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1948 /// a real `--enable-tx-size-search=1` stream reaches it.
1949 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1950}
1951
1952#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1953pub(crate) fn vert_ab_tx4_hits() -> usize {
1954 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1955}
1956
1957#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1958pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1959 AB16_HITS.with(std::cell::Cell::get)
1960}
1961
1962fn bump_ab16(arm: usize) {
1963 hit_do! {
1964 AB16_HITS.with(|c| {
1965 let mut v = c.get();
1966 v[arm] += 1;
1967 c.set(v);
1968 });
1969 }
1970}
1971
1972// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1973// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1974// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1975// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1976// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1977// superblock's z-order recursion, not raster mi position).
1978thread_local! {
1979 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1980 const { std::cell::Cell::new(0) };
1981}
1982
1983/// Current value of [`HORZ_VERT_INTRA_HITS`].
1984#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1985pub(crate) fn horz_vert_intra_hits() -> usize {
1986 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1987}
1988
1989// How many blocks were decoded as a frame-edge rect strip -- the single
1990// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1991// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1992// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1993// paths share the counter.
1994thread_local! {
1995 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1996 const { std::cell::Cell::new(0) };
1997}
1998
1999/// Current value of [`EDGE_RECT_STRIP_HITS`].
2000#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
2001pub(crate) fn edge_rect_strip_hits() -> usize {
2002 EDGE_RECT_STRIP_HITS.with(|c| c.get())
2003}
2004
2005// lane-interedge r1: frame-edge half strips on the INTER path, per partition
2006// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
2007// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
2008// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
2009// are height mod 16 == 8, so every inter frame crosses these nodes.
2010thread_local! {
2011 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
2012 const { std::cell::Cell::new([0; 6]) };
2013}
2014
2015/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
2016pub(crate) fn bump_inter_edge_strip(idx: usize) {
2017 hit_do! {
2018 INTER_EDGE_STRIP_HITS.with(|c| {
2019 let mut v = c.get();
2020 v[idx] += 1;
2021 c.set(v);
2022 });
2023 }
2024}
2025
2026// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
2027// forced split -- libaom `decode_partition` (decodeframe.c):
2028// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
2029// straddle case that reads NO symbol at all. Indexed by level:
2030// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
2031thread_local! {
2032 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
2033 const { std::cell::Cell::new([0; 4]) };
2034}
2035
2036fn bump_edge_both_cut(level: usize) {
2037 hit_do! {
2038 EDGE_BOTH_CUT_HITS.with(|c| {
2039 let mut v = c.get();
2040 v[level] += 1;
2041 c.set(v);
2042 });
2043 }
2044}
2045
2046/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
2047pub fn inter_edge_strip_hits() -> [usize; 6] {
2048 INTER_EDGE_STRIP_HITS.with(|c| c.get())
2049}
2050
2051/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
2052/// into the next one (class `counter-from-refused-stream`).
2053pub fn reset_inter_edge_strip_hits() {
2054 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
2055}
2056
2057/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
2058#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2059pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
2060 EDGE_BOTH_CUT_HITS.with(|c| c.get())
2061}
2062
2063/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
2064#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2065pub(crate) fn reset_edge_both_cut_hits() {
2066 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
2067}
2068
2069// How many HORZ/VERT intra strips resolved a SPLIT luma transform
2070// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
2071// the case every rect path here refused by name before, and the first
2072// refusal the user's ReelB extract (600s in) stops at.
2073thread_local! {
2074 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
2075 const { std::cell::Cell::new(0) };
2076}
2077
2078/// Current value of [`RECT_SPLIT_TX_HITS`].
2079#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2080pub(crate) fn rect_split_tx_hits() -> usize {
2081 RECT_SPLIT_TX_HITS.with(|c| c.get())
2082}
2083
2084// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
2085// side 64) AND split past the first depth, i.e. tiled more than one unit in
2086// each axis -- the only shape with a transform unit that has neighbours on
2087// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
2088// no gate fired before lane-rectsplit r2 (the shared counter above also
2089// counts 32x32-level and depth-1 strips, so it cannot prove this case).
2090thread_local! {
2091 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
2092 const { std::cell::Cell::new(0) };
2093}
2094
2095/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
2096#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2097pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
2098 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
2099}
2100
2101// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
2102// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
2103// chroma half takes that had no coefficient tables before (index order:
2104// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
2105// proves the pair it happens to hit cannot catch a transposed scan/context
2106// table (class scan-weights-cross-axis).
2107thread_local! {
2108 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
2109 const { std::cell::Cell::new([0; 4]) };
2110}
2111
2112/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
2113#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2114pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
2115 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
2116}
2117
2118// lane-av1-422: how many SQUARE chroma coefficient units the strip path read
2119// on a 4:2:2 frame (ss 1,0) -- the half-width, unhalved-height shape whose
2120// tables only exist because of the square rows in the chroma_tiled arm. A
2121// 4:2:0 or 4:4:4 frame can never increment it (their rect strips' chroma is
2122// itself rect), and a restored `/2 chroma height` diverts 4:2:2 squares onto
2123// the rect rows, so the witness gate reads 0 there and fails.
2124thread_local! {
2125 static CHROMA422_SQUARE_HITS: std::cell::Cell<usize> =
2126 const { std::cell::Cell::new(0) };
2127}
2128
2129/// Current value of [`CHROMA422_SQUARE_HITS`].
2130// lane-av1-422b: `pub` so `examples/decode_probe.rs` can census it the way
2131// it does every other capability counter.
2132pub fn chroma422_square_hits() -> usize {
2133 CHROMA422_SQUARE_HITS.with(|c| c.get())
2134}
2135
2136// lane-av1-422f: how many RECT chroma coefficient units the square-block
2137// path read on a 4:2:2 frame (ss 1,0) -- TX_4X8 / TX_8X16 / TX_16X32, the
2138// plane block's own half-width, unhalved-height shape. A 4:2:0 or 4:4:4
2139// frame never takes the rect branch (their units are square
2140// `chroma_tx == chroma_tx_h`), so a witness gate reading 0 here proves the
2141// model reverted to squares.
2142thread_local! {
2143 static CHROMA422_RECT_HITS: std::cell::Cell<usize> =
2144 const { std::cell::Cell::new(0) };
2145}
2146
2147/// Current value of [`CHROMA422_RECT_HITS`].
2148pub fn chroma422_rect_hits() -> usize {
2149 CHROMA422_RECT_HITS.with(|c| c.get())
2150}
2151
2152// lane-av1-422g: how many PER-LEAF TX_4X4 chroma coefficient units the
2153// sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per even-column
2154// leaf per plane (`is_chroma_reference`'s `!(mi_col & ss_x)`). A 4:2:0 frame
2155// codes no sub-8 chroma at all and 4:4:4 goes through `sub8_leaf_chroma444`,
2156// so a witness gate reading 0 here proves the per-leaf 4:2:2 arm never ran.
2157thread_local! {
2158 static CHROMA422_SUB8_HITS: std::cell::Cell<usize> =
2159 const { std::cell::Cell::new(0) };
2160}
2161
2162/// Current value of [`CHROMA422_SUB8_HITS`].
2163pub fn chroma422_sub8_hits() -> usize {
2164 CHROMA422_SUB8_HITS.with(|c| c.get())
2165}
2166
2167// lane-av1-422sub8rect: how many PER-PIECE TX_4X4 chroma coefficient units
2168// the INTER sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per
2169// non-skipped odd-column piece per plane (`is_chroma_reference`'s
2170// `mi_col & 0x01` at ss_x 1). 4:2:0 goes through the shared group unit and
2171// 4:4:4 through [`sub8_leaf_chroma444`]'s own per-piece twin, so a witness
2172// gate reading 0 here proves the inter 4:2:2 per-piece arm never ran.
2173thread_local! {
2174 static CHROMA422_INTER_SUB8_HITS: std::cell::Cell<usize> =
2175 const { std::cell::Cell::new(0) };
2176}
2177
2178/// Current value of [`CHROMA422_INTER_SUB8_HITS`].
2179pub fn chroma422_inter_sub8_hits() -> usize {
2180 CHROMA422_INTER_SUB8_HITS.with(|c| c.get())
2181}
2182
2183// lane-av1-422m: how many TX_4X4 chunk units the invalid-ss-size chroma arm
2184// read (the 8x32 luma block whose 4:2:2 plane has no `ss_size_lookup` block).
2185// A 4:2:0 or 4:4:4 frame cannot increment it, so a non-zero read proves the
2186// chunked 4:2:2 chroma really decoded.
2187thread_local! {
2188 static CHROMA422_CHUNK_HITS: std::cell::Cell<usize> =
2189 const { std::cell::Cell::new(0) };
2190}
2191
2192/// Current value of [`CHROMA422_CHUNK_HITS`].
2193pub fn chroma422_chunk_hits() -> usize {
2194 CHROMA422_CHUNK_HITS.with(|c| c.get())
2195}
2196
2197// lane-av1-422stripanchor: how many 4-wide-strip PAIR chroma units
2198// ([`decode_rect_split`]'s ported floored-pair anchor) decoded. A 4:2:0 or
2199// 4:4:4 frame cannot increment it (the arm is keyed to a 2-px-wide chroma
2200// block, which only a 1-mi-wide strip at ss (1, 0) produces), so a non-zero
2201// read proves a stream routed a 4-wide strip through the split path.
2202thread_local! {
2203 static CHROMA422_PAIR_WIDE_HITS: std::cell::Cell<usize> =
2204 const { std::cell::Cell::new(0) };
2205}
2206
2207/// Current value of [`CHROMA422_PAIR_WIDE_HITS`].
2208pub fn chroma422_pair_wide_hits() -> usize {
2209 CHROMA422_PAIR_WIDE_HITS.with(|c| c.get())
2210}
2211
2212// How many HORZ/VERT intra strips actually predicted with filter intra
2213// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
2214// ("this decoder predicts square-only") until `predict_filter_intra` took
2215// `bw`x`bh`.
2216thread_local! {
2217 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
2218 const { std::cell::Cell::new(0) };
2219}
2220
2221/// Current value of [`FILTER_INTRA_RECT_HITS`].
2222#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2223pub(crate) fn filter_intra_rect_hits() -> usize {
2224 FILTER_INTRA_RECT_HITS.with(|c| c.get())
2225}
2226
2227// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
2228// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
2229// was never read at all before that round, so a gate needs to prove the flag
2230// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
2231// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
2232// carry different probabilities (18101 vs 20229), so a transposed pair is
2233// only caught by a gate that sees the flag fire on BOTH shapes (class
2234// scan-weights-cross-axis).
2235thread_local! {
2236 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
2237 const { std::cell::Cell::new(0) };
2238 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
2239 const { std::cell::Cell::new(0) };
2240}
2241
2242/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
2243#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2244pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
2245 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
2246}
2247
2248/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
2249#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2250pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
2251 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
2252}
2253
2254// How many rectangular transform units actually coded coefficients through
2255// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
2256// exercised the rect coefficient reader at all rather than passing on
2257// all-skip blocks.
2258thread_local! {
2259 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2260 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2261}
2262
2263/// Current value of [`RECT_COEFF_TU_HITS`].
2264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2265pub(crate) fn rect_coeff_tu_hits() -> usize {
2266 RECT_COEFF_TU_HITS.with(|c| c.get())
2267}
2268
2269/// Rectangular transform units whose resolved `tx_type` is a 1D class
2270/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
2271/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
2272/// for the square reader's own 1D types.
2273#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2274pub(crate) fn rect_class1_hits() -> usize {
2275 RECT_CLASS1_HITS.with(|c| c.get())
2276}
2277
2278// lane-av1readcensus: the PER-UNIT coefficient census -- one unit counted
2279// per `read_coeffs`/`read_coeffs_rect` call, i.e. per object this decoder
2280// actually walks, which is the unit the round-4 `av1444rect` count measured
2281// (636 square chroma reads against the oracle's 1086). The counters are
2282// 4:4:4-ONLY (`CENSUS_444`, set per frame beside `set_subsampling`), so a
2283// 4:2:0 control reads `(0, 0, 0)` -- a walk-shape change at 4:2:0 is another
2284// lane's business, and this census must not fire there.
2285thread_local! {
2286 /// Per-plane unit counts, `[luma, u, v]`, at 4:4:4 only.
2287 static CENSUS_444_UNITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2288 /// Of [`CENSUS_444_UNITS`], the units that coded at least one coefficient
2289 /// (`txb_skip == 0`) -- the per-plane split is only comparable against
2290 /// the oracle's when both sides count all-zero units the same way.
2291 static CENSUS_444_CODED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2292 /// Sequential unit index, so a trace line names its own position in the
2293 /// frame's walk rather than relying on line order alone.
2294 static CENSUS_UNIT_N: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2295 /// The plane the units read from here on belong to. A thread-local rather
2296 /// than a `read_coeffs` parameter because the three luma call sites
2297 /// (`decode_rect_split`, `decode_block_rect64`, `read_inter_plane_rect`)
2298 /// are not this lane's to edit and would each grow an argument; the
2299 /// plane-owning readers stamp it once on entry instead.
2300 static CENSUS_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2301 /// 4:4:4 (`subsampling_x == 0 && subsampling_y == 0`) for the frame being
2302 /// decoded, set per frame from [`crate::stream`].
2303 static CENSUS_444: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2304}
2305
2306/// Current `[luma, u, v]` 4:4:4 coefficient-unit counts.
2307#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2308pub(crate) fn census_444_units() -> [usize; 3] {
2309 CENSUS_444_UNITS.with(|c| c.get())
2310}
2311
2312/// Current `[luma, u, v]` 4:4:4 counts of units that coded coefficients.
2313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2314pub(crate) fn census_444_coded() -> [usize; 3] {
2315 CENSUS_444_CODED.with(|c| c.get())
2316}
2317
2318/// lane-av1readcensus: arms the 4:4:4 census for the frame about to decode,
2319/// called once per frame from [`crate::stream`]'s decode loop beside
2320/// [`set_subsampling`]. At 4:2:0 (or 4:2:2) every census counter stays zero --
2321/// the walk-shape question this census answers is a 4:4:4 one.
2322pub(crate) fn set_census_444(ss_x: u8, ss_y: u8) {
2323 CENSUS_444.with(|c| c.set(ss_x == 0 && ss_y == 0));
2324}
2325
2326/// lane-av1readcensus: the plane the units read from here on belong to,
2327/// stamped by the plane-owning readers ([`read_plane`], [`read_inter_plane`],
2328/// [`read_inter_plane_rect`]) on entry.
2329pub(crate) fn set_census_plane(plane: usize) {
2330 CENSUS_PLANE.with(|c| c.set(plane));
2331}
2332
2333/// lane-av1readcensus: is the per-unit census trace on? Shares
2334/// [`coeff_trace_on`]'s per-frame narrowing so one frame's walk can be
2335/// dumped without the rest of the stream.
2336fn census_trace_on() -> bool {
2337 if !crate::envflags::env_flag!("EC_CENSUS_UNIT") {
2338 return false;
2339 }
2340 match COEFF_TRACE_FRAME.with(|c| c.get()) {
2341 None => true,
2342 Some(w) if w >= usize::MAX - 1 => true,
2343 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
2344 }
2345}
2346
2347/// lane-av1readcensus: one line per coefficient unit this decoder walks, the
2348/// twin of the oracle's `EC_COEFF` / `EC_COEFF_VAL` bracket around each
2349/// `av1_read_coeffs_txb` call. Pair the two sides by `post_rng` (or by `n`),
2350/// never by plane label or by walk position -- the walk order is exactly what
2351/// the census is measuring.
2352fn census_unit(
2353 w: usize,
2354 h: usize,
2355 tx_type: TxType,
2356 eob: usize,
2357 all_zero: bool,
2358 entry_rng: u32,
2359 dec: &SymbolDecoder,
2360) {
2361 let plane = CENSUS_PLANE.with(|c| c.get()).min(2);
2362 let coded = usize::from(!all_zero);
2363 CENSUS_UNIT_N.with(|c| c.set(c.get() + 1));
2364 hit_do! {
2365 CENSUS_444_UNITS.with(|c| {
2366 if CENSUS_444.with(|on| on.get()) {
2367 let mut v = c.get();
2368 v[plane] += 1;
2369 c.set(v);
2370 }
2371 });
2372 CENSUS_444_CODED.with(|c| {
2373 if CENSUS_444.with(|on| on.get()) {
2374 let mut v = c.get();
2375 v[plane] += coded;
2376 c.set(v);
2377 }
2378 });
2379 }
2380 if !census_trace_on() {
2381 return;
2382 }
2383 let n = CENSUS_UNIT_N.with(|c| c.get()) - 1;
2384 let post_rng = dec.debug_state().0;
2385 eprintln!(
2386 "EC_CENSUS_UNIT side=ours n={n} plane={plane} w={w} h={h} tx={tx_type:?} eob={eob} \
2387 all_zero={all_zero} entry_rng={entry_rng} post_rng={post_rng}"
2388 );
2389}
2390
2391// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
2392// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
2393// shapes whose `use_filter_intra` symbol had no CDF class before this round.
2394// A gate asserting the wider counter would be satisfied by a 32x16 strip and
2395// prove nothing about the new shapes.
2396thread_local! {
2397 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
2398 const { std::cell::Cell::new(0) };
2399}
2400
2401/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
2402#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2403pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
2404 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
2405}
2406
2407// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
2408// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
2409// counter would be satisfied by a 16x8 strip and prove nothing here.
2410thread_local! {
2411 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
2412 const { std::cell::Cell::new(0) };
2413}
2414
2415/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
2416#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2417pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
2418 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
2419}
2420
2421// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
2422// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
2423// call on the current thread -- the same before/after counter pattern as
2424// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
2425// `eob_pt`/1D-neighbour context path rather than every block coincidentally
2426// landing on `DCT_DCT`.
2427thread_local! {
2428 static TX_CLASS1_HITS: std::cell::Cell<usize> =
2429 const { std::cell::Cell::new(0) };
2430}
2431
2432// How many `uv_mode` reads resolved to a directional chroma mode (neither
2433// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
2434// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
2435// actually exercised chroma's own directional predictor.
2436thread_local! {
2437 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
2438 const { std::cell::Cell::new(0) };
2439}
2440
2441/// Current value of [`DIRECTIONAL_UV_HITS`].
2442#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2443pub(crate) fn directional_uv_hits() -> usize {
2444 DIRECTIONAL_UV_HITS.with(|c| c.get())
2445}
2446
2447// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
2448// something other than [`ANGLE_DELTA_ZERO`], across every call in the
2449// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
2450// proving a stream actually exercised a nonzero angle delta.
2451thread_local! {
2452 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
2453 const { std::cell::Cell::new(0) };
2454}
2455
2456// How many [`read_single_ref`] reads resolved to a reference other than
2457// `LAST_FRAME`, across every call on the current thread -- the same before/after
2458// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2459// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
2460// only other supported one so far) rather than every block coincidentally
2461// resolving `LAST_FRAME`.
2462thread_local! {
2463 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
2464 const { std::cell::Cell::new(0) };
2465}
2466
2467/// Current value of [`NON_LAST_REF_HITS`].
2468#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2469pub(crate) fn non_last_ref_hits() -> usize {
2470 NON_LAST_REF_HITS.with(|c| c.get())
2471}
2472
2473// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2474// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2475// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2476// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2477// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2478// `GOLDEN_FRAME` draw it did not ask for.
2479thread_local! {
2480 static LAST2_HITS: std::cell::Cell<usize> =
2481 const { std::cell::Cell::new(0) };
2482}
2483thread_local! {
2484 static LAST3_HITS: std::cell::Cell<usize> =
2485 const { std::cell::Cell::new(0) };
2486}
2487thread_local! {
2488 static GOLDEN_HITS: std::cell::Cell<usize> =
2489 const { std::cell::Cell::new(0) };
2490}
2491thread_local! {
2492 static BWDREF_HITS: std::cell::Cell<usize> =
2493 const { std::cell::Cell::new(0) };
2494}
2495thread_local! {
2496 static ALTREF2_HITS: std::cell::Cell<usize> =
2497 const { std::cell::Cell::new(0) };
2498}
2499thread_local! {
2500 static ALTREF_HITS: std::cell::Cell<usize> =
2501 const { std::cell::Cell::new(0) };
2502}
2503
2504// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2505// -- proves a `reference_select` stream actually reached a block that picked
2506// compound, not just that the header bit was set. Every such block is
2507// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2508// so this only ever counts attempted reads, never a completed decode.
2509thread_local! {
2510 static COMP_MODE_HITS: std::cell::Cell<usize> =
2511 const { std::cell::Cell::new(0) };
2512}
2513
2514/// Current value of [`COMP_MODE_HITS`].
2515#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2516pub(crate) fn comp_mode_hits() -> usize {
2517 COMP_MODE_HITS.with(|c| c.get())
2518}
2519
2520// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2521// use for, across every call on the current thread -- the same before/after
2522// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2523// exercised palette reconstruction rather than only reading and refusing the
2524// `palette_y_mode` symbol.
2525thread_local! {
2526 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2527}
2528
2529/// Current value of [`PALETTE_HITS`].
2530#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2531pub(crate) fn palette_hits() -> usize {
2532 PALETTE_HITS.with(|c| c.get())
2533}
2534
2535// lane-tiles r12: of those, how many sat at their own TILE's left column --
2536// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2537// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2538// palette gate that never hits one proves nothing about the tile guard.
2539thread_local! {
2540 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2541}
2542
2543/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2544#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2545pub(crate) fn palette_tile_left_hits() -> usize {
2546 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2547}
2548
2549// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2550// palette use -- proves a stream actually reconstructed UV palette pixels,
2551// not just read and refused the `palette_uv_mode` symbol.
2552thread_local! {
2553 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2554}
2555
2556/// Current value of [`PALETTE_UV_HITS`].
2557#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2558pub(crate) fn palette_uv_hits() -> usize {
2559 PALETTE_UV_HITS.with(|c| c.get())
2560}
2561
2562// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2563// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2564// (not just the square path's) actually fired.
2565thread_local! {
2566 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2567}
2568
2569/// Current value of [`PALETTE_RECT_HITS`].
2570#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2571pub(crate) fn palette_rect_hits() -> usize {
2572 PALETTE_RECT_HITS.with(|c| c.get())
2573}
2574
2575// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2576// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2577// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2578// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2579// RD, almost always refused-on-use because the block doesn't end up USING a
2580// palette -- see r5's report). This is the site the removed refusal
2581// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2582// fired here whether or not the block picked a palette, so this is the
2583// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2584// never observes.
2585thread_local! {
2586 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2587}
2588
2589/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2590#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2591pub(crate) fn rect_screen_content_hits() -> usize {
2592 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2593}
2594
2595// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2596// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2597// windowing actually ran, not just that the whole-block path stayed exact.
2598// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2599// first actually incremented in r7, when the refusal it guarded was lifted.
2600thread_local! {
2601 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2602}
2603
2604thread_local! {
2605 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2606 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2607 /// (16x8/8x16), the two shapes the lifted refusals named.
2608 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2609}
2610
2611/// Current value of [`RECT4_PALETTE_HITS`].
2612#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2613pub(crate) fn rect4_palette_hits() -> usize {
2614 RECT4_PALETTE_HITS.with(|c| c.get())
2615}
2616
2617/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2618#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2619pub(crate) fn palette_split_tx_hits() -> usize {
2620 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2621}
2622
2623thread_local! {
2624 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2625 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2626 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2627 /// `--min-partition-size=8` puts them on this leaf path.
2628 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2629}
2630
2631/// Current value of [`PALETTE_LEAF8_HITS`].
2632#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2633pub(crate) fn palette_leaf8_hits() -> usize {
2634 PALETTE_LEAF8_HITS.with(|c| c.get())
2635}
2636
2637/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2638#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2639pub(crate) fn reset_palette_leaf8_hits() {
2640 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2641}
2642
2643thread_local! {
2644 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2645 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2646 /// block that also carries a real, corner-cropped luma transform.
2647 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2648}
2649
2650/// Current value of [`PALETTE_SB_STRIP_HITS`].
2651#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2652pub(crate) fn palette_sb_strip_hits() -> usize {
2653 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2654}
2655
2656/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2657#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2658pub(crate) fn reset_palette_sb_strip_hits() {
2659 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2660}
2661
2662// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2663// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2664// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2665// capability rather than the key frame's, which every screen stream also
2666// carries.
2667thread_local! {
2668 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2669 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2670}
2671
2672// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2673// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2674// shared counter too, so only this one proves a gate really reached the leaf
2675// where the refusal used to sit.
2676thread_local! {
2677 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2678 const { std::cell::Cell::new((0, 0)) };
2679}
2680
2681/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2682pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2683 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2684}
2685
2686/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2687pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2688 (
2689 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2690 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2691 )
2692}
2693
2694// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2695// and which are therefore predicted one transform unit at a time (a skipped
2696// block codes no coefficients, so nothing else in the stream witnesses this
2697// path -- only the pixels do).
2698thread_local! {
2699 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2700}
2701
2702/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2703pub fn skip_split_tx_hits() -> usize {
2704 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2705}
2706
2707// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2708// `tx_depth` split the luma transform -- the arm that predicted DC off the
2709// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2710// witness this path, so a gate that wants it needs the counter.
2711thread_local! {
2712 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2713 /// lane-av1chromadc: chroma units of a skipped block whose intra-BC /
2714 /// UV-palette override had to be WINDOWED to the unit's own extent --
2715 /// i.e. `cn_cols * cn_rows > 1`, which at 4:2:0 never happens (the chroma
2716 /// plane block is one 32x32 unit) and at 4:4:4 is every block of 64 and
2717 /// above. Counts UNITS, not blocks. EXCLUSIVE to this walk: the other two
2718 /// override sites (the luma slot and `decode_intrabc_owned_rect`) have
2719 /// their own windows.
2720 static SKIP_CHROMA_OVERRIDE_WINDOW_HITS: std::cell::Cell<usize> =
2721 const { std::cell::Cell::new(0) };
2722}
2723
2724/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2725pub fn skip_split_tx_override_hits() -> usize {
2726 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2727}
2728
2729/// lane-av1chromadc: [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`].
2730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2731pub fn skip_chroma_override_window_hits() -> usize {
2732 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.get())
2733}
2734
2735/// Zeroes [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`] before a gate's own decode.
2736#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2737pub fn reset_skip_chroma_override_window_hits() {
2738 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.set(0));
2739}
2740
2741/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2742pub fn reset_skip_split_tx_override_hits() {
2743 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2744}
2745
2746// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2747// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2748// really are smaller than the block and FEWER symbols are read than the
2749// block has cells (class map-read-past-frame-edge).
2750thread_local! {
2751 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2752}
2753
2754/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2755pub fn palette_onscreen_cut_hits() -> usize {
2756 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2757}
2758
2759/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2760pub fn reset_palette_onscreen_cut_hits() {
2761 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2762}
2763
2764/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2765pub fn reset_skip_split_tx_hits() {
2766 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2767}
2768
2769// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2770// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2771// the gate's proof that the lifted path actually ran, per size.
2772thread_local! {
2773 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2774 const { std::cell::Cell::new([0; 4]) };
2775}
2776
2777/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2778#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2779pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2780 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2781}
2782
2783/// A just-decoded palette-Y block's own predicted pixels
2784/// (`side*side`, row-major, `colors[map[i]]`), consumed by
2785/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2786/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2787/// per-block override through `read_plane`'s two dozen call sites is the
2788/// alternative this avoids). Always empty again once that call consumes
2789/// it (`.take()`), so a non-palette block's own `reconstruct` call never
2790/// sees stale state.
2791
2792/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2793/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2794/// site whose reconstruct never runs would be picked up by the NEXT block's
2795/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2796/// lane-lossless2: one transform unit's window on a block-sized palette
2797/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2798/// handing it the whole-block buffer makes every unit reconstruct the block's
2799/// top-left corner (the luma split-transform paths already window; the chroma
2800/// ones did not, which is invisible until a lossless frame codes a palette
2801/// block as 4x4 chroma units).
2802fn palette_window(
2803 buf: &[u16],
2804 stride: usize,
2805 ox: usize,
2806 oy: usize,
2807 w: usize,
2808 h: usize,
2809) -> Vec<u16> {
2810 (0..h)
2811 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2812 .collect()
2813}
2814
2815/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2816#[track_caller]
2817fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2818 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2819 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2820 eprintln!(
2821 "PALSET len={} stale={stale} at {}",
2822 buf.len(),
2823 std::panic::Location::caller()
2824 );
2825 }
2826 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2827}
2828
2829#[track_caller]
2830fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2831 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2832 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2833 eprintln!(
2834 "PALTAKE len={:?} at {}",
2835 got.as_ref().map(Vec::len),
2836 std::panic::Location::caller()
2837 );
2838 }
2839 got
2840}
2841
2842/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2843/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2844/// pixels, because at parse time this block's own luma is still queued.
2845#[derive(Clone, Copy, Debug)]
2846pub(crate) struct CflSrc {
2847 px: usize,
2848 py: usize,
2849 bw: usize,
2850 bh: usize,
2851}
2852
2853fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2854 CflSrc {
2855 px,
2856 py,
2857 bw: side,
2858 bh: side,
2859 }
2860}
2861
2862fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2863 CflSrc { px, py, bw, bh }
2864}
2865
2866/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2867/// instead of executed. Each variant is the resolved argument tuple of the
2868/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2869/// order performs exactly the same writes in exactly the same order --
2870/// entropy parsing no longer touches the frame's own planes (except the two
2871/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2872/// the replay on a superblock-row wavefront worker.
2873/// The dequantization + inverse transform of one transform unit, kept as its
2874/// INPUTS so that a recorded write carries the work instead of its result
2875/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2876/// recon worker, not on the parsing thread. `stride == 0` means the dense
2877/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2878/// `reconstruct_mc_rect` reads both of its buffers at.
2879#[derive(Clone, Copy)]
2880pub(crate) struct TxParams {
2881 pub(crate) w: usize,
2882 pub(crate) h: usize,
2883 pub(crate) bit_depth: u8,
2884 pub(crate) q_idx: i32,
2885 pub(crate) dc_delta: i32,
2886 pub(crate) ac_delta: i32,
2887 pub(crate) tx_type: TxType,
2888 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
2889 /// on the parse thread by [`block_iqmatrix`] and captured here so the
2890 /// recon worker scales identically without touching frame state.
2891 pub(crate) qm: Option<crate::qm::Iqm>,
2892 pub(crate) stride: usize,
2893 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
2894 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
2895 /// the 4x4 Walsh-Hadamard
2896 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2897 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2898 pub(crate) lossless: bool,
2899}
2900
2901/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
2902/// The mixed-lossless witness's proof the per-segment lossless path really
2903/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
2904/// workers run this on their own threads.
2905static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2906
2907/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
2908/// delta around one decode.
2909#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2910pub(crate) fn lossless_wht_units() -> usize {
2911 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2912}
2913
2914/// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
2915/// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
2916/// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
2917/// `coded_lossless` frame before it looks at the `tx_mode` symbol,
2918/// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree,
2919/// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for
2920/// EVERY plane of a lossless block, and of `av1/common/idct.c`'s
2921/// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a
2922/// `lossless` branch -- every other size falls through to the IDCT, because
2923/// there is no non-4x4 lossless inverse transform to dispatch to. So one of
2924/// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape;
2925/// read as a before/after delta around one decode it names the caller. Must
2926/// read 0 on a stream whose lossless unit geometry is right. Atomic: the
2927/// wavefront workers run the transform on their own threads.
2928static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
2929 std::sync::atomic::AtomicUsize::new(0);
2930
2931/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
2932/// before/after delta around one decode.
2933#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2934pub(crate) fn lossless_wht_split_units() -> usize {
2935 LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2936}
2937
2938impl TxParams {
2939 /// The one copy of the produce-the-residual code: the inline path calls it
2940 /// on the parse thread, the wavefront worker calls it on its own, so both
2941 /// are the same function on the same inputs and byte-identical.
2942 fn run(self, grid: &[i32]) -> Vec<i32> {
2943 let residual = if self.lossless {
2944 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2945 // lane-whtshape: a non-4x4 unit here is this decoder's own
2946 // transform-unit geometry being wrong (see
2947 // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used
2948 // to be stopped by a `debug_assert_eq!` that RELEASE never ran:
2949 // the 4x4 WHT returned 16 values for a `w * h` block and the
2950 // release build died one frame later in the strided copy with an
2951 // opaque `range end index 8 out of range for slice of length 0`
2952 // that never named lossless or the transform. Counted, and
2953 // reconstructed as the raster of 4x4 WHT units
2954 // ([`crate::transform::dequant_and_inverse_wht`]) instead: total,
2955 // the same in both profiles, and the 4x4 fast path is the same
2956 // single call it always was. The old
2957 // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with
2958 // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does
2959 // not either), and `av1_get_tx_type` already answers `DCT_DCT` on
2960 // every plane of a lossless block, so asserting an argument
2961 // nothing reads was a debug-only panic on a value release
2962 // ignores.
2963 if self.w != 4 || self.h != 4 {
2964 LOSSLESS_WHT_SPLIT_UNITS.fetch_add(
2965 self.w.div_ceil(4) * self.h.div_ceil(4),
2966 std::sync::atomic::Ordering::Relaxed,
2967 );
2968 }
2969 crate::transform::dequant_and_inverse_wht(
2970 grid,
2971 self.w,
2972 self.h,
2973 self.bit_depth,
2974 self.q_idx,
2975 self.dc_delta,
2976 self.ac_delta,
2977 )
2978 } else {
2979 dequant_and_inverse_typed_wh(
2980 grid,
2981 self.w,
2982 self.h,
2983 self.bit_depth,
2984 self.q_idx,
2985 self.dc_delta,
2986 self.ac_delta,
2987 self.tx_type,
2988 self.qm,
2989 )
2990 };
2991 // An all-zero grid transforms to the empty marker, and a strided copy
2992 // of zeros is still zeros: the marker passes straight through.
2993 if residual.is_empty() {
2994 return residual;
2995 }
2996 if self.stride == 0 {
2997 return residual;
2998 }
2999 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
3000 // height exceeds its (narrow) prediction stride needs the full
3001 // stride * h; every square caller has h == stride and is unchanged.
3002 let mut strided = vec![0i32; self.stride * self.h];
3003 for row in 0..self.h {
3004 strided[row * self.stride..][..self.w]
3005 .copy_from_slice(&residual[row * self.w..][..self.w]);
3006 }
3007 strided
3008 }
3009}
3010
3011/// A recorded write's residual: already transformed, or the coefficients and
3012/// [`TxParams`] the worker transforms itself.
3013pub(crate) enum Residual {
3014 /// An already-transformed residual in the arena, `(offset, len)`; a zero
3015 /// `len` is the all-zero marker [`dense_residual`] expands.
3016 Done(u32, u32),
3017 /// The coefficients live in the pushing tile's arena
3018 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
3019 /// len)` in it.
3020 Coeffs(TxParams, u32, u32),
3021}
3022
3023impl Residual {
3024 /// The record for a transform unit whose coefficient grid is all zero:
3025 /// the empty marker, so neither the grid nor the residual is cloned and
3026 /// the worker never runs the transform (60% of the 4K segment's units).
3027 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3028 if is_zero_grid(grid) {
3029 return Self::Done(0, 0);
3030 }
3031 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
3032 }
3033
3034 /// A residual the parse thread already transformed, kept in the arena
3035 /// instead of its own `Vec`.
3036 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3037 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
3038 // which is exactly the all-zero marker -- one pointer compare instead
3039 // of copying up to 64 KB of zeros into the arena per block.
3040 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
3041 return Self::Done(0, 0);
3042 }
3043 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
3044 }
3045
3046 /// The residual to reconstruct with; `scratch` is where a transform run
3047 /// on this thread lands, so the caller owns that buffer.
3048 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
3049 match self {
3050 Self::Done(off, len) => &arena[off as usize..][..len as usize],
3051 Self::Coeffs(p, off, len) => {
3052 *scratch = p.run(&arena[off as usize..][..len as usize]);
3053 scratch
3054 }
3055 }
3056 }
3057}
3058
3059/// Appends to the tile's coefficient arena, returning the offset the record
3060/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
3061fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
3062 fctx.coeff_arena.with(|a| {
3063 let mut a = a.borrow_mut();
3064 let off = a.len();
3065 a.extend_from_slice(v);
3066 off as u32
3067 })
3068}
3069
3070/// [`push_coeffs`] for a recorded prediction.
3071fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
3072 fctx.pred_arena.with(|a| {
3073 let mut a = a.borrow_mut();
3074 let off = a.len();
3075 a.extend_from_slice(v);
3076 off as u32
3077 })
3078}
3079
3080/// An all-zero residual, for the transform units that code no coefficient:
3081/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
3082/// and the reconstruction loops below read this instead of a per-unit
3083/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
3084/// (a 128-wide inter block's prediction stride).
3085pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
3086
3087/// lane-blockscratch: one plane's coefficient levels as the block-tail
3088/// neighbour writes want them. A plane that coded nothing (a skipped block, a
3089/// strip with no chroma, luma under a var-tx split whose units already wrote
3090/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
3091/// zeroing up to 64 KB of its own per block.
3092#[derive(Clone)]
3093enum Grid {
3094 Zero(usize),
3095 Own(Vec<i32>),
3096}
3097
3098/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
3099/// unit that writes into it. Only a block wider or taller than 64 px codes its
3100/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
3101/// collectors per block and then drop them untouched.
3102fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
3103 if v.is_empty() {
3104 *v = vec![0i32; n];
3105 }
3106 v
3107}
3108
3109impl std::ops::Deref for Grid {
3110 type Target = [i32];
3111 fn deref(&self) -> &[i32] {
3112 match self {
3113 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
3114 Grid::Own(v) => v,
3115 }
3116 }
3117}
3118
3119/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
3120/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
3121/// transform units that code no coefficient without the scan (lane-coefgrid).
3122pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
3123 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
3124}
3125
3126/// `residual`, or `n` zeros when it is the empty all-zero marker.
3127fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
3128 if residual.is_empty() {
3129 &ZERO_RESIDUAL[..n]
3130 } else {
3131 residual
3132 }
3133}
3134
3135/// Where a recorded motion-compensated write reads its prediction from.
3136///
3137/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
3138/// the parse thread's single biggest reconstruction cost, so at
3139/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
3140/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
3141/// runs it into its own three-plane slot, and every transform unit of that
3142/// block then reads its window out of that slot ([`Pred::Cur`]).
3143#[derive(Clone, Copy)]
3144pub(crate) enum Pred<'a> {
3145 /// A prediction the parse thread already built, at its own stride
3146 /// (`stride == 0` means "the reader's own `stride` argument").
3147 Inline(&'a [u16], usize),
3148 /// The current block's deferred prediction: plane, its stride, and this
3149 /// unit's offset into it.
3150 Cur {
3151 plane: usize,
3152 stride: usize,
3153 off: usize,
3154 },
3155}
3156
3157impl<'a> Pred<'a> {
3158 /// The same prediction read at an explicit stride.
3159 fn view(self, stride: usize) -> Self {
3160 match self {
3161 Self::Inline(b, _) => Self::Inline(b, stride),
3162 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
3163 }
3164 }
3165 /// The materialised buffer and the stride to read it at (`stride` is the
3166 /// reader's own when this prediction was built dense); `None` for a
3167 /// deferred prediction, which only a recorded op can carry.
3168 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
3169 match self {
3170 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
3171 Self::Cur { .. } => None,
3172 }
3173 }
3174 /// This prediction's window starting `n` samples in.
3175 fn offset(self, n: usize) -> Self {
3176 match self {
3177 Self::Inline(b, s) => Self::Inline(&b[n..], s),
3178 Self::Cur { plane, stride, off } => Self::Cur {
3179 plane,
3180 stride,
3181 off: off + n,
3182 },
3183 }
3184 }
3185}
3186
3187/// [`Pred`], resolved into what a recorded op carries.
3188pub(crate) enum PredSrc {
3189 /// A prediction window in the tile's prediction arena, `(offset, len)`.
3190 Owned(u32, u32),
3191 /// A window of the block prediction: its plane, its offset, and the
3192 /// stride it is read at -- which is the block's, not necessarily the
3193 /// op's (a transform unit's residual stays dense, so the worker takes
3194 /// its window out of the block prediction itself).
3195 Cur {
3196 plane: usize,
3197 off: usize,
3198 src: usize,
3199 },
3200}
3201
3202/// One block's whole-block prediction build, deferred to a recon worker.
3203///
3204/// The closure borrows the tile's reference pictures and its own frame-level
3205/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
3206/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
3207/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
3208pub(crate) struct PredBuild(
3209 Box<
3210 dyn FnOnce(
3211 &mut PlaneBuf<'static>,
3212 &mut PlaneBuf<'static>,
3213 &mut PlaneBuf<'static>,
3214 &crate::decode::FrameCtx,
3215 // lane-blockmem: the previous block's three prediction buffers,
3216 // refilled in place -- the build used to return three fresh
3217 // `Vec`s per block and drop these.
3218 &mut [Vec<u16>; 3],
3219 ),
3220 >,
3221);
3222
3223// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
3224// pictures and frame tables, and the closure runs on exactly one worker.
3225#[allow(unsafe_code)]
3226unsafe impl Send for PredBuild {}
3227
3228/// `true` when this tile's writes are recorded for the wavefront instead of
3229/// performed at the push site, i.e. when a prediction may be deferred.
3230fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
3231 fctx.recon_planes.with(std::cell::Cell::get).is_none()
3232}
3233
3234/// The previous block's prediction buffer, cleared and zero-filled to `n`
3235/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
3236/// without the per-block allocation and free.
3237fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
3238 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
3239 // than resized element by element -- which is every block on the inline
3240 // path, where there is no previous buffer to reuse.
3241 if v.capacity() < n {
3242 return vec![0u16; n];
3243 }
3244 v.clear();
3245 v.resize(n, 0);
3246 v
3247}
3248
3249/// Records one block's prediction build for the worker that reconstructs it.
3250#[allow(unsafe_code)]
3251fn push_pred<'a>(
3252 fctx: &crate::decode::FrameCtx,
3253 f: impl FnOnce(
3254 &mut PlaneBuf<'static>,
3255 &mut PlaneBuf<'static>,
3256 &mut PlaneBuf<'static>,
3257 &crate::decode::FrameCtx,
3258 &mut [Vec<u16>; 3],
3259 ) + 'a,
3260) {
3261 type Dyn<'x> = dyn FnOnce(
3262 &mut PlaneBuf<'static>,
3263 &mut PlaneBuf<'static>,
3264 &mut PlaneBuf<'static>,
3265 &crate::decode::FrameCtx,
3266 &mut [Vec<u16>; 3],
3267 ) + 'x;
3268 let boxed: Box<Dyn<'a>> = Box::new(f);
3269 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
3270 // before the borrows the closure holds go out of scope.
3271 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
3272 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
3273}
3274
3275/// One superblock's recorded writes plus the two arenas they index -- the
3276/// unit a wavefront worker takes off the queue (lane-recoparse).
3277pub(crate) struct ReconJob {
3278 ops: Vec<ReconOp>,
3279 coeffs: Vec<i32>,
3280 preds: Vec<u16>,
3281}
3282
3283pub(crate) enum ReconOp {
3284 /// lane-wave4: build this block's prediction into the worker's slot.
3285 Pred(PredBuild),
3286 Intra {
3287 plane: usize,
3288 x: usize,
3289 y: usize,
3290 bw: usize,
3291 bh: usize,
3292 /// `true` when the parse site called `reconstruct_rect` (whose
3293 /// `edges_rect` differs from `edges` even at `bw == bh`).
3294 rect: bool,
3295 mode: usize,
3296 angle_delta: i32,
3297 reach: Reach,
3298 residual: Residual,
3299 cfl: Option<(i32, CflSrc)>,
3300 filter_intra: Option<usize>,
3301 smooth_neighbor: bool,
3302 /// The palette/intrabc prediction override, taken off
3303 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
3304 /// from that slot by the replay.
3305 pred: Option<Vec<u16>>,
3306 },
3307 Mc {
3308 plane: usize,
3309 x: usize,
3310 y: usize,
3311 stride: usize,
3312 w: usize,
3313 h: usize,
3314 prediction: PredSrc,
3315 residual: Residual,
3316 },
3317}
3318
3319/// The three planes of the tile currently being decoded, as raw pointers.
3320///
3321/// corner-cut: at one reconstruction thread a recorded write must cost
3322/// nothing -- deferring it to the end of the superblock is +1.2%
3323/// instructions and +4.5% wall on 4K, because the residual is written at
3324/// parse and read back cache-cold at replay. So the recorded op is performed
3325/// at the push site instead, through the pointers the tile decoder registers
3326/// once ([`ReconInline`]), which is the same thread, the same order and the
3327/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
3328/// stack still holds aliases them, exactly the [`crate::par::Shared`]
3329/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
3330/// threading the three planes down every `read_plane`/`read_inter_plane`
3331/// call site (~40) so the push site owns the borrow it writes through.
3332#[derive(Clone, Copy)]
3333pub(crate) struct ReconPlanes(
3334 *mut PlaneBuf<'static>,
3335 *mut PlaneBuf<'static>,
3336 *mut PlaneBuf<'static>,
3337);
3338
3339// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
3340// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
3341// value travelling is `None`; the pointers never leave the tile decoder's
3342// own thread.
3343#[allow(unsafe_code)]
3344unsafe impl Send for ReconPlanes {}
3345// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
3346// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
3347// contract, one superblock per band instead of one row band.
3348#[allow(unsafe_code)]
3349unsafe impl Sync for ReconPlanes {}
3350
3351/// Registers the tile's planes for inline reconstruction and unregisters them
3352/// on every exit from the tile decoder, including the `?` ones -- a stale
3353/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
3354/// tile.
3355pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
3356
3357#[allow(unsafe_code)]
3358impl<'a> ReconInline<'a> {
3359 /// Installs the guard for this tile when reconstruction is inline
3360 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
3361 /// to the queue instead, for the wavefront workers to replay.
3362 fn install(
3363 fctx: &'a crate::decode::FrameCtx,
3364 y: &mut PlaneBuf<'static>,
3365 u: &mut PlaneBuf<'static>,
3366 v: &mut PlaneBuf<'static>,
3367 ) -> Option<Self> {
3368 if crate::par::recon_threads() != 1 {
3369 return None;
3370 }
3371 // SAFETY: the planes are locals of the tile decoder and outlive the
3372 // guard, which is dropped on every exit from it (including `?`); see
3373 // [`ReconPlanes`] for the aliasing trade-off.
3374 let planes = ReconPlanes(
3375 std::ptr::from_mut(y),
3376 std::ptr::from_mut(u),
3377 std::ptr::from_mut(v),
3378 );
3379 fctx.recon_planes.with(|c| c.set(Some(planes)));
3380 Some(Self(fctx))
3381 }
3382}
3383
3384impl Drop for ReconInline<'_> {
3385 fn drop(&mut self) {
3386 self.0.recon_planes.with(|c| c.set(None));
3387 }
3388}
3389
3390#[allow(unsafe_code)]
3391fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
3392 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
3393 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
3394 // the parse site would have performed itself before lane-wave1.
3395 // The inline path never records coefficients (the transform runs at
3396 // the push site), so the arena is not read here.
3397 unsafe {
3398 exec_op(
3399 op,
3400 &mut *y,
3401 &mut *u,
3402 &mut *v,
3403 &mut Default::default(),
3404 &[],
3405 &[],
3406 fctx,
3407 )
3408 };
3409 return;
3410 }
3411 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
3412}
3413
3414/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
3415/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
3416///
3417/// The parser keeps parsing and never touches the planes; each superblock's
3418/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
3419/// `(row, column)` inside the tile (128x128 superblocks are one job for all
3420/// four of their 64x64 visits, since a 128 block writes across quadrants).
3421/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
3422/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
3423/// every pixel an intra predictor can read (its edges reach one block right
3424/// along the row above and one block down the column to the left, both
3425/// inside those two neighbours) and every CfL AC read (this block's own
3426/// luma, written by this same job). Jobs are handed out in raster order, so
3427/// the oldest outstanding one always has its dependencies met: no deadlock.
3428///
3429/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
3430/// `thread_local!` and miss every worker, which is why the default is 1.
3431pub(crate) struct WaveState {
3432 q: std::sync::Mutex<WaveQueue>,
3433 cv: std::sync::Condvar,
3434 planes: ReconPlanes,
3435 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
3436 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
3437 bit_depth: u8,
3438 enable_edge_filter: bool,
3439 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
3440 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3441 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3442 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3443 /// default halved every worker's chroma reference position and lost the
3444 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3445 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3446 subsampling: (u8, u8),
3447 last_col: usize,
3448}
3449
3450struct WaveQueue {
3451 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3452 /// row's front job can ever be runnable -- a job waits on its own left
3453 /// neighbour -- so a worker takes the lowest row whose front job's
3454 /// dependencies are met. Popping the raster-oldest job instead (what
3455 /// this replaced) put every worker on the SAME row, where the wavefront
3456 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3457 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3458 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3459 /// walking it.
3460 queued: usize,
3461 /// Per superblock row, the last column reconstructed (-1 = none yet).
3462 done: Vec<isize>,
3463 /// Per superblock row, the last column PARSED (submitted, whether or not
3464 /// it recorded any write) and the last column actually pushed as a job
3465 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3466 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3467 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3468 last_sub: Vec<isize>,
3469 last_push: Vec<isize>,
3470 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3471 active: usize,
3472 closed: bool,
3473 /// lane-sballoc: the three per-superblock buffers a finished job hands
3474 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3475 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3476 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3477 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3478 /// inside the queue's own mutex, which both sides already take.
3479 free: Vec<JobBufs>,
3480 free_cap: usize,
3481}
3482
3483/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3484type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3485
3486impl WaveQueue {
3487 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3488 /// or `None` (with the blocking condition counted when instrumented).
3489 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, ReconJob)> {
3490 let mut blocked: Option<bool> = None;
3491 for r in 0..self.rows.len() {
3492 let Some(front) = self.rows[r].front() else {
3493 continue;
3494 };
3495 let c = front.0;
3496 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3497 let left = c == 0 || self.done[r] >= c as isize - 1;
3498 if above && left {
3499 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3500 self.queued -= 1;
3501 return Some((r, c, job));
3502 }
3503 if blocked.is_none() {
3504 blocked = Some(above);
3505 }
3506 }
3507 if stats {
3508 match blocked {
3509 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3510 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3511 None => 0,
3512 };
3513 }
3514 None
3515 }
3516}
3517
3518/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3519/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3520/// empty queue), how far ahead the parse thread is, and how often the two
3521/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3522/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3523/// whole run.
3524const WS_SLOTS: usize = 16;
3525use std::sync::atomic::AtomicU64;
3526use std::sync::atomic::Ordering::Relaxed;
3527static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3528static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3529static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3530static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3531static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3532static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3533/// Parse-thread time between two submits, i.e. everything parse still does
3534/// itself (symbol decode plus the predictions not deferred).
3535static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3536/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3537/// (the intrabc/interintra reads) and at the tile's end.
3538static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3539static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3540static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3541static WS_TILES: AtomicU64 = AtomicU64::new(0);
3542
3543fn wave_stats() -> bool {
3544 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3545 match ON.load(Relaxed) {
3546 0 => {
3547 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3548 .map(|v| v.trim() == "1")
3549 .unwrap_or(false);
3550 ON.store(1 + u8::from(on), Relaxed);
3551 on
3552 }
3553 n => n == 2,
3554 }
3555}
3556
3557fn wave_stats_dump() {
3558 let ms = |n: u64| n as f64 / 1e6;
3559 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3560 for i in 0..WS_SLOTS {
3561 let jobs = WS_JOBS[i].load(Relaxed);
3562 if jobs == 0 {
3563 continue;
3564 }
3565 s += &format!(
3566 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3567 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3568 ms(WS_BUSY[i].load(Relaxed)),
3569 ms(WS_WAIT[i].load(Relaxed)),
3570 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3571 );
3572 }
3573 s += &format!(
3574 " | pipe={}/{}",
3575 PIPE_FRAMES.load(Relaxed),
3576 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3577 );
3578 s += &format!(
3579 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3580 ms(WS_PARSE.load(Relaxed)),
3581 ms(WS_BARRIER.load(Relaxed)),
3582 WS_BARRIERS.load(Relaxed),
3583 ms(WS_DRAIN.load(Relaxed)),
3584 WS_BLOCK_ABOVE.load(Relaxed),
3585 WS_BLOCK_LEFT.load(Relaxed),
3586 );
3587 eprintln!("{s}");
3588}
3589
3590#[allow(unsafe_code)]
3591fn wave_worker(st: &WaveState, idx: usize) {
3592 let fctx = FrameCtx::new();
3593 fctx.bit_depth.set(st.bit_depth);
3594 fctx.enable_edge_filter.set(st.enable_edge_filter);
3595 let (sx, sy) = st.subsampling;
3596 fctx.subsampling_x.set(sx);
3597 fctx.subsampling_y.set(sy);
3598 let stats = wave_stats();
3599 let slot = idx.min(WS_SLOTS - 1);
3600 loop {
3601 let t0 = std::time::Instant::now();
3602 let mut q = st.q.lock().unwrap();
3603 let (r, c, job) = loop {
3604 if let Some(job) = q.take_runnable(st.last_col, stats) {
3605 break job;
3606 }
3607 if q.closed && q.queued == 0 {
3608 return;
3609 }
3610 q = st.cv.wait(q).unwrap();
3611 };
3612 q.active += 1;
3613 drop(q);
3614 if stats {
3615 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3616 WS_JOBS[slot].fetch_add(1, Relaxed);
3617 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3618 }
3619 let t1 = std::time::Instant::now();
3620 let ReconPlanes(y, u, v) = st.planes;
3621 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3622 // every superblock that could have written or be reading them is
3623 // complete by the wavefront rule above.
3624 let mut cur: [Vec<u16>; 3] = Default::default();
3625 let ReconJob {
3626 mut ops,
3627 mut coeffs,
3628 mut preds,
3629 } = job;
3630 unsafe {
3631 for op in ops.drain(..) {
3632 exec_op(
3633 op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx,
3634 );
3635 }
3636 }
3637 if stats {
3638 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3639 }
3640 coeffs.clear();
3641 preds.clear();
3642 let mut q = st.q.lock().unwrap();
3643 // lane-sballoc: hand the three buffers back for the next submit.
3644 if q.free.len() < q.free_cap {
3645 q.free.push((ops, coeffs, preds));
3646 }
3647 q.done[r] = c as isize;
3648 q.active -= 1;
3649 st.cv.notify_all();
3650 }
3651}
3652
3653/// Installs the wavefront for one tile and joins its workers on every exit
3654/// from the tile decoder, including the `?` ones -- the jobs hold raw
3655/// pointers into the tile's planes, so no worker may outlive them.
3656/// (lane-pool1: the workers come from this thread's persistent pool, so a
3657/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3658/// with fresh scratch.)
3659pub(crate) struct WaveGuard<'a>(
3660 &'a crate::decode::FrameCtx,
3661 Option<crate::par::Batch<'static>>,
3662);
3663
3664#[allow(unsafe_code)]
3665impl<'a> WaveGuard<'a> {
3666 fn install(
3667 fctx: &'a crate::decode::FrameCtx,
3668 y: &mut PlaneBuf<'static>,
3669 u: &mut PlaneBuf<'static>,
3670 v: &mut PlaneBuf<'static>,
3671 rows: usize,
3672 cols: usize,
3673 ) -> Option<Self> {
3674 let threads = crate::par::recon_threads();
3675 if threads == 1 || rows == 0 || cols == 0 {
3676 return None;
3677 }
3678 let st = std::sync::Arc::new(WaveState {
3679 q: std::sync::Mutex::new(WaveQueue {
3680 rows: (0..rows)
3681 .map(|_| std::collections::VecDeque::new())
3682 .collect(),
3683 queued: 0,
3684 done: vec![-1; rows],
3685 last_sub: vec![-1; rows],
3686 last_push: vec![-1; rows],
3687 active: 0,
3688 closed: false,
3689 free: Vec::new(),
3690 free_cap: threads + 2,
3691 }),
3692 cv: std::sync::Condvar::new(),
3693 // SAFETY: the planes are locals of the tile decoder and outlive
3694 // this guard, which joins every worker in `drop`.
3695 planes: ReconPlanes(
3696 std::ptr::from_mut(y),
3697 std::ptr::from_mut(u),
3698 std::ptr::from_mut(v),
3699 ),
3700 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3701 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3702 subsampling: (
3703 fctx.subsampling_x.with(std::cell::Cell::get),
3704 fctx.subsampling_y.with(std::cell::Cell::get),
3705 ),
3706 last_col: cols - 1,
3707 });
3708 let batch = crate::par::Batch::new("ec-av1-recon");
3709 for idx in 0..threads {
3710 let st = std::sync::Arc::clone(&st);
3711 batch.submit(move || wave_worker(&st, idx));
3712 }
3713 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3714 fctx.wave_mark
3715 .with(|c| c.set(Some(std::time::Instant::now())));
3716 Some(Self(fctx, Some(batch)))
3717 }
3718}
3719
3720impl Drop for WaveGuard<'_> {
3721 fn drop(&mut self) {
3722 let st = self.0.wave.with(|w| w.borrow_mut().take());
3723 if let Some(st) = st {
3724 st.q.lock().unwrap().closed = true;
3725 st.cv.notify_all();
3726 }
3727 let t0 = std::time::Instant::now();
3728 // Dropping the batch waits every worker out, as the joins did.
3729 drop(self.1.take());
3730 if wave_stats() {
3731 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3732 WS_TILES.fetch_add(1, Relaxed);
3733 wave_stats_dump();
3734 }
3735 }
3736}
3737
3738/// An empty buffer for the next superblock: the recycled one when it is at
3739/// least as big as the superblock just parsed, else a fresh sized one
3740/// (lane-sballoc; `v` is always empty).
3741fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3742 if v.capacity() < cap {
3743 v.reserve_exact(cap - v.len());
3744 }
3745 v
3746}
3747
3748/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3749/// when there is no wavefront (one reconstruction thread), in which case the
3750/// caller replays them itself.
3751fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3752 let st = fctx.wave.with(|w| w.borrow().clone());
3753 let Some(st) = st else { return false };
3754 // lane-blockmem: the op list is replaced sized for the next superblock,
3755 // exactly as the two arenas below are -- taking it left a zero-capacity
3756 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3757 // every superblock.
3758 // lane-sballoc: the replacement comes from the finished jobs' free list
3759 // when there is one (warm capacity, already faulted in); only the first
3760 // superblocks of a tile allocate.
3761 let mut q = st.q.lock().unwrap();
3762 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3763 let ops = fctx.recon_ops.with(|c| {
3764 let mut c = c.borrow_mut();
3765 let cap = c.len();
3766 std::mem::replace(&mut *c, reuse(sops, cap))
3767 });
3768 // The job owns its coefficients: the arena is replaced by an empty one
3769 // sized for the next superblock, so parse never regrows from nothing and
3770 // the worker frees this buffer once, instead of once per unit.
3771 let coeffs = fctx.coeff_arena.with(|c| {
3772 let mut c = c.borrow_mut();
3773 let cap = c.len();
3774 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3775 });
3776 let preds = fctx.pred_arena.with(|c| {
3777 let mut c = c.borrow_mut();
3778 let cap = c.len();
3779 std::mem::replace(&mut *c, reuse(spreds, cap))
3780 });
3781 {
3782 if (c as isize) > q.last_sub[r] {
3783 q.last_sub[r] = c as isize;
3784 }
3785 if !ops.is_empty() {
3786 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3787 q.queued += 1;
3788 q.last_push[r] = c as isize;
3789 }
3790 drop(q);
3791 st.cv.notify_all();
3792 }
3793 if wave_stats() {
3794 let now = std::time::Instant::now();
3795 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3796 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3797 }
3798 }
3799 true
3800}
3801
3802/// Waits until every submitted job is reconstructed, so the parser may read
3803/// the planes itself (the intrabc source fetch and the interintra intra
3804/// predictor -- see [`flush_recon`]).
3805fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3806 let st = fctx.wave.with(|w| w.borrow().clone());
3807 let Some(st) = st else { return };
3808 let stats = wave_stats();
3809 let t0 = std::time::Instant::now();
3810 let mut q = st.q.lock().unwrap();
3811 while q.queued > 0 || q.active > 0 {
3812 q = st.cv.wait(q).unwrap();
3813 }
3814 drop(q);
3815 if stats {
3816 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3817 WS_BARRIERS.fetch_add(1, Relaxed);
3818 }
3819}
3820
3821/// Performs an intra write at its push site when the tile registered its
3822/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3823/// caller must record it for the wavefront workers instead.
3824#[allow(unsafe_code)]
3825#[allow(clippy::too_many_arguments)]
3826fn inline_intra(
3827 plane: usize,
3828 x: usize,
3829 oy: usize,
3830 bw: usize,
3831 bh: usize,
3832 rect: bool,
3833 mode: usize,
3834 angle_delta: i32,
3835 reach: Reach,
3836 residual: &[i32],
3837 cfl: Option<(i32, CflSrc)>,
3838 filter_intra: Option<usize>,
3839 smooth_neighbor: bool,
3840 fctx: &crate::decode::FrameCtx,
3841) -> bool {
3842 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3843 return false;
3844 };
3845 let pred = take_palette_pred(fctx);
3846 // SAFETY: see [`ReconPlanes`].
3847 unsafe {
3848 exec_intra(
3849 &mut *y,
3850 &mut *u,
3851 &mut *v,
3852 plane,
3853 x,
3854 oy,
3855 bw,
3856 bh,
3857 rect,
3858 mode,
3859 angle_delta,
3860 reach,
3861 residual,
3862 cfl,
3863 filter_intra,
3864 smooth_neighbor,
3865 pred,
3866 fctx,
3867 );
3868 }
3869 true
3870}
3871
3872/// [`inline_intra`] for a motion-compensated write.
3873#[allow(unsafe_code)]
3874#[allow(clippy::too_many_arguments)]
3875fn inline_mc(
3876 plane: usize,
3877 x: usize,
3878 oy: usize,
3879 stride: usize,
3880 w: usize,
3881 h: usize,
3882 prediction: &[u16],
3883 residual: &[i32],
3884 fctx: &crate::decode::FrameCtx,
3885) -> bool {
3886 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3887 return false;
3888 };
3889 // SAFETY: see [`ReconPlanes`].
3890 unsafe {
3891 exec_mc(
3892 &mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx,
3893 );
3894 }
3895 true
3896}
3897
3898/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3899#[allow(clippy::too_many_arguments)]
3900fn push_intra(
3901 plane: usize,
3902 x: usize,
3903 y: usize,
3904 side: usize,
3905 mode: usize,
3906 angle_delta: i32,
3907 reach: Reach,
3908 residual: &[i32],
3909 cfl: Option<(i32, CflSrc)>,
3910 filter_intra: Option<usize>,
3911 smooth_neighbor: bool,
3912 fctx: &crate::decode::FrameCtx,
3913) {
3914 if inline_intra(
3915 plane,
3916 x,
3917 y,
3918 side,
3919 side,
3920 false,
3921 mode,
3922 angle_delta,
3923 reach,
3924 residual,
3925 cfl,
3926 filter_intra,
3927 smooth_neighbor,
3928 fctx,
3929 ) {
3930 return;
3931 }
3932 let pred = take_palette_pred(fctx);
3933 push_op(
3934 fctx,
3935 ReconOp::Intra {
3936 plane,
3937 x,
3938 y,
3939 bw: side,
3940 bh: side,
3941 rect: false,
3942 mode,
3943 angle_delta,
3944 reach,
3945 residual: Residual::done(residual, fctx),
3946 cfl,
3947 filter_intra,
3948 smooth_neighbor,
3949 pred,
3950 },
3951 );
3952}
3953
3954/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3955#[allow(clippy::too_many_arguments)]
3956fn push_intra_rect(
3957 plane: usize,
3958 x: usize,
3959 y: usize,
3960 bw: usize,
3961 bh: usize,
3962 mode: usize,
3963 angle_delta: i32,
3964 reach: Reach,
3965 residual: &[i32],
3966 cfl: Option<(i32, CflSrc)>,
3967 filter_intra: Option<usize>,
3968 smooth_neighbor: bool,
3969 fctx: &crate::decode::FrameCtx,
3970) {
3971 if inline_intra(
3972 plane,
3973 x,
3974 y,
3975 bw,
3976 bh,
3977 true,
3978 mode,
3979 angle_delta,
3980 reach,
3981 residual,
3982 cfl,
3983 filter_intra,
3984 smooth_neighbor,
3985 fctx,
3986 ) {
3987 return;
3988 }
3989 let pred = take_palette_pred(fctx);
3990 push_op(
3991 fctx,
3992 ReconOp::Intra {
3993 plane,
3994 x,
3995 y,
3996 bw,
3997 bh,
3998 rect: true,
3999 mode,
4000 angle_delta,
4001 reach,
4002 residual: Residual::done(residual, fctx),
4003 cfl,
4004 filter_intra,
4005 smooth_neighbor,
4006 pred,
4007 },
4008 );
4009}
4010
4011/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
4012fn push_mc(
4013 plane: usize,
4014 x: usize,
4015 y: usize,
4016 side: usize,
4017 prediction: Pred<'_>,
4018 residual: &[i32],
4019 fctx: &crate::decode::FrameCtx,
4020) {
4021 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
4022}
4023
4024/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
4025#[allow(clippy::too_many_arguments)]
4026fn push_mc_rect(
4027 plane: usize,
4028 x: usize,
4029 y: usize,
4030 stride: usize,
4031 w: usize,
4032 h: usize,
4033 prediction: Pred<'_>,
4034 residual: &[i32],
4035 fctx: &crate::decode::FrameCtx,
4036) {
4037 let (src, stride) = match prediction.inline(stride) {
4038 Some(v) => v,
4039 None => {
4040 let Pred::Cur {
4041 plane: sp,
4042 stride: ss,
4043 off,
4044 } = prediction
4045 else {
4046 unreachable!()
4047 };
4048 push_op(
4049 fctx,
4050 ReconOp::Mc {
4051 plane,
4052 x,
4053 y,
4054 stride: ss,
4055 w,
4056 h,
4057 prediction: PredSrc::Cur {
4058 plane: sp,
4059 off,
4060 src: ss,
4061 },
4062 residual: Residual::done(residual, fctx),
4063 },
4064 );
4065 return;
4066 }
4067 };
4068 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
4069 return;
4070 }
4071 push_op(
4072 fctx,
4073 ReconOp::Mc {
4074 plane,
4075 x,
4076 y,
4077 stride,
4078 w,
4079 h,
4080 // The whole window `reconstruct_mc_rect` reads at `stride`, not
4081 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
4082 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
4083 residual: Residual::done(residual, fctx),
4084 },
4085 );
4086}
4087
4088/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
4089/// thread the transform runs here, exactly as before; on the wavefront it
4090/// travels with the op and runs on the worker (lane-wave3).
4091#[allow(clippy::too_many_arguments)]
4092fn push_intra_tx(
4093 plane: usize,
4094 x: usize,
4095 y: usize,
4096 bw: usize,
4097 bh: usize,
4098 rect: bool,
4099 mode: usize,
4100 angle_delta: i32,
4101 reach: Reach,
4102 tx: TxParams,
4103 grid: &[i32],
4104 cfl: Option<(i32, CflSrc)>,
4105 filter_intra: Option<usize>,
4106 smooth_neighbor: bool,
4107 fctx: &crate::decode::FrameCtx,
4108) {
4109 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4110 inline_intra(
4111 plane,
4112 x,
4113 y,
4114 bw,
4115 bh,
4116 rect,
4117 mode,
4118 angle_delta,
4119 reach,
4120 &tx.run(grid),
4121 cfl,
4122 filter_intra,
4123 smooth_neighbor,
4124 fctx,
4125 );
4126 return;
4127 }
4128 let pred = take_palette_pred(fctx);
4129 push_op(
4130 fctx,
4131 ReconOp::Intra {
4132 plane,
4133 x,
4134 y,
4135 bw,
4136 bh,
4137 rect,
4138 mode,
4139 angle_delta,
4140 reach,
4141 residual: Residual::coeffs(tx, grid, fctx),
4142 cfl,
4143 filter_intra,
4144 smooth_neighbor,
4145 pred,
4146 },
4147 );
4148}
4149
4150/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
4151#[allow(clippy::too_many_arguments)]
4152fn push_mc_rect_tx(
4153 plane: usize,
4154 x: usize,
4155 y: usize,
4156 stride: usize,
4157 w: usize,
4158 h: usize,
4159 prediction: Pred<'_>,
4160 tx: TxParams,
4161 grid: &[i32],
4162 fctx: &crate::decode::FrameCtx,
4163) {
4164 // lane-wave4: a deferred prediction is not there to be windowed -- the
4165 // op carries its offset into the block's prediction instead, and the
4166 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
4167 // both buffers at one stride).
4168 let (prediction, stride) = match prediction.inline(stride) {
4169 Some(v) => v,
4170 None => {
4171 let Pred::Cur {
4172 plane: sp,
4173 stride: ss,
4174 off,
4175 } = prediction
4176 else {
4177 unreachable!()
4178 };
4179 let mut tx = tx;
4180 tx.stride = 0;
4181 push_op(
4182 fctx,
4183 ReconOp::Mc {
4184 plane,
4185 x,
4186 y,
4187 stride: w,
4188 w,
4189 h,
4190 prediction: PredSrc::Cur {
4191 plane: sp,
4192 off,
4193 src: ss,
4194 },
4195 residual: Residual::coeffs(tx, grid, fctx),
4196 },
4197 );
4198 return;
4199 }
4200 };
4201 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4202 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
4203 // stride, so a prediction handed over at the block's stride (a var-tx
4204 // unit's window, lane-wave4) has to be densified for a dense residual
4205 // -- which is exactly what the recorded path below does.
4206 let residual = tx.run(grid);
4207 let res_stride = if tx.stride == 0 { w } else { tx.stride };
4208 let window;
4209 let prediction = if stride == res_stride {
4210 prediction
4211 } else {
4212 debug_assert_eq!(res_stride, w);
4213 let mut win = Vec::with_capacity(w * h);
4214 for row in 0..h {
4215 win.extend_from_slice(&prediction[row * stride..][..w]);
4216 }
4217 window = win;
4218 &window[..]
4219 };
4220 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
4221 return;
4222 }
4223 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
4224 // two buffers at `stride`, so the record carries that window densely
4225 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
4226 // copied 64*64 samples on the PARSING thread before. The residual is then
4227 // produced dense too (`TxParams::stride = 0`), which is the same numbers
4228 // in the same places at stride `w`.
4229 let off = fctx.pred_arena.with(|a| {
4230 let mut a = a.borrow_mut();
4231 let off = a.len();
4232 for row in 0..h {
4233 a.extend_from_slice(&prediction[row * stride..][..w]);
4234 }
4235 off as u32
4236 });
4237 let mut tx = tx;
4238 tx.stride = 0;
4239 push_op(
4240 fctx,
4241 ReconOp::Mc {
4242 plane,
4243 x,
4244 y,
4245 stride: w,
4246 w,
4247 h,
4248 prediction: PredSrc::Owned(off, (w * h) as u32),
4249 residual: Residual::coeffs(tx, grid, fctx),
4250 },
4251 );
4252}
4253
4254/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
4255/// and empties the queue (lane-wave1 step (i)).
4256///
4257/// Called at the top of each superblock visit and at the end of each tile, so
4258/// a whole superblock's parsing runs with no plane access at all; the two
4259/// parse-time pixel READS that survive -- the intrabc source fetch and the
4260/// interintra intra predictor -- flush ahead of themselves instead, which
4261/// keeps them byte-exact and names exactly what step (ii) still has to move.
4262fn flush_recon(
4263 fctx: &crate::decode::FrameCtx,
4264 y: &mut PlaneBuf<'static>,
4265 u: &mut PlaneBuf<'static>,
4266 v: &mut PlaneBuf<'static>,
4267) {
4268 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
4269 // writes in place, not just this superblock's queue.
4270 wave_barrier(fctx);
4271 let mut ops = fctx
4272 .recon_spare
4273 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4274 fctx.recon_ops
4275 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
4276 let mut coeffs = fctx
4277 .coeff_spare
4278 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4279 fctx.coeff_arena
4280 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
4281 let mut preds = fctx
4282 .pred_spare
4283 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4284 fctx.pred_arena
4285 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
4286 let mut cur: [Vec<u16>; 3] = Default::default();
4287 for op in ops.drain(..) {
4288 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
4289 }
4290 coeffs.clear();
4291 preds.clear();
4292 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
4293 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
4294 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
4295}
4296
4297/// Performs one recorded write: the body [`flush_recon`] replays, and the
4298/// body [`push_op`] runs immediately when reconstruction is inline.
4299fn exec_op(
4300 op: ReconOp,
4301 y: &mut PlaneBuf<'static>,
4302 u: &mut PlaneBuf<'static>,
4303 v: &mut PlaneBuf<'static>,
4304 cur: &mut [Vec<u16>; 3],
4305 coeffs: &[i32],
4306 preds: &[u16],
4307 fctx: &crate::decode::FrameCtx,
4308) {
4309 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
4310 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
4311 // alone. It makes the encoder's own streams garbage, so it is a
4312 // MEASUREMENT rung only -- what it measures is how much of the encoder's
4313 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
4314 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
4315 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
4316 // stage and the parse plus the neighbour grids are the other 94%. That
4317 // is why handing the decoder the encoder's own reconstruction cannot
4318 // shrink the stage: only publishing the per-mi neighbour state the
4319 // filters read (and so never parsing at all) can.
4320 if crate::envflags::env_flag!("EC_AV1_NORECON") {
4321 return;
4322 }
4323 let mut scratch = Vec::new();
4324 match op {
4325 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
4326 ReconOp::Intra {
4327 plane,
4328 x,
4329 y: oy,
4330 bw,
4331 bh,
4332 rect,
4333 mode,
4334 angle_delta,
4335 reach,
4336 residual,
4337 cfl,
4338 filter_intra,
4339 smooth_neighbor,
4340 pred,
4341 } => exec_intra(
4342 y,
4343 u,
4344 v,
4345 plane,
4346 x,
4347 oy,
4348 bw,
4349 bh,
4350 rect,
4351 mode,
4352 angle_delta,
4353 reach,
4354 residual.resolve(coeffs, &mut scratch),
4355 cfl,
4356 filter_intra,
4357 smooth_neighbor,
4358 pred,
4359 fctx,
4360 ),
4361 ReconOp::Mc {
4362 plane,
4363 x,
4364 y: oy,
4365 stride,
4366 w,
4367 h,
4368 prediction,
4369 residual,
4370 } => {
4371 let residual = residual.resolve(coeffs, &mut scratch);
4372 match prediction {
4373 PredSrc::Owned(off, len) => {
4374 let p = &preds[off as usize..][..len as usize];
4375 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
4376 }
4377 PredSrc::Cur {
4378 plane: sp,
4379 off,
4380 src,
4381 } => {
4382 let block = std::mem::take(&mut cur[sp]);
4383 if src == stride {
4384 exec_mc(
4385 y,
4386 u,
4387 v,
4388 plane,
4389 x,
4390 oy,
4391 stride,
4392 w,
4393 h,
4394 &block[off..],
4395 residual,
4396 fctx,
4397 );
4398 } else {
4399 // A transform unit's residual is dense, so its window
4400 // of the block prediction is taken out dense too --
4401 // the copy the parsing thread used to make, made here.
4402 let mut window = Vec::with_capacity(w * h);
4403 for row in 0..h {
4404 window.extend_from_slice(&block[off + row * src..][..w]);
4405 }
4406 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
4407 }
4408 cur[sp] = block;
4409 }
4410 }
4411 }
4412 }
4413}
4414
4415/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
4416/// path ([`push_op`]'s registered planes) reaches it without ever building
4417/// the record -- which is what keeps one reconstruction thread at the cost of
4418/// the pre-lane-wave1 decoder.
4419#[allow(clippy::too_many_arguments)]
4420fn exec_intra(
4421 y: &mut PlaneBuf<'static>,
4422 u: &mut PlaneBuf<'static>,
4423 v: &mut PlaneBuf<'static>,
4424 plane: usize,
4425 x: usize,
4426 oy: usize,
4427 bw: usize,
4428 bh: usize,
4429 rect: bool,
4430 mode: usize,
4431 angle_delta: i32,
4432 reach: Reach,
4433 residual: &[i32],
4434 cfl: Option<(i32, CflSrc)>,
4435 filter_intra: Option<usize>,
4436 smooth_neighbor: bool,
4437 pred: Option<Vec<u16>>,
4438 fctx: &crate::decode::FrameCtx,
4439) {
4440 // The CfL AC signal is read HERE, off the luma that has already been
4441 // written for this block -- at parse time it would have been the previous
4442 // frame's samples.
4443 let ac = cfl.map(|(alpha, src)| {
4444 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
4445 (alpha, sig)
4446 });
4447 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
4448 let target: &mut PlaneBuf<'static> = match plane {
4449 0 => &mut *y,
4450 1 => &mut *u,
4451 _ => &mut *v,
4452 };
4453 // lane-av1cmpaudit: label the in-flight reconstruction's plane for the
4454 // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`).
4455 // Saved and restored so the rung reports THIS call's plane even under
4456 // nesting, and so both of exec_intra's return paths need no cleanup.
4457 let prev_plane = RECON_PLANE.with(|c| c.replace(plane));
4458 let _plane_guard = PlaneGuard(prev_plane);
4459 if rect {
4460 target.reconstruct_rect(
4461 x,
4462 oy,
4463 bw,
4464 bh,
4465 mode,
4466 angle_delta,
4467 reach,
4468 residual,
4469 cfl,
4470 filter_intra,
4471 smooth_neighbor,
4472 pred,
4473 fctx,
4474 );
4475 } else {
4476 target.reconstruct(
4477 x,
4478 oy,
4479 bw,
4480 mode,
4481 angle_delta,
4482 reach,
4483 residual,
4484 cfl,
4485 filter_intra,
4486 smooth_neighbor,
4487 pred,
4488 fctx,
4489 );
4490 }
4491}
4492
4493/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4494#[allow(clippy::too_many_arguments)]
4495fn exec_mc(
4496 y: &mut PlaneBuf<'static>,
4497 u: &mut PlaneBuf<'static>,
4498 v: &mut PlaneBuf<'static>,
4499 plane: usize,
4500 x: usize,
4501 oy: usize,
4502 stride: usize,
4503 w: usize,
4504 h: usize,
4505 prediction: &[u16],
4506 residual: &[i32],
4507 fctx: &crate::decode::FrameCtx,
4508) {
4509 let target: &mut PlaneBuf<'static> = match plane {
4510 0 => &mut *y,
4511 1 => &mut *u,
4512 _ => &mut *v,
4513 };
4514 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
4515}
4516
4517thread_local! {
4518 /// The current frame's `mi` grid, kept only while a frame header set
4519 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4520 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4521 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4522 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4523 /// does not allow intrabc (so nothing is paid for it).
4524 ///
4525 /// corner-cut: only [`decode_block`] (the square path) records into it,
4526 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4527 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4528 /// be wrong there; upgrade = record from the rect/leaf paths too.
4529 /// The block vector [`read_intra_mode`] just decoded, handed to
4530 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4531 /// which the alternative -- a tenth tuple member through every caller --
4532 /// already avoids). Always `.take()`n by the block that reads it.
4533 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4534 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4535 /// returns too, so it counts reads, not reconstructions (a refused block
4536 /// is never reconstructed).
4537 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4538}
4539// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4540// an intrabc block's chroma reads can inherit it (see
4541// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4542// through that one arming site.
4543// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4544// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4545// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4546// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4547// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4548// intrabc block's two chroma [`read_plane`] calls; the type decides the
4549// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4550// -- getting it wrong desyncs the chroma coefficients, it is not a
4551// reconstruction-only detail.
4552
4553/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4554/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4555/// needs no separate plumbing to reach the rect-strip mode reader.
4556fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4557 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4558}
4559
4560thread_local! {
4561 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4562 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4563 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4564 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4565}
4566
4567/// Current value of [`RECT_INTRABC_READS`].
4568pub(crate) fn rect_intrabc_reads() -> usize {
4569 RECT_INTRABC_READS.with(|c| c.get())
4570}
4571
4572/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4573#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4574pub(crate) fn reset_rect_intrabc_reads() {
4575 RECT_INTRABC_READS.with(|c| c.set(0));
4576}
4577
4578thread_local! {
4579 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4580 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4581 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4582}
4583
4584thread_local! {
4585 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4586 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4587 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4588 /// counter: zero means the gate's fixture no longer reaches the route).
4589 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4590 const { std::cell::Cell::new(0) };
4591}
4592
4593/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4595pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4596 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4597}
4598
4599/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4601pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4602 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4603}
4604
4605/// Current value of [`LEAF8_INTRABC_HITS`].
4606pub(crate) fn leaf8_intrabc_hits() -> usize {
4607 LEAF8_INTRABC_HITS.with(|c| c.get())
4608}
4609
4610/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4611#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4612pub(crate) fn reset_leaf8_intrabc_hits() {
4613 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4614}
4615
4616/// Current value of [`INTRABC_HITS`].
4617#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4618pub(crate) fn intrabc_hits() -> usize {
4619 INTRABC_HITS.with(|c| c.get())
4620}
4621
4622thread_local! {
4623 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4624 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4625 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4626 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4627 /// here. A non-zero value is what makes the disarm below load-bearing.
4628 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4629 const { std::cell::Cell::new(0) };
4630}
4631
4632/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4633#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4634pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4635 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4636}
4637
4638/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4639/// decode).
4640#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4641pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4642 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4643}
4644
4645thread_local! {
4646 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4647 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4648 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4649 /// Before the fix this route predicted intra-DC and every one of this
4650 /// fixture's 150 such cells differed from the oracle on both chroma
4651 /// planes.
4652 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4653 const { std::cell::Cell::new(0) };
4654}
4655
4656/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4657#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4658pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4659 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4660}
4661
4662/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4663/// decode).
4664#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4665pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4666 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4667}
4668
4669/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4670#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4671pub(crate) fn reset_intrabc_hits() {
4672 INTRABC_HITS.with(|c| c.set(0));
4673}
4674
4675thread_local! {
4676 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4677 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4678 /// that replaced the refusal "an intrabc block under TxMode::Select".
4679 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4680 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4681 /// sizes (not one square size across every leaf) -- the engagement
4682 /// counter proving a witness actually exercises the per-leaf reconstruct.
4683 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4684 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4685 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4686 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4687 /// symbol here desynced `warped.obu` at the very next block.
4688 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4689 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4690 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4691 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4692 /// this one).
4693 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4694 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4695 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4696 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4697 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4698 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4699 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4700 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4701 /// counts neither orientation nor the skip flag, so an arm that flipped
4702 /// to an all-skip stream (no residual reader at all) would stay green.
4703 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4704 const { std::cell::Cell::new([0, 0]) };
4705 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4706 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4707 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4708 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4709 /// invisible to every gate because they only counted CODED strips.
4710 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4711 const { std::cell::Cell::new([0, 0]) };
4712 /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized
4713 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4714 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no
4715 /// halving of its own. At 4:2:0 this is the same arithmetic as the halving,
4716 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4717 /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's
4718 /// chroma plane block.
4719 static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4720 const { std::cell::Cell::new(0) };
4721 /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block
4722 /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR
4723 /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes
4724 /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block,
4725 /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's
4726 /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a
4727 /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm:
4728 /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot
4729 /// be satisfied by any older route.
4730 static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell<usize> =
4731 const { std::cell::Cell::new(0) };
4732 /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips
4733 /// ([`decode_intrabc_owned_rect`]) whose chroma plane block was sized
4734 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4735 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies
4736 /// no halving of its own. At 4:2:0 the two forms are the same arithmetic,
4737 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4738 /// EXCLUSIVE to this arm: no other caller sizes a 128-root intra-BC
4739 /// strip's chroma plane block.
4740 static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4741 const { std::cell::Cell::new(0) };
4742}
4743
4744/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4745/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4746#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4747pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4748 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4749}
4750
4751/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4752/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4753#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4754pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4755 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4756}
4757
4758/// Current value of [`INTRABC_RECT_HITS`].
4759#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4760pub fn intrabc_rect_hits() -> usize {
4761 INTRABC_RECT_HITS.with(|c| c.get())
4762}
4763
4764/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4765#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4766pub(crate) fn reset_intrabc_rect_hits() {
4767 INTRABC_RECT_HITS.with(|c| c.set(0));
4768 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4769 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4770 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4771}
4772
4773/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4774#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4775pub fn ibc_rect_chroma_footprint_444_hits() -> usize {
4776 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4777}
4778
4779/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4780#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4781pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() {
4782 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4783}
4784
4785/// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4786#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4787pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
4788 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4789}
4790
4791/// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4792#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4793pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
4794 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4795}
4796
4797/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4798#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4799pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
4800 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
4801}
4802
4803/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4804#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4805pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
4806 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
4807}
4808
4809/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4810#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4811pub fn intrabc_rect_vartx_hits() -> usize {
4812 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4813}
4814
4815thread_local! {
4816 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4817 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4818 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4819 /// guard (`decode_block_128rect`). A refused block bumps
4820 /// [`INTRABC_HITS`] but never this one.
4821 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4822 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4823 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4824 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4825 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4826 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4827 /// side` model walked the 4:2:0 count on every axis, so this counter is
4828 /// the reach/arm witness for the per-axis walk.
4829 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4830 const { std::cell::Cell::new(0) };
4831 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4832 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4833 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4834 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4835 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4836 const { std::cell::Cell::new(0) };
4837}
4838
4839/// Current value of [`INTRABC_128RECT_HITS`].
4840#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4841pub fn intrabc_128rect_hits() -> usize {
4842 INTRABC_128RECT_HITS.with(|c| c.get())
4843}
4844
4845/// Zeroes [`INTRABC_128RECT_HITS`].
4846#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4847pub(crate) fn reset_intrabc_128rect_hits() {
4848 INTRABC_128RECT_HITS.with(|c| c.set(0));
4849}
4850
4851/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
4852#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4853pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
4854 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
4855}
4856
4857/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
4858#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4859pub fn intrabc_128rect_chunk_shape() -> usize {
4860 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
4861}
4862
4863/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
4864/// [`INTRABC_128RECT_CHUNK_SHAPE`].
4865#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4866pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
4867 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
4868 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
4869}
4870
4871/// Current value of [`INTRABC_VARTX_HITS`].
4872pub fn intrabc_vartx_hits() -> usize {
4873 INTRABC_VARTX_HITS.with(|c| c.get())
4874}
4875
4876/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4877pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4878 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4879}
4880
4881/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4882#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4883pub(crate) fn reset_intrabc_vartx_hits() {
4884 INTRABC_VARTX_HITS.with(|c| c.set(0));
4885}
4886
4887/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4888/// decode).
4889#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4890pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4891 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4892}
4893
4894/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4895#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4896pub fn rect_intrabc_vartx_hits() -> usize {
4897 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4898}
4899
4900/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4901/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4902/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4903/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4904fn record_intrabc_mi(
4905 mi_r: usize,
4906 mi_c: usize,
4907 n4: usize,
4908 dv: Option<(i32, i32)>,
4909 n: &mut Neighbours,
4910 fctx: &crate::decode::FrameCtx,
4911) {
4912 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4913}
4914
4915/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4916/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4917/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4918///
4919/// Also stamps libaom's `is_inter_block` verdict for this block into the
4920/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4921/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4922/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4923/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4924/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4925/// every block runs; this runs after it (class leaked-band otherwise).
4926fn record_intrabc_mi_rect(
4927 mi_r: usize,
4928 mi_c: usize,
4929 n4_w: usize,
4930 n4_h: usize,
4931 dv: Option<(i32, i32)>,
4932 n: &mut Neighbours,
4933 fctx: &crate::decode::FrameCtx,
4934) {
4935 if dv.is_some() {
4936 for i in 0..n4_w {
4937 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4938 *cell = true;
4939 }
4940 }
4941 for i in 0..n4_h {
4942 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4943 *cell = true;
4944 }
4945 }
4946 }
4947 fctx.intrabc_mi_grid.with(|g| {
4948 let mut g = g.borrow_mut();
4949 let Some((grid, _, _)) = g.as_mut() else {
4950 return;
4951 };
4952 let info = crate::mvstack::MiInfo {
4953 is_inter: dv.is_some(),
4954 ref_frame: 0,
4955 ref_frame1: NO_REF1,
4956 mv: mv16(dv.unwrap_or((0, 0))),
4957 mv1: (0, 0),
4958 is_new_mv: dv.is_some(),
4959 is_global_mv0: false,
4960 is_global_mv1: false,
4961 size: n4_w as u8,
4962 size_h: n4_h as u8,
4963 };
4964 for r in mi_r..mi_r + n4_h {
4965 for c in mi_c..mi_c + n4_w {
4966 grid.set(r, c, info);
4967 }
4968 }
4969 });
4970}
4971
4972// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4973// proves a real `skip_mode_present` stream actually reached a block that
4974// picked it, not just that the frame header bit was set.
4975thread_local! {
4976 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4977 const { std::cell::Cell::new(0) };
4978}
4979
4980/// Current value of [`SKIP_MODE_HITS`].
4981#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4982pub(crate) fn skip_mode_hits() -> usize {
4983 SKIP_MODE_HITS.with(|c| c.get())
4984}
4985
4986// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4987// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4988// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4989// reached [`obmc_blend`], not just the header bit.
4990thread_local! {
4991 static OBMC_HITS: std::cell::Cell<usize> =
4992 const { std::cell::Cell::new(0) };
4993}
4994
4995// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4996// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4997// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4998// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4999// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
5000// decoder used to read with the wrong alphabet, so a gate that asserts this
5001// counter advanced proves the fixed path fired (class
5002// `gate-blind-to-feature`).
5003thread_local! {
5004 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5005}
5006
5007/// Current value of [`FIMV_ALPHABET_HITS`].
5008pub fn fimv_alphabet_hits() -> usize {
5009 FIMV_ALPHABET_HITS.with(|c| c.get())
5010}
5011
5012// lane-fimv r1: how many frame headers this decoder has decoded with
5013// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
5014// prove the encoder really produced the header state under test rather than
5015// assume it.
5016thread_local! {
5017 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5018}
5019
5020/// Current value of [`FIMV_FRAME_HITS`].
5021pub fn fimv_frame_hits() -> usize {
5022 FIMV_FRAME_HITS.with(|c| c.get())
5023}
5024
5025/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
5026/// `force_integer_mv` bit is set.
5027pub fn note_force_integer_mv_frame() {
5028 hit!(FIMV_FRAME_HITS);
5029}
5030
5031/// Current value of [`OBMC_HITS`].
5032#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5033pub(crate) fn obmc_hits() -> usize {
5034 OBMC_HITS.with(|c| c.get())
5035}
5036
5037// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
5038// off the neighbour band -- the positive half of the proof for "an OBMC
5039// neighbour whose switchable interp filter was never recorded". A
5040// fixed-filter frame returns before this point (its neighbours legitimately
5041// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
5042// `interp_filter` symbols were published by `record_inter_rect_mi`.
5043thread_local! {
5044 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5045}
5046
5047/// Current value of [`OBMC_FILTER_BAND_READS`].
5048#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5049pub(crate) fn obmc_filter_band_reads() -> usize {
5050 OBMC_FILTER_BAND_READS.with(|c| c.get())
5051}
5052
5053// lane-scaledref r1: per-case firing counts for the scaled-reference gate
5054// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
5055// reference would pass just as well and prove nothing, so the gate
5056// hard-asserts each combination this round lifts actually occurred:
5057// a compound block with a scaled tap, a warp block whose warp libaom
5058// suppresses because the reference is scaled, an OBMC block, an interintra
5059// block, and an 8x8 leaf.
5060thread_local! {
5061 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5062 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5063 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5064 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5065 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5066 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5067 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5068}
5069
5070/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5071/// scaled and one unscaled tap.
5072#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5073pub(crate) fn mixed_scale_compound_hits() -> usize {
5074 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5075}
5076
5077/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5078/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5079/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5080/// `blockd.h:1484`).
5081#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5082pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5083 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5084}
5085
5086/// Current value of [`SCALED_COMPOUND_HITS`].
5087#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5088pub(crate) fn scaled_compound_hits() -> usize {
5089 SCALED_COMPOUND_HITS.with(|c| c.get())
5090}
5091
5092/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5093pub fn scaled_warp_fallback_hits() -> usize {
5094 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5095}
5096
5097/// Current value of [`SCALED_OBMC_HITS`].
5098#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5099pub(crate) fn scaled_obmc_hits() -> usize {
5100 SCALED_OBMC_HITS.with(|c| c.get())
5101}
5102
5103/// Current value of [`SCALED_INTERINTRA_HITS`].
5104#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5105pub(crate) fn scaled_interintra_hits() -> usize {
5106 SCALED_INTERINTRA_HITS.with(|c| c.get())
5107}
5108
5109/// Current value of [`SCALED_BLOCK8_HITS`].
5110#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5111pub(crate) fn scaled_block8_hits() -> usize {
5112 SCALED_BLOCK8_HITS.with(|c| c.get())
5113}
5114
5115// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5116// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5117// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5118// 8x8-leaf OBMC block apart from a 16x16+ one.
5119thread_local! {
5120 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5121}
5122
5123// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5124// pair whose two directions differ (`enable_dual_filter` only -- with dual
5125// filter off both directions take the single symbol, so this can never fire).
5126// A gate asserting it proves the stream really carries dual-filter blocks.
5127thread_local! {
5128 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5129}
5130
5131// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5132// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5133// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5134// no-filter sentinel that made a neighbouring OBMC block panic).
5135thread_local! {
5136 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5137}
5138
5139/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5140#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5141pub(crate) fn dual_filter_diff_hits() -> usize {
5142 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5143}
5144
5145/// Current value of [`COMPOUND8_FILTER_HITS`].
5146#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5147pub(crate) fn compound8_filter_hits() -> usize {
5148 COMPOUND8_FILTER_HITS.with(|c| c.get())
5149}
5150
5151// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5152// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5153// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5154// -- the gate's proof that a fixture really exercises the alphabet this
5155// round changed, even though the block itself still refuses (warp
5156// estimation/filter not ported).
5157thread_local! {
5158 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5159 const { std::cell::Cell::new(0) };
5160}
5161
5162/// Current value of [`WARP_SELECTED_HITS`].
5163#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5164pub(crate) fn warp_selected_hits() -> usize {
5165 WARP_SELECTED_HITS.with(|c| c.get())
5166}
5167
5168// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5169// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5170// into the compound intermediate) rather than translationally -- the
5171// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5172// really reached [`crate::warp::warp_affine_compound`].
5173// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5174// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5175// counter is frame-global. These two are the same arms restricted to blocks
5176// whose top mode-info row is in the frame's upper half, which is the half
5177// this lane's evidence covers.
5178thread_local! {
5179 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5180 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5181}
5182
5183/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5184/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5185///
5186/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5187/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5188/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5189/// The figure quoted for that fixture comes from a patch-run-restore build
5190/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5191/// is the same discipline every 4:2:2 lane in this family uses.
5192#[allow(dead_code)]
5193pub(crate) fn top_half_compound_hits() -> usize {
5194 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5195}
5196
5197/// How many inter blocks in the frame's upper half satisfy libaom's
5198/// `is_global_mv_block` on at least one reference slot -- mode
5199/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5200/// model > `TRANSLATION`. This is the block set whose prediction goes
5201/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5202/// as computed at the increment site; it is NOT merely "some slot has a
5203/// non-TRANSLATION model", which also counts blocks that are not global-mv
5204/// blocks.
5205///
5206/// Like [`top_half_compound_hits`], no committed test reads it: with the
5207/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5208/// these numbers describe.
5209#[allow(dead_code)]
5210pub(crate) fn top_half_warp_hits() -> usize {
5211 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5212}
5213
5214thread_local! {
5215 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5216 const { std::cell::Cell::new(0) };
5217}
5218
5219/// Current value of [`COMPOUND_WARP_HITS`].
5220#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5221pub(crate) fn compound_warp_hits() -> usize {
5222 COMPOUND_WARP_HITS.with(|c| c.get())
5223}
5224
5225// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5226// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5227// translationally until r3, so a gate needs to tell a warped 8x8 compound
5228// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5229thread_local! {
5230 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5231 const { std::cell::Cell::new(0) };
5232}
5233
5234/// Current value of [`COMPOUND_WARP_HITS_8`].
5235#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5236pub(crate) fn compound_warp_hits_8() -> usize {
5237 COMPOUND_WARP_HITS_8.with(|c| c.get())
5238}
5239
5240// lane-gmaffine r1: how many blocks built their prediction from a
5241// SIX-parameter (`AFFINE`) global-motion model through
5242// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5243// carried an AFFINE `global_motion_params` AND that a block was predicted
5244// with it, not merely that the header parsed one.
5245thread_local! {
5246 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5247 const { std::cell::Cell::new(0) };
5248}
5249
5250/// Current value of [`AFFINE_GM_HITS`].
5251#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5252pub(crate) fn affine_gm_hits() -> usize {
5253 AFFINE_GM_HITS.with(|c| c.get())
5254}
5255
5256// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5257// combine rather than the simple average -- `compound_idx == 0` under
5258// `enable_jnt_comp`, whose weights come from
5259// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5260// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5261// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5262// stream that carries `enable_jnt_comp = true` in its sequence header but
5263// codes every compound block with `compound_idx == 1` leaves this at 0 and
5264// decoded identically without the whole distance-weight path.
5265thread_local! {
5266 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5267 const { std::cell::Cell::new(0) };
5268}
5269
5270/// Current value of [`DIST_WTD_COMP_HITS`].
5271#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5272pub(crate) fn dist_wtd_comp_hits() -> usize {
5273 DIST_WTD_COMP_HITS.with(|c| c.get())
5274}
5275
5276/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5277#[allow(dead_code)] // test-only
5278pub(crate) fn reset_dist_wtd_comp_hits() {
5279 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5280}
5281
5282// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5283// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5284// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5285// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5286// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5287// side build and its own counter, [`AFFINE_GM_HITS`]).
5288thread_local! {
5289 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5290 const { std::cell::Cell::new(0) };
5291}
5292
5293/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5294#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5295pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5296 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5297}
5298
5299// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5300// differently at the block's WIDTH than at libaom's
5301// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5302// pick the wrong motion_mode alphabet.
5303thread_local! {
5304 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5305}
5306
5307/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5308pub fn tr_reach_longer_side_hits() -> usize {
5309 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5310}
5311
5312// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5313// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5314// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5315// reads its interp-filter symbol. Counts the blocks where that guard flips
5316// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5317// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5318// entropy desync one symbol wide).
5319thread_local! {
5320 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5321}
5322
5323/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5324pub fn gm_nontrans_small_side_hits() -> usize {
5325 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5326}
5327
5328// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5329// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5330// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5331// only once `find_projection` returned a usable model, unlike
5332// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5333// proof that the leaf path itself fired, not the 16x16+ one.
5334thread_local! {
5335 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5336 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5337}
5338
5339/// Current value of [`GLOBALMV_HITS_8`].
5340#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5341pub(crate) fn globalmv_hits_8() -> usize {
5342 GLOBALMV_HITS_8.with(|c| c.get())
5343}
5344
5345/// Current value of [`WARP_HITS_8`].
5346#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5347pub(crate) fn warp_hits_8() -> usize {
5348 WARP_HITS_8.with(|c| c.get())
5349}
5350
5351// How many blocks decoded `interintra == 1` with the non-wedge blended
5352// prediction applied (lane-interintra r1) -- the gate's proof that a
5353// stream actually exercised interintra.
5354thread_local! {
5355 static INTERINTRA_HITS: std::cell::Cell<usize> =
5356 const { std::cell::Cell::new(0) };
5357}
5358
5359/// Current value of [`INTERINTRA_HITS`].
5360#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5361pub(crate) fn interintra_hits() -> usize {
5362 INTERINTRA_HITS.with(|c| c.get())
5363}
5364
5365// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5366// -- the shape `interintra_blend` used to build a square `side x side` intra
5367// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5368// pre-existing interintra gate passed with that bug, so the rect arm needs
5369// its own counter to stop being vacuous.
5370thread_local! {
5371 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5372}
5373
5374/// Current value of [`INTERINTRA_RECT_HITS`].
5375pub fn interintra_rect_hits() -> usize {
5376 INTERINTRA_RECT_HITS.with(|c| c.get())
5377}
5378
5379// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5380// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5381// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5382// gate fixture actually exercises this alphabet, even though the block
5383// still refuses (the mask blend itself is unported).
5384thread_local! {
5385 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5386 const { std::cell::Cell::new(0) };
5387}
5388
5389/// Current value of [`MASKED_COMPOUND_HITS`].
5390#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5391pub(crate) fn masked_compound_hits() -> usize {
5392 MASKED_COMPOUND_HITS.with(|c| c.get())
5393}
5394
5395// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5396// masked-compound block whose true footprint is rectangular, i.e. the case
5397// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5398// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5399// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5400thread_local! {
5401 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5402 const { std::cell::Cell::new(0) };
5403}
5404
5405/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5406#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5407pub(crate) fn rect_masked_compound_hits() -> usize {
5408 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5409}
5410
5411// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5412// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5413// actually exercised the wedge blend, not just the DIFFWTD half of
5414// `MASKED_COMPOUND_HITS`.
5415thread_local! {
5416 static WEDGE_HITS: std::cell::Cell<usize> =
5417 const { std::cell::Cell::new(0) };
5418}
5419
5420/// Current value of [`WEDGE_HITS`].
5421#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5422pub(crate) fn wedge_hits() -> usize {
5423 WEDGE_HITS.with(|c| c.get())
5424}
5425
5426// How many blocks decoded a real wedge-INTERINTRA block
5427// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5428// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5429// smooth arm counted by `INTERINTRA_HITS`.
5430thread_local! {
5431 static WII_HITS: std::cell::Cell<usize> =
5432 const { std::cell::Cell::new(0) };
5433}
5434
5435/// Current value of [`WII_HITS`].
5436#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5437pub(crate) fn wii_hits() -> usize {
5438 WII_HITS.with(|c| c.get())
5439}
5440
5441// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5442// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5443// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5444// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5445// frame carrying one.
5446thread_local! {
5447 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5448}
5449
5450/// Current value of [`NOCFL_UV_MODE_HITS`].
5451#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5452pub(crate) fn nocfl_uv_mode_hits() -> usize {
5453 NOCFL_UV_MODE_HITS.with(|c| c.get())
5454}
5455
5456/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5457/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5458pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5459 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5460
5461fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5462 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5463}
5464
5465// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5466// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5467// the rect wedge masks lifted this round actually fired, not just the square
5468// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5469thread_local! {
5470 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5471 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5472}
5473
5474/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5475pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5476 RECT_WEDGE_HITS.with(|c| c.get())
5477}
5478
5479/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5480pub(crate) fn rect_wii_hits() -> [usize; 6] {
5481 RECT_WII_HITS.with(|c| c.get())
5482}
5483
5484// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5485// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5486// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5487// aomdec, neighbour list included).
5488thread_local! {
5489 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5490}
5491
5492/// Current value of [`OBMC_RECT_LEAF_HITS`].
5493pub(crate) fn obmc_rect_leaf_hits() -> usize {
5494 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5495}
5496
5497// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5498// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5499// to be read from the pair's FIRST mi, which is a different block and, when
5500// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5501// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5502thread_local! {
5503 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5504}
5505
5506/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5507pub(crate) fn obmc_pair_filter_hits() -> usize {
5508 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5509}
5510
5511// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5512// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5513// own side, so a block overhanging the bottom/right still predicts the full
5514// neighbour strip (the destination write is what clips). We used to shrink the
5515// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5516// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5517thread_local! {
5518 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5519}
5520
5521/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5522#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5523pub(crate) fn obmc_edge_span_hits() -> usize {
5524 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5525}
5526
5527/// Current value of [`OBMC_HITS_8`].
5528#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5529pub(crate) fn obmc_hits_8() -> usize {
5530 OBMC_HITS_8.with(|c| c.get())
5531}
5532
5533// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5534// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5535// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5536// `VERT_B` all still fall into the generic "a partition type this encoder
5537// never writes" refusal below) -- the gate's proof that a free-partition
5538// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5539// coincidentally never selecting one.
5540thread_local! {
5541 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5542 const { std::cell::Cell::new(0) };
5543}
5544
5545/// Current value of [`EXTENDED_PARTITION_HITS`].
5546#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5547pub(crate) fn extended_partition_hits() -> usize {
5548 EXTENDED_PARTITION_HITS.with(|c| c.get())
5549}
5550
5551// lane-partitions r1: how many 32x32 quadrants decoded a real
5552// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5553// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5554// gate's proof this round's arms actually fired.
5555thread_local! {
5556 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5557 const { std::cell::Cell::new(0) };
5558}
5559
5560/// Current value of [`RECT_PARTITION_HITS`].
5561#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5562pub(crate) fn rect_partition_hits() -> usize {
5563 RECT_PARTITION_HITS.with(|c| c.get())
5564}
5565
5566// lane-inter8 r1: how many superblocks an inter tile coded as a single
5567// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5568// static content, previously a named refusal).
5569thread_local! {
5570 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5571 /// path decoded as one whole block (its gate's own witness).
5572 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5573 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5574 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5575 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5576}
5577
5578/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5579pub(crate) fn inter_sb128_horz_hits() -> usize {
5580 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5581}
5582
5583/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5584pub(crate) fn inter_sb128_vert_hits() -> usize {
5585 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5586}
5587
5588/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5589pub fn inter_sb128_none_hits() -> usize {
5590 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5591}
5592
5593thread_local! {
5594 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5595 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5596 /// units) -- the gate's witness that the lifted refusal's case fired.
5597 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5598}
5599
5600/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5601pub fn intra_128_in_inter_hits() -> usize {
5602 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5603}
5604
5605thread_local! {
5606 /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the
5607 /// intra-in-inter 128x128 root read (`decode_inter_block`'s
5608 /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every
5609 /// unit is one `read_plane` on U and one on V, so the counter is the
5610 /// gate's proof the arm ran at all -- no committed 4:4:4 fixture
5611 /// reached it before this lane.
5612 pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell<usize> =
5613 const { std::cell::Cell::new(0) };
5614}
5615
5616/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's
5617/// before/after delta.
5618pub fn intra_128_in_inter_mu_chroma_hits() -> usize {
5619 INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get)
5620}
5621
5622thread_local! {
5623 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5624 const { std::cell::Cell::new(0) };
5625}
5626
5627/// Current value of [`INTER_SB_NONE_HITS`].
5628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5629pub(crate) fn inter_sb_none_hits() -> usize {
5630 INTER_SB_NONE_HITS.with(|c| c.get())
5631}
5632
5633// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5634// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5635// path has always run that loop, so only this counter proves the newly-lifted
5636// alphabet value fired.
5637thread_local! {
5638 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5639 const { std::cell::Cell::new(0) };
5640}
5641
5642/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5643#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5644pub(crate) fn inter_sub16_split_hits() -> usize {
5645 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5646}
5647
5648// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5649// while at least one reference picture was SCALED (superres) -- the counter
5650// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5651thread_local! {
5652 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5653 const { std::cell::Cell::new(0) };
5654}
5655
5656/// Current value of [`SCALED_LEAF8_HITS`].
5657pub fn scaled_leaf8_hits() -> usize {
5658 SCALED_LEAF8_HITS.with(|c| c.get())
5659}
5660
5661// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5662// rect pair) were predicted from a SCALED reference -- the counter behind the
5663// lifted "sub-8x8 inter block under a scaled reference" refusal.
5664thread_local! {
5665 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5666 const { std::cell::Cell::new(0) };
5667}
5668
5669/// Current value of [`SCALED_SUB8_HITS`].
5670pub fn scaled_sub8_hits() -> usize {
5671 SCALED_SUB8_HITS.with(|c| c.get())
5672}
5673
5674// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5675// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5676// rect coefficient reader itself fired, not just the strip-level partition
5677// symbol [`RECT_PARTITION_HITS`] already counts.
5678thread_local! {
5679 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5680 const { std::cell::Cell::new(0) };
5681}
5682
5683/// Current value of [`RECT_COEFF_HITS`].
5684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5685pub(crate) fn rect_coeff_hits() -> usize {
5686 RECT_COEFF_HITS.with(|c| c.get())
5687}
5688
5689// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5690// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5691// charter's real-aomenc gate hard-asserts.
5692thread_local! {
5693 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5694 const { std::cell::Cell::new(0) };
5695}
5696
5697/// Current value of [`RECT_LEAF_COEFF_HITS`].
5698#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5699pub(crate) fn rect_leaf_coeff_hits() -> usize {
5700 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5701}
5702
5703// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5704// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5705// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5706// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5707// needs rectangular intra prediction" before this round.
5708thread_local! {
5709 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5710 const { std::cell::Cell::new([0; 3]) };
5711}
5712
5713/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5714/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5715#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5716pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5717 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5718}
5719
5720// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5721// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5722// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5723// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5724// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5725// a single counter cannot tell an axis swap from a working arm
5726// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5727thread_local! {
5728 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5729 const { std::cell::Cell::new([0; 2]) };
5730}
5731
5732/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5733/// (0 = 64x32, 1 = 32x64).
5734pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5735 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5736}
5737
5738// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5739// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5740// is never incremented) -- the gate's proof that the lifted path ran per depth.
5741thread_local! {
5742 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5743 const { std::cell::Cell::new([0; 3]) };
5744}
5745
5746// lane-t900 r21: rect intra strips inside an inter frame that read the
5747// screen-content palette syntax (`allow_screen_content_tools` set and the
5748// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5749// refusal used to guard, so this counter is what keeps its witness gate
5750// non-vacuous.
5751thread_local! {
5752 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5753}
5754
5755/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5756#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5757pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5758 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5759}
5760
5761/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5762#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5763pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5764 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5765}
5766
5767/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5768#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5769pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5770 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5771}
5772
5773// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5774// approximation would have resolved off a DIFFERENT CDF row than the real
5775// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5776// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5777// tally is green on the old code too (class gate-blind-to-feature).
5778thread_local! {
5779 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5780 const { std::cell::Cell::new(0) };
5781}
5782
5783/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5784#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5785pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5786 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5787}
5788
5789// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5790// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5791// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5792// rect strip on the inter block path" before this round.
5793thread_local! {
5794 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5795 const { std::cell::Cell::new([0; 4]) };
5796}
5797
5798/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5799/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5800pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5801 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5802}
5803
5804// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5805// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5806// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5807// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5808// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
5809// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
5810// REACH only, never that the fix bites -- that is the gate's byte compare and
5811// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
5812thread_local! {
5813 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5814}
5815
5816/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5817#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5818pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5819 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5820}
5821
5822/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
5823#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5824pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
5825 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
5826}
5827
5828// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
5829// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
5830// stream of the same recipe leaves it at 0, which is what makes it the
5831// 4:4:4-only route.
5832//
5833// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
5834// never was. A route counter fires identically before and after a change that
5835// changes nothing downstream, so a non-zero count proves REACH and nothing
5836// more. On this lane it is also armed deliberately OUTSIDE the `own444`
5837// expression, so that the mutation (`own444 = false`) still increments it and
5838// the red comes from the pixel/entropy arm instead. The evidence that the ss
5839// gate bites is the measured fork move -- first entropy fork read 11750 ->
5840// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
5841// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
5842// a DIFFERS-style assertion to carry a claim.
5843thread_local! {
5844 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5845}
5846
5847/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
5848#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5849pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
5850 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5851}
5852
5853/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
5854#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5855pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
5856 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
5857}
5858
5859// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
5860// through one of the key-frame rect readers ([`decode_block_rect4`],
5861// [`decode_block_rect64`]). `Some((size_group, skip))` tells
5862// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
5863// already read by [`decode_inter_block`] and (b) the luma mode comes off
5864// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
5865// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
5866
5867// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
5868// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
5869// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
5870// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
5871thread_local! {
5872 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5873 const { std::cell::Cell::new(0) };
5874}
5875
5876/// Current value of [`MODE_MI_OVERRIDE_HITS`].
5877#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5878pub(crate) fn mode_mi_override_hits() -> usize {
5879 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5880}
5881
5882// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
5883// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
5884// mode from the previous tile, where libaom's `up_available`/`left_available`
5885// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
5886// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
5887// per superblock row in `start_row`, so the luma fallback cannot leak the way
5888// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
5889// the invariant that makes the coarse fallback safe.
5890thread_local! {
5891 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
5892 const { std::cell::Cell::new(0) };
5893}
5894
5895/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
5896#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5897pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
5898 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
5899}
5900
5901// lane-cfl r1: how many times a chroma intra-edge filter-type read
5902// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
5903// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
5904// r1 defect would have filtered a chroma edge with the wrong strength.
5905thread_local! {
5906 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5907 const { std::cell::Cell::new(0) };
5908}
5909
5910/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
5911#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5912pub(crate) fn uv_mode_mi_override_hits() -> usize {
5913 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5914}
5915
5916// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
5917// `uv_mode` from the mi GRID where the one-slot-per-column map would have
5918// answered differently -- the sub-8x8 pair case where the pair's own first
5919// half had already overwritten the column slot the chroma-ref half reads.
5920thread_local! {
5921 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
5922 const { std::cell::Cell::new(0) };
5923}
5924
5925/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
5926pub fn uv_mode_grid_override_hits() -> usize {
5927 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
5928}
5929
5930// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
5931// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
5932// from an earlier block in that pixel row/column while the mi-exact map --
5933// which an inter block only started writing this round -- correctly says the
5934// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
5935// an INTER mode, and its `uv_mode` "is not set for inter blocks").
5936thread_local! {
5937 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
5938 const { std::cell::Cell::new(0) };
5939}
5940
5941/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
5942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5943pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
5944 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
5945}
5946
5947// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
5948// suppressed at a TILE edge that is not a frame edge -- the above/left
5949// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
5950// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
5951// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
5952// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
5953// above would decide this tile's chroma edge filter strength.
5954thread_local! {
5955 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
5956 const { std::cell::Cell::new(0) };
5957}
5958
5959/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
5960#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5961pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
5962 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
5963}
5964
5965// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
5966// left neighbour whose `uv_mode` at libaom's real read cell
5967// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
5968// cell this decoder used to read (its own mi row). Two buckets: the raw mode
5969// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
5970// flipped. The second is the one that can move pixels.
5971thread_local! {
5972 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
5973 const { std::cell::Cell::new(0) };
5974 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
5975 const { std::cell::Cell::new(0) };
5976}
5977thread_local! {
5978 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5979}
5980
5981/// Current value of [`UV_LEFT_SS_Y_READS`].
5982pub fn uv_left_ss_y_reads() -> usize {
5983 UV_LEFT_SS_Y_READS.with(|c| c.get())
5984}
5985
5986/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
5987pub fn uv_left_ss_y_mode_diff_hits() -> usize {
5988 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
5989}
5990
5991/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
5992pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
5993 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
5994}
5995
5996// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
5997// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
5998// decoder reads (its own mi row) and the cell libaom reads (one row down)
5999// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
6000// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
6001// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
6002thread_local! {
6003 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6004}
6005
6006/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
6007pub fn uv_left_1mi_split_hits() -> usize {
6008 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
6009}
6010
6011// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
6012// Bumped in `Neighbours::start_tile`; never read by decode logic.
6013thread_local! {
6014 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
6015}
6016
6017// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
6018// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
6019// shapes the r1 chroma defect showed up on.
6020thread_local! {
6021 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6022 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6023}
6024// lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4
6025// arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample)
6026// and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two
6027// reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability
6028// evidence for that function's format-blind extent.
6029thread_local! {
6030 static CFL_AC_444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6031 static CFL_AC_422_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6032 static CFL_AC_420_SQ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6033 static CFL_AC_420_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6034 static CFL_AC_Q3_AT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6035}
6036
6037/// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits.
6038pub fn cfl_ac_arm_hits() -> [usize; 4] {
6039 [
6040 CFL_AC_444_HITS.with(|c| c.get()),
6041 CFL_AC_422_HITS.with(|c| c.get()),
6042 CFL_AC_420_SQ_HITS.with(|c| c.get()),
6043 CFL_AC_420_RECT_HITS.with(|c| c.get()),
6044 ]
6045}
6046
6047/// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is
6048/// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate
6049/// proves it is reached ONLY at 4:2:0.
6050pub fn cfl_ac_q3_at_hits() -> usize {
6051 CFL_AC_Q3_AT_HITS.with(|c| c.get())
6052}
6053
6054/// Current value of [`CFL_BLOCK_HITS`].
6055#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6056pub(crate) fn cfl_block_hits() -> usize {
6057 CFL_BLOCK_HITS.with(|c| c.get())
6058}
6059
6060/// Current value of [`UV_ANGLE_DELTA_HITS`].
6061#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6062pub(crate) fn uv_angle_delta_hits() -> usize {
6063 UV_ANGLE_DELTA_HITS.with(|c| c.get())
6064}
6065
6066// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
6067// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
6068// gate's proof this round's arms actually reached a real block, not just
6069// that `partition_w64` read one of those two symbol values.
6070thread_local! {
6071 static SB_RECT_HITS: std::cell::Cell<usize> =
6072 const { std::cell::Cell::new(0) };
6073}
6074
6075// Current value of [`SB_RECT_HITS`].
6076// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
6077// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
6078// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
6079// non-SPLIT edge arm actually decoded (before this round the bit was read and
6080// thrown away, so that arm was unreachable).
6081thread_local! {
6082 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6083}
6084
6085/// Current value of [`EDGE_PART_HITS`].
6086#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6087pub(crate) fn edge_part_hits() -> [usize; 4] {
6088 EDGE_PART_HITS.with(|c| c.get())
6089}
6090
6091/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
6092#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6093pub(crate) fn reset_edge_part_hits() {
6094 EDGE_PART_HITS.with(|c| c.set([0; 4]));
6095}
6096
6097fn bump_edge_part(slot: usize) {
6098 hit_do! {
6099 EDGE_PART_HITS.with(|c| {
6100 let mut h = c.get();
6101 h[slot] += 1;
6102 c.set(h);
6103 });
6104 }
6105}
6106
6107#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6108pub(crate) fn sb_rect_hits() -> usize {
6109 SB_RECT_HITS.with(|c| c.get())
6110}
6111
6112// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
6113// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
6114// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
6115// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6116// paths (intra and inter) feed the same counter.
6117//
6118// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6119// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6120// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6121// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6122// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6123// every SB of the last row), so the 32-level slots stay 0 on that content and
6124// only these prove the arm fired.
6125thread_local! {
6126 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6127 const { std::cell::Cell::new([0; 8]) };
6128}
6129
6130/// Current value of [`EDGE32_HITS`].
6131#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6132pub(crate) fn edge32_hits() -> [usize; 8] {
6133 EDGE32_HITS.with(|c| c.get())
6134}
6135
6136/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6137/// reads are `if`-conditions, so the counter has to ride the expression.
6138fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6139 bump_edge32(base + bit.min(1));
6140 bit
6141}
6142
6143fn bump_edge32(slot: usize) {
6144 hit_do! {
6145 EDGE32_HITS.with(|c| {
6146 let mut h = c.get();
6147 h[slot] += 1;
6148 c.set(h)
6149 });
6150 }
6151}
6152
6153// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6154// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6155// strip) fired. Real aomenc picks these at 64 even with
6156// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6157// the counter the gate hard-asserts.
6158thread_local! {
6159 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6160 const { std::cell::Cell::new([0; 4]) };
6161}
6162
6163/// Current value of [`SB_AB_HITS`], summed over the four arms.
6164#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6165pub(crate) fn sb_ab_hits() -> usize {
6166 SB_AB_HITS.with(|c| c.get().iter().sum())
6167}
6168
6169/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6170/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6171/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6172/// proof of all four.
6173#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6174pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6175 SB_AB_HITS.with(std::cell::Cell::get)
6176}
6177
6178// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6179// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6180// strips). Two counters, not one, because a gate that only proved "some 1:4
6181// strip fired" would pass on a stream that never coded the other axis, and
6182// every scan/context table this round added comes in a transposed pair.
6183thread_local! {
6184 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6185 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6186}
6187
6188/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6189#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6190pub(crate) fn sb_rect4_horz_hits() -> usize {
6191 SB_RECT4_HORZ_HITS.with(|c| c.get())
6192}
6193
6194/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6195#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6196pub(crate) fn sb_rect4_vert_hits() -> usize {
6197 SB_RECT4_VERT_HITS.with(|c| c.get())
6198}
6199
6200// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6201// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6202// strips), the arms the ReelB mid-film extract stops at.
6203thread_local! {
6204 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6205 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6206 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6207 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6208 /// `PARTITION_VERT_4`.
6209 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6210 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6211 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6212 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6213 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6214 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6215 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6216 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6217}
6218
6219// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6220// a gate that only counted strips would pass on an all-skip stream, which
6221// exercises none of the new scan/context tables.
6222thread_local! {
6223 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6224}
6225
6226// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6227// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6228// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6229// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6230// counts the same for a 16x8/8x16 strip below 16x16.
6231thread_local! {
6232 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6233 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6234 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6235}
6236
6237/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6238#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6239pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6240 (
6241 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6242 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6243 )
6244}
6245
6246/// Current value of `SUB16_SPLIT_HITS`.
6247#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6248pub(crate) fn sub16_split_hits() -> usize {
6249 SUB16_SPLIT_HITS.with(|c| c.get())
6250}
6251
6252// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6253// luma transform is SPLIT and which therefore leave through that fn's early
6254// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6255thread_local! {
6256 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6257}
6258
6259/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6260#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6261pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6262 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6263}
6264
6265/// Current value of `RECT4_COEFF_HITS`.
6266pub(crate) fn rect4_coeff_hits() -> usize {
6267 RECT4_COEFF_HITS.with(|c| c.get())
6268}
6269
6270// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6271// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6272// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6273// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6274// asserts the arms it proves separately so a run whose RD only picked one
6275// cannot pass as proof of the others.
6276thread_local! {
6277 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6278}
6279
6280/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6281/// inter frame).
6282pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6283 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6284}
6285
6286// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6287// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6288// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6289// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6290// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6291// arm separately so a run whose RD only picked one cannot pass as proof of
6292// four.
6293thread_local! {
6294 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6295}
6296
6297/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6298/// inter frame).
6299pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6300 AB16_INTER_HITS.with(std::cell::Cell::get)
6301}
6302
6303// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6304// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6305// counts the odd strips that close a 4:2:0 chroma pair
6306// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6307// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6308// the PREVIOUS strip's own mv/ref/filters -- libaom
6309// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6310// through `is_sub8x8_inter` (same file, :54).
6311thread_local! {
6312 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6313 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6314 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6315 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6316}
6317
6318// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6319// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6320// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6321thread_local! {
6322 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6323 const { std::cell::Cell::new([0; 3]) };
6324}
6325
6326/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6327/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6328pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6329 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6330 (v[0], v[1], v[2])
6331}
6332
6333/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6334/// strips, chroma pairs closed, chroma pairs built from two different
6335/// strips' motion vectors)`.
6336pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6337 (
6338 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6339 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6340 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6341 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6342 )
6343}
6344
6345/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6346/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6347/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6348/// that all mean "an ordinary block, chroma of its own".
6349#[derive(Clone, Copy)]
6350pub(crate) struct InterStripChroma {
6351 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6352 /// read and reconstruct NO chroma at all.
6353 has_chroma: bool,
6354 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6355 horz: bool,
6356 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6357 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6358 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6359 pair_mi: (usize, usize),
6360 /// The previous (even) strip's single-reference MC parameters, `None`
6361 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6362 /// and the whole chroma block is predicted from THIS strip's mv.
6363 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6364}
6365
6366/// The single-reference MC parameters of the inter block that decoded
6367/// last -- read by the next 1:4 strip to build its pair's chroma.
6368
6369fn bump_ab16_inter(arm: usize) {
6370 hit_do! {
6371 AB16_INTER_HITS.with(|c| {
6372 let mut v = c.get();
6373 v[arm] += 1;
6374 c.set(v);
6375 });
6376 }
6377}
6378
6379// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6380// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6381// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6382thread_local! {
6383 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6384 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6385 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6386 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6387 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6388 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6389 /// base mi differs from what the strip's own (odd) mi would have said --
6390 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6391 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6392 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6393 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6394 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6395 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6396 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6397 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6398 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6399 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6400 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6401 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6402 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6403 /// block overhanging the frame does NOT code.
6404 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6405 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6406 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6407 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6408 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6409 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6410 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6411 /// hardcoded 4:2:0 span mis-stepped).
6412 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6413 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6414 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6415 /// that replaced the single rect unit).
6416 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6417 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6418 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6419 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6420 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6421 /// units whose libaom-faithful block-relative reach
6422 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6423 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6424 /// no stream reached a rect leaf where the two disagree -- a gate
6425 /// asserting the reach fix must see this nonzero, or the fixture never
6426 /// exercised the fixed path.
6427 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6428}
6429
6430/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6431/// that reconstructed as flat DC before lane-kf1200 r2).
6432pub fn skip_cfl_hits() -> usize {
6433 SKIP_CFL_HITS.with(|c| c.get())
6434}
6435
6436/// How many chroma transform units the frame-edge clip skipped in
6437/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6438/// stream whose lossless blocks never overhang the frame -- a gate asserting
6439/// the clip fired must see this nonzero.
6440pub fn chroma_edge_tu_clip_hits() -> usize {
6441 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6442}
6443
6444/// How many skipped lossless intrabc rect strips had their luma entropy
6445/// bands zeroed per unit (lane-av1-loss64).
6446pub fn skip_lossless_band_reset_hits() -> usize {
6447 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6448}
6449
6450/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6451/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6452/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6453/// must see this nonzero.
6454pub fn rect_split_lossless_chroma444_hits() -> usize {
6455 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6456}
6457
6458/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6459/// per-4x4 inter units (lane-av1-ibc444rect).
6460pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6461 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6462}
6463
6464/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6465/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6466pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6467 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6468}
6469
6470/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6471/// block-relative reach libaom's `has_bottom_left` gives, where the
6472/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6473/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6474pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6475 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6476}
6477
6478/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6479pub fn reset_sub8_chroma444_tu_reach_hits() {
6480 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6481}
6482
6483/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6484pub fn reset_ibc444rect_hits() {
6485 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6486 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6487}
6488
6489/// Gate-side reset for the two lane-av1-loss64 counters above.
6490pub fn reset_loss64_hits() {
6491 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6492 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6493}
6494
6495/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6496/// from the pair's base mi than the strip's own mi would have given.
6497pub fn rect4_16_uv_pair_filt_hits() -> usize {
6498 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6499}
6500
6501/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6502pub fn rect4_16_lossless_chroma_hits() -> usize {
6503 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6504}
6505
6506/// How many 16x4/4x16 strips reconstructed as intra block copy.
6507pub fn rect4_16_intrabc_hits() -> usize {
6508 RECT4_16_INTRABC_HITS.with(|c| c.get())
6509}
6510
6511/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6512pub fn reset_rect4_16_pair_hits() {
6513 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6514 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6515}
6516
6517// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6518// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6519// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6520// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6521// intra-edge filter type must come from the chroma-reference position).
6522thread_local! {
6523 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6524 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6525}
6526
6527/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6528pub fn reelc_chroma_counters() -> (usize, usize) {
6529 (
6530 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6531 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6532 )
6533}
6534
6535/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6536/// strips, chroma-reference strips, strips with a coded residual, strips
6537/// whose luma transform is split)`.
6538pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6539 (
6540 RECT4_16_HORZ_HITS.with(|c| c.get()),
6541 RECT4_16_VERT_HITS.with(|c| c.get()),
6542 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6543 RECT4_16_COEFF_HITS.with(|c| c.get()),
6544 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6545 )
6546}
6547
6548/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6549pub(crate) fn rect4_32_horz_hits() -> usize {
6550 RECT4_32_HORZ_HITS.with(|c| c.get())
6551}
6552
6553/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6554pub(crate) fn rect4_32_vert_hits() -> usize {
6555 RECT4_32_VERT_HITS.with(|c| c.get())
6556}
6557
6558/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6559pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6560 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6561}
6562
6563/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6564pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6565 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6566}
6567
6568/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6569pub(crate) fn inter_sb_horz_hits() -> usize {
6570 INTER_SB_HORZ_HITS.with(|c| c.get())
6571}
6572
6573/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6574pub(crate) fn inter_sb_vert_hits() -> usize {
6575 INTER_SB_VERT_HITS.with(|c| c.get())
6576}
6577
6578/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6579pub(crate) fn inter_sb_horz4_hits() -> usize {
6580 INTER_SB_HORZ4_HITS.with(|c| c.get())
6581}
6582
6583/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6584pub(crate) fn inter_sb_vert4_hits() -> usize {
6585 INTER_SB_VERT4_HITS.with(|c| c.get())
6586}
6587
6588// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6589// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6590// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6591// just inert-compiled. Zero forever on a passing gate means that gate's
6592// stream never carries `delta_q_present=1` through a rect64 block.
6593thread_local! {
6594 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6595 const { std::cell::Cell::new(0) };
6596}
6597
6598/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6599#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6600pub(crate) fn rect64_qidx_drift_hits() -> usize {
6601 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6602}
6603
6604// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6605// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6606// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6607// free-partition gate's proof this round's arms actually fired.
6608thread_local! {
6609 static PARTAB_HITS: std::cell::Cell<usize> =
6610 const { std::cell::Cell::new(0) };
6611}
6612
6613/// Current value of [`PARTAB_HITS`].
6614#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6615pub(crate) fn partab_hits() -> usize {
6616 PARTAB_HITS.with(|c| c.get())
6617}
6618
6619// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6620// one counter per arm rather than one shared total -- the gate hard-asserts
6621// each of these individually nonzero so a recipe that only ever fires
6622// HORZ_A can't silently stand in for the whole set.
6623thread_local! {
6624 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6625 const { std::cell::Cell::new(0) };
6626 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6627 const { std::cell::Cell::new(0) };
6628 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6629 const { std::cell::Cell::new(0) };
6630 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6631 const { std::cell::Cell::new(0) };
6632}
6633
6634/// Current value of [`INTRA_HORZ_A_HITS`].
6635#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6636pub(crate) fn intra_horz_a_hits() -> usize {
6637 INTRA_HORZ_A_HITS.with(|c| c.get())
6638}
6639/// Current value of [`INTRA_HORZ_B_HITS`].
6640#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6641pub(crate) fn intra_horz_b_hits() -> usize {
6642 INTRA_HORZ_B_HITS.with(|c| c.get())
6643}
6644/// Current value of [`INTRA_VERT_A_HITS`].
6645#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6646pub(crate) fn intra_vert_a_hits() -> usize {
6647 INTRA_VERT_A_HITS.with(|c| c.get())
6648}
6649/// Current value of [`INTRA_VERT_B_HITS`].
6650#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6651pub(crate) fn intra_vert_b_hits() -> usize {
6652 INTRA_VERT_B_HITS.with(|c| c.get())
6653}
6654
6655// How many [`read_inter_compound_mode`] reads actually happened
6656// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6657// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6658// mvstack build), not just that `comp_mode` fired. Still refused right
6659// after (no MV assignment or MC wired), so this only counts attempted
6660// reads.
6661thread_local! {
6662 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6663 const { std::cell::Cell::new(0) };
6664}
6665
6666/// Current value of [`COMPOUND_MODE_HITS`].
6667#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6668pub(crate) fn compound_mode_hits() -> usize {
6669 COMPOUND_MODE_HITS.with(|c| c.get())
6670}
6671
6672/// How many query blocks folded in at least one temporal MV candidate
6673/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6674/// temporal-MV gate's own firing counter (lane-av1tmvp).
6675///
6676/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6677/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6678/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6679/// counter compiles and the projection math it counts is unit-tested
6680/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6681/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6682/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6683/// against any real stream today. See the module doc on
6684/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6685#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6686pub(crate) fn tmv_hits() -> usize {
6687 crate::mvstack::tmv_hits()
6688}
6689
6690/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6691/// produced on this thread, the 10-bit inter gate's firing proof.
6692#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6693pub(crate) fn inter_pred_hits() -> usize {
6694 crate::mc::inter_pred_hits()
6695}
6696
6697/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6698/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6699/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6700/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6701/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6702/// needs to turn a query block's own resolved `ref_frame` into
6703/// `TplArgs::cur_offset_0` (spec 7.9.3).
6704pub(crate) struct TplFrameArgs<'a> {
6705 pub field: &'a crate::motion_field::TplField,
6706 pub order_hint_bits: u32,
6707 pub order_hint: u32,
6708 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6709 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6710 /// frame's own `ref_frame_idx` names for each single reference.
6711 pub ref_order_hints: [u32; 7],
6712}
6713
6714/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6715/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6716/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6717/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6718/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6719/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6720/// cell straddles two different blocks' values.
6721#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6722pub(crate) fn build_motion_field(
6723 grid: &MiGrid,
6724 mi_cols: usize,
6725 mi_rows: usize,
6726 order_hint: u32,
6727 order_hint_bits: u32,
6728 ref_order_hints: [u32; 7],
6729 fctx: &FrameCtx,
6730) -> crate::motion_field::MotionField {
6731 let mut field =
6732 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6733 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6734 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6735 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6736 // referencing one stores only its OTHER side's mv. With
6737 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6738 // nothing is skipped.
6739 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6740 // only on the reference frame, so it is 7 table lookups per frame instead
6741 // of two per inter unit.
6742 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6743 let i = rf.wrapping_sub(LAST_FRAME as usize);
6744 order_hint_bits != 0
6745 && i < 7
6746 && (crate::motion_field::get_relative_dist(
6747 order_hint_bits,
6748 ref_order_hints[i],
6749 order_hint,
6750 ) > 0
6751 || ref_order_hints[i] == order_hint)
6752 });
6753 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6754 // capped at 12 bits per component; a longer one is not stored at all.
6755 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6756 let (cols, rows, cells) = field.cells_mut();
6757 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6758 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6759 // `row` writes cell row `row / 2`).
6760 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6761 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6762 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6763 for col in 0..mi_cols {
6764 let Some(info) = grid.get_frame(row, col) else {
6765 continue;
6766 };
6767 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6768 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6769 // so an intra block -- or an inter block whose every slot is on the
6770 // other side / over the limit -- wipes what an earlier block wrote
6771 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6772 // share a cell).
6773 if !info.is_inter {
6774 out[col / 2] = None;
6775 continue;
6776 }
6777 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6778 // qualifying one wins -- a compound block stores its second
6779 // reference's mv, never its first (unless the second is on the
6780 // other side or over the limit). Storing slot 0 unconditionally
6781 // put the wrong (mv, ref_frame_offset) pair in every compound
6782 // block's cell, which a later frame's temporal candidate then
6783 // projected with the wrong reference distance.
6784 let mut saved: Option<crate::motion_field::SavedMv> = None;
6785 for (rf, mv) in [
6786 (info.ref_frame, Some(mv32(info.mv))),
6787 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6788 ] {
6789 let (Some(mv), true) = (mv, rf > 0) else {
6790 continue;
6791 };
6792 if other_side[rf as usize] {
6793 continue;
6794 }
6795 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6796 continue;
6797 }
6798 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6799 }
6800 out[col / 2] = saved;
6801 }
6802 }
6803 };
6804 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6805 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6806 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6807 let bands = crate::par::bands(rows, crate::par::filter_threads());
6808 if bands.len() <= 1 {
6809 fill(0, rows, cells);
6810 } else {
6811 let shared = crate::par::Shared::new(cells);
6812 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6813 // SAFETY: cell rows `r0..r1` are this band's alone.
6814 let cells = unsafe { shared.get() };
6815 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6816 });
6817 }
6818 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6819 eprintln!("EC_TPL_SAVED oh={order_hint}");
6820 for (r, row) in field.occupancy().iter().enumerate() {
6821 eprintln!("EC_TPL_SAVED r{r} {row}");
6822 }
6823 }
6824 field
6825}
6826
6827/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
6828/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
6829#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6830pub(crate) fn ref_hits(ref_frame: i8) -> usize {
6831 let c = match ref_frame {
6832 LAST2_FRAME => &LAST2_HITS,
6833 LAST3_FRAME => &LAST3_HITS,
6834 GOLDEN_FRAME => &GOLDEN_HITS,
6835 BWDREF_FRAME => &BWDREF_HITS,
6836 ALTREF2_FRAME => &ALTREF2_HITS,
6837 ALTREF_FRAME => &ALTREF_HITS,
6838 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
6839 };
6840 c.with(|v| v.get())
6841}
6842
6843/// The sequence header's `enable_intra_edge_filter`, set once per
6844/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
6845/// own read of it, kept off the call stack (see that function's own doc
6846/// comment for why) rather than threaded through every `read_plane`/
6847/// `decode_block`/`decode_leaf8` call between here and there.
6848
6849/// Set [`ENABLE_EDGE_FILTER`] for this thread.
6850///
6851/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
6852/// never did -- so an inter frame's intra blocks read whatever value the last
6853/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
6854/// harmless (its own key frame sets it first), but a caller that decodes an
6855/// inter frame directly, or a test harness running several streams on one
6856/// thread, inherits a foreign sequence's bit: decode stops being a pure
6857/// function of the bitstream. `decode_stream` now calls this once per stream
6858/// from the sequence header, which covers every frame including inter ones.
6859pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
6860 fctx.enable_edge_filter.with(|f| f.set(value));
6861}
6862
6863/// Current value of [`ANGLE_DELTA_HITS`].
6864#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6865pub(crate) fn angle_delta_hits() -> usize {
6866 ANGLE_DELTA_HITS.with(|c| c.get())
6867}
6868
6869/// Current value of [`TX_CLASS1_HITS`].
6870#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6871pub(crate) fn tx_class1_hits() -> usize {
6872 TX_CLASS1_HITS.with(|c| c.get())
6873}
6874
6875// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
6876// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
6877// bottom) this thread's decode actually reconstructed -- the same
6878// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
6879// genuinely exercised the sub-8x8 leaf path rather than every attempt
6880// coincidentally landing on `PARTITION_NONE`.
6881thread_local! {
6882 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6883 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
6884 /// sub-blocks (lane-intersub8).
6885 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6886 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
6887 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
6888 /// `[1] = VERT` (two BLOCK_4X8).
6889 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
6890 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
6891 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
6892 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
6893 /// MIXED groups whose chroma reference is INTER while its sibling is
6894 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
6895 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
6896 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
6897 /// so only this cell separates the split arm from the HORZ/VERT one).
6898 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
6899}
6900
6901/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
6902/// mixed groups, split 4x4 leaves)`.
6903pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
6904 SUB8_INTRA_RECT_HITS.with(|c| {
6905 let h = c.get();
6906 (h[0], h[1], h[2], h[3], h[4])
6907 })
6908}
6909
6910/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
6911pub fn sub8_inter_rect_hits() -> (usize, usize) {
6912 SUB8_INTER_RECT_HITS.with(|c| {
6913 let h = c.get();
6914 (h[0], h[1])
6915 })
6916}
6917
6918// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
6919// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
6920// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
6921// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
6922// (b) was 0 for every stream before this round -- the leaf path never touched
6923// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
6924// filtered where libaom skips it. A gate asserts both are non-zero.
6925thread_local! {
6926 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6927 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6928 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
6929 // crosses the cropped frame edge -- the only units for which "clamp at
6930 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
6931 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
6932 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
6933 // whose width or height is not a multiple of 8 is the only shape that
6934 // produces one; the straddling-band gate arms assert it grew.
6935 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6936 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
6937 // (see `Neighbours::skip_written`).
6938 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6939 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
6940 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
6941 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
6942 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
6943 // 8-tall strip pair where only one half is skip must still be FILTERED.
6944 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6945 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6946}
6947
6948/// Current value of `RECT_SKIP_BAND_HITS`.
6949pub fn rect_skip_band_hits() -> usize {
6950 RECT_SKIP_BAND_HITS.with(|c| c.get())
6951}
6952
6953/// Current value of `CDEF_MIXED_SKIP_UNITS`.
6954pub fn cdef_mixed_skip_units() -> usize {
6955 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
6956}
6957
6958/// Current value of `CDEF_SKIPPED_UNITS`.
6959#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6960pub(crate) fn cdef_skipped_units() -> usize {
6961 CDEF_SKIPPED_UNITS.with(|c| c.get())
6962}
6963
6964/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
6965/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
6966pub fn cdef_unwritten_skip_units() -> usize {
6967 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
6968}
6969
6970/// Current value of `INTER8_SKIP_BAND_HITS`.
6971#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6972pub(crate) fn inter8_skip_band_hits() -> usize {
6973 INTER8_SKIP_BAND_HITS.with(|c| c.get())
6974}
6975
6976/// Current value of `CDEF_STRADDLE_UNITS`.
6977#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6978pub(crate) fn cdef_straddle_units() -> usize {
6979 CDEF_STRADDLE_UNITS.with(|c| c.get())
6980}
6981
6982/// Current value of [`SUB8_SPLIT_HITS`].
6983#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6984pub(crate) fn sub8_split_hits() -> usize {
6985 SUB8_SPLIT_HITS.with(|c| c.get())
6986}
6987
6988/// Current value of [`SUB8_INTER_SPLIT_HITS`].
6989pub fn sub8_inter_split_hits() -> usize {
6990 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
6991}
6992
6993// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
6994// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
6995// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
6996// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
6997// first sub-block's type is never the one). Reading it off sub-block 0
6998// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
6999// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
7000// see this rule through this counter.
7001thread_local! {
7002 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7003}
7004
7005/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
7006pub fn sub8_chroma_tx_from_ref_hits() -> usize {
7007 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
7008}
7009
7010fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
7011 if coeffs && first_sub != chroma_ref {
7012 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
7013 }
7014}
7015
7016// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
7017// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
7018// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
7019// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
7020// asserts on these two rather than a plain leaf count.
7021thread_local! {
7022 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7023 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7024 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
7025 /// two 4x4 transform units, predicted one after the other. A separate
7026 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
7027 /// the gate can prove THIS path fired.
7028 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7029 /// 16x8/8x16 intra strips whose prediction actually read past the block's
7030 /// own width (above-right) or height (below-left) -- the samples
7031 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
7032 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
7033 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7034 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
7035 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
7036 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7037}
7038
7039/// Current value of [`RECT8_SPLIT_TX_HITS`].
7040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7041pub(crate) fn rect8_split_tx_hits() -> usize {
7042 RECT8_SPLIT_TX_HITS.with(|c| c.get())
7043}
7044
7045/// Current value of [`RECT_STRIP_PRED_HITS`].
7046#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7047pub(crate) fn rect_strip_pred_hits() -> usize {
7048 RECT_STRIP_PRED_HITS.with(|c| c.get())
7049}
7050
7051/// Current value of [`RECT_STRIP_REACH_HITS`].
7052#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7053pub(crate) fn rect_strip_reach_hits() -> usize {
7054 RECT_STRIP_REACH_HITS.with(|c| c.get())
7055}
7056
7057/// Current value of [`TX4X8_CODED_HITS`].
7058#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7059pub(crate) fn tx4x8_coded_hits() -> usize {
7060 TX4X8_CODED_HITS.with(|c| c.get())
7061}
7062
7063/// Current value of [`TX8X4_CODED_HITS`].
7064#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7065pub(crate) fn tx8x4_coded_hits() -> usize {
7066 TX8X4_CODED_HITS.with(|c| c.get())
7067}
7068
7069// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
7070// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
7071// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
7072// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
7073// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
7074// (`eob_pt_{16,64,128,256}_chroma_class1`).
7075thread_local! {
7076 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
7077 const { std::cell::Cell::new(0) };
7078}
7079
7080/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
7081#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7082pub(crate) fn chroma_eob_class1_hits() -> usize {
7083 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
7084}
7085
7086/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
7087/// `tx_type` put this block's `eob_pt` on the class-1 row.
7088fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
7089 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
7090 hit!(CHROMA_EOB_CLASS1_HITS);
7091 }
7092}
7093
7094// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
7095// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
7096// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
7097// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
7098// looked identical to a same-plane disagreement. Set by `exec_intra` (the
7099// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
7100// by the `EC_PRED` rung, so it cannot change a decode.
7101thread_local! {
7102 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7103}
7104
7105/// The plane index the `EC_PRED` rung prints as `plane=`.
7106fn recon_plane() -> usize {
7107 RECON_PLANE.with(std::cell::Cell::get)
7108}
7109
7110/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
7111/// either of its two early returns.
7112struct PlaneGuard(usize);
7113impl Drop for PlaneGuard {
7114 fn drop(&mut self) {
7115 RECON_PLANE.with(|c| c.set(self.0));
7116 }
7117}
7118
7119const SUB_MI: u32 = 4;
7120const MI: usize = 4;
7121const SB: usize = 64;
7122/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
7123/// (tile start, superblock-row start).
7124///
7125/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
7126/// `av1_get_partition_plane_context` reads its own zero-initialised
7127/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
7128/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
7129/// (64), which reads identically at every level up to 64x64 but sets the bit
7130/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
7131/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
7132/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
7133const NO_NEIGHBOUR_SIDE: usize = 128;
7134const BLOCK: usize = 32;
7135const SUB: usize = 16;
7136const TX32: usize = 32;
7137const TX16: usize = 16;
7138const TX8: usize = 8;
7139const TX4: usize = 4;
7140const DC_PRED: usize = 0;
7141/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7142/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7143/// constant.
7144const V_PRED: usize = 1;
7145const H_PRED: usize = 2;
7146/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7147/// `Fimode_To_Intradir`, libaom `blockd.h`).
7148const D157_PRED: usize = 6;
7149/// The last directional mode, `D67_PRED`.
7150const D67_PRED: usize = 8;
7151/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7152/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7153/// codes anything else, so this decoder never reads anything else either.
7154const ANGLE_DELTA_ZERO: usize = 3;
7155const NUM_BASE_LEVELS: i32 = 2;
7156const COEFF_BASE_RANGE: i32 = 12;
7157const BR_STEP: i32 = 3;
7158const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7159
7160/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7161/// whose probability mass a superblock or block half outside the frame
7162/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7163/// duplicated here (that module is another lane's territory this round) and
7164/// kept in step with it by the byte-exact round-trip tests below rather than
7165/// by sharing code.
7166const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7167const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7168
7169fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7170 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7171 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7172 }
7173}
7174
7175fn element_prob(cdf: &[u16], element: usize) -> u16 {
7176 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7177}
7178
7179/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7180/// with: the mass of `elements` becomes the probability of the one partition
7181/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7182/// (the encoder's non-adapting counterpart to this read).
7183fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7184 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7185 [32768 - split, 32768, 0]
7186}
7187
7188fn unsupported(what: impl Into<String>) -> Error {
7189 Error::unsupported("AV1 tile", what.into())
7190}
7191
7192/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7193/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7194/// same rule.
7195pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7196 match base_q_idx {
7197 0..=20 => 0,
7198 21..=60 => 1,
7199 61..=120 => 2,
7200 _ => 3,
7201 }
7202}
7203
7204/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7205/// [`crate::tile`]'s writer generates its scan tables with.
7206fn default_scan(side: usize) -> &'static [u16] {
7207 // One table per transform side (4/8/16/32), built once: this used to be a
7208 // fresh heap allocation plus the whole anti-diagonal walk on every
7209 // transform block read.
7210 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7211 [
7212 default_scan_gen(4),
7213 default_scan_gen(8),
7214 default_scan_gen(16),
7215 default_scan_gen(32),
7216 ]
7217 });
7218 assert!(
7219 matches!(side, 4 | 8 | 16 | 32),
7220 "no default scan for a {side}-point transform"
7221 );
7222 &SCANS[side.trailing_zeros() as usize - 2]
7223}
7224
7225fn default_scan_gen(side: usize) -> Vec<u16> {
7226 let mut scan = Vec::with_capacity(side * side);
7227 for d in 0..(2 * side - 1) {
7228 let lo = d.saturating_sub(side - 1);
7229 let hi = d.min(side - 1);
7230 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7231 if d % 2 == 0 {
7232 scan.extend(diagonal.rev());
7233 } else {
7234 scan.extend(diagonal);
7235 }
7236 }
7237 scan
7238}
7239
7240/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7241/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7242/// in, instead of the default zigzag. libaom's own tables are keyed by a
7243/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7244/// physically column-major level buffer, but they decompose to the exact
7245/// same (row, col) walk as a flat row-major traversal of *our* row-major
7246/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7247/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7248/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7249/// transposed (column 0 down every row, then column 1, ...).
7250pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7251 class_scan_table_wh(side, side, class)
7252}
7253
7254/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7255/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7256/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7257/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7258/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7259/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7260fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7261 match class {
7262 TxClass::Vert => (0..(w * h) as u16).collect(),
7263 TxClass::Horiz => (0..w)
7264 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7265 .collect(),
7266 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7267 }
7268}
7269
7270fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7271 match scan_idx {
7272 0 => 0,
7273 i if i <= area / 8 => 1,
7274 i if i <= area / 4 => 2,
7275 _ => 3,
7276 }
7277}
7278
7279/// One cell of [`read_coeffs`]'s level buffer.
7280///
7281/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7282/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7283/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7284/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7285/// zero cells instead of needing the `row >= side || col >= side` edge test
7286/// this used to run five times per coefficient. Nothing writes a padding
7287/// cell, so the values are the same zeros the test returned.
7288#[inline]
7289fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7290 grid[row * stride + col] as i32
7291}
7292
7293/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7294/// `txb_common.h`): everything but the two lone-axis-identity types this
7295/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7296#[derive(Clone, Copy, PartialEq, Eq)]
7297pub(crate) enum TxClass {
7298 TwoD,
7299 Horiz,
7300 Vert,
7301}
7302
7303impl TxClass {
7304 pub(crate) fn of(tx_type: TxType) -> Self {
7305 match tx_type {
7306 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7307 // key on axis alone -- FLIPADST is still ADST for this purpose.
7308 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7309 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7310 _ => Self::TwoD,
7311 }
7312 }
7313}
7314
7315/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7316/// table (indexed by the position along the transform's *coded* axis --
7317/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7318/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7319/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7320pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7321 match i {
7322 0 => 26,
7323 1 => 31,
7324 _ => 36,
7325 }
7326}
7327
7328fn base_ctx(
7329 grid: &[u8],
7330 stride: usize,
7331 row: usize,
7332 col: usize,
7333 class: TxClass,
7334 rect_shape: Option<(usize, usize)>,
7335) -> usize {
7336 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7337 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7338 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7339 // position through the full 1D neighbour sum and offset table. Skipping
7340 // that for every class desynced the last (DC) coefficient of a
7341 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7342 // 0, which then read one extra `BR` symbol at the max and forced a
7343 // spurious third Golomb call).
7344 if class == TxClass::TwoD && row == 0 && col == 0 {
7345 return 0;
7346 }
7347 let offsets: [(usize, usize); 5] = match class {
7348 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7349 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7350 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7351 };
7352 let mag: i32 = offsets
7353 .iter()
7354 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7355 .sum();
7356 let ctx = ((mag + 1) >> 1).min(4) as usize;
7357 match class {
7358 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7359 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7360 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7361 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7362 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7363 // strip, which own a genuinely different table from the square one
7364 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7365 // square table vs the real ctx 13 the rect table gives).
7366 TxClass::TwoD => {
7367 // lane-rectsplit r4: apply libaom's GENERATING RULE
7368 // (`txb_common.h:199-209`) directly instead of indexing the
7369 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7370 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7371 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7372 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7373 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7374 // transcriptions are `[col][row]` and this read had them as
7375 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7376 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7377 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7378 // pins the rule against the tables over their whole 5x5 domain.
7379 if let Some((w, h)) = rect_shape {
7380 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7381 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7382 }
7383 if w < h && row < 2 {
7384 return ctx + 11;
7385 }
7386 if w > h && col < 2 {
7387 return ctx + 16;
7388 }
7389 }
7390 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7391 }
7392 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7393 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7394 }
7395}
7396
7397/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7398/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7399/// function of the tx class alone, which is fixed for a whole transform unit,
7400/// so resolving it once per unit takes the class match and the `(dr, dc)`
7401/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7402/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7403/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7404/// original `(dr, dc)` form.
7405fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7406 match class {
7407 TxClass::TwoD => (
7408 [stride, 1, stride + 1, 2 * stride, 2],
7409 [stride, 1, stride + 1],
7410 ),
7411 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7412 TxClass::Vert => (
7413 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7414 [stride, 1, 2 * stride],
7415 ),
7416 }
7417}
7418
7419/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7420/// neighbours) + 1) >> 1`, clamped to 4.
7421#[inline(always)]
7422fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7423 let mut mag = 0u32;
7424 for &t in taps {
7425 mag += u32::from(grid[idx + t]).min(3);
7426 }
7427 (((mag + 1) >> 1) as usize).min(4)
7428}
7429
7430/// [`br_ctx`]'s neighbour sum, off flat taps.
7431#[inline(always)]
7432fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7433 let mut mag = 0u32;
7434 for &t in taps {
7435 mag += u32::from(grid[idx + t]);
7436 }
7437 (((mag + 1) >> 1) as usize).min(6)
7438}
7439
7440/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7441/// origin-offset tail the two coefficient readers state inline; kept as the
7442/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7443/// flat one against.
7444#[cfg(test)]
7445fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7446 let extra = match class {
7447 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7448 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7449 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7450 };
7451 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7452 let mag = (((mag + 1) >> 1).min(6)) as usize;
7453 if row == 0 && col == 0 {
7454 return mag;
7455 }
7456 let near_origin = match class {
7457 TxClass::TwoD => row < 2 && col < 2,
7458 TxClass::Horiz => col == 0,
7459 TxClass::Vert => row == 0,
7460 };
7461 if near_origin { mag + 7 } else { mag + 14 }
7462}
7463
7464/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7465/// transposed from libaom's column-major buffer into this decoder's row-major
7466/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7467/// against the real table). Not the square zigzag formula generalized to
7468/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7469const SCAN_32X16: [u16; 512] = [
7470 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7471 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7472 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7473 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7474 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7475 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7476 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7477 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7478 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7479 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7480 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7481 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7482 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7483 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7484 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7485 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7486 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7487 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7488 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7489 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7490 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7491 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7492 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7493 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7494 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7495 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7496 510, 479, 511,
7497];
7498
7499/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7500/// [`SCAN_32X16`]'s doc comment).
7501const SCAN_16X32: [u16; 512] = [
7502 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,
7503 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7504 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7505 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7506 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7507 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7508 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7509 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7510 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7511 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7512 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7513 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7514 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7515 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7516 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7517 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7518 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7519 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7520 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7521 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7522 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7523 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7524 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7525 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7526 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7527 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7528];
7529
7530/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7531/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7532/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7533/// the same source).
7534const SCAN_4X8: [u16; 32] = [
7535 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,
7536 23, 26, 29, 27, 30, 31,
7537];
7538
7539/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7540const SCAN_8X4: [u16; 32] = [
7541 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,
7542 29, 22, 15, 30, 23, 31,
7543];
7544
7545/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7546/// [`SCAN_32X16`]'s doc comment).
7547const SCAN_16X8: [u16; 128] = [
7548 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,
7549 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7550 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7551 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7552 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7553 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7554];
7555
7556/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7557/// [`SCAN_32X16`]'s doc comment).
7558const SCAN_8X16: [u16; 128] = [
7559 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,
7560 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7561 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7562 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7563 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7564 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7565];
7566
7567/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7568/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7569/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7570/// scans column-major (`p = col * height + row`), so a naive copy of
7571/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7572/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7573/// are byte-identical to this decoder's [`SCAN_8X16`].
7574const SCAN_32X8: [u16; 256] = [
7575 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7576 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7577 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7578 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7579 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7580 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7581 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7582 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7583 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7584 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7585 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7586 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7587 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7588];
7589/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7590/// 16x64 `PARTITION_VERT_4` strip).
7591const SCAN_8X32: [u16; 256] = [
7592 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,
7593 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7594 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7595 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7596 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7597 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7598 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7599 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7600 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7601 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7602 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7603 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7604 239, 246, 253, 247, 254, 255,
7605];
7606/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7607/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7608/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7609/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7610/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7611/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7612/// were emitted -- a naive copy installs the transpose (class
7613/// reference-layout-not-spec).
7614const SCAN_16X4: [u16; 64] = [
7615 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,
7616 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7617 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7618];
7619/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7620/// 8x32 `PARTITION_VERT_4` strip).
7621const SCAN_4X16: [u16; 64] = [
7622 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,
7623 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7624 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7625];
7626
7627/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7628/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7629/// padding already holds.
7630#[inline]
7631fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7632 grid[row * stride + col] as i32
7633}
7634
7635/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7636/// the rect generalization is libaom's own comment in
7637/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7638/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7639/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7640/// [`decode_block_rect`] codes (see that function's own doc comment).
7641fn base_ctx_rect(
7642 grid: &[u8],
7643 stride: usize,
7644 w: usize,
7645 h: usize,
7646 row: usize,
7647 col: usize,
7648 class: TxClass,
7649) -> usize {
7650 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7651 // the 2D class short-circuits the DC position.
7652 if class == TxClass::TwoD && row == 0 && col == 0 {
7653 return 0;
7654 }
7655 let offsets: [(usize, usize); 5] = match class {
7656 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7657 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7658 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7659 };
7660 let mag: i32 = offsets
7661 .iter()
7662 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7663 .sum();
7664 let ctx = ((mag + 1) >> 1).min(4) as usize;
7665 match class {
7666 TxClass::TwoD => {
7667 if w < h && row < 2 {
7668 return ctx + 11;
7669 }
7670 if w > h && col < 2 {
7671 return ctx + 16;
7672 }
7673 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7674 }
7675 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7676 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7677 // position along one axis only).
7678 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7679 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7680 }
7681}
7682
7683/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7684/// neighbour-offset math itself is shape-independent, only the boundary
7685/// clamp needs the real bound in each axis.
7686/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7687/// its body was character-for-character [`br_ctx`]'s, which
7688/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7689#[cfg(test)]
7690fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7691 let extra = match class {
7692 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7693 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7694 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7695 };
7696 let mag = neighbour_rect(grid, stride, row + 1, col)
7697 + neighbour_rect(grid, stride, row, col + 1)
7698 + extra;
7699 let mag = (((mag + 1) >> 1).min(6)) as usize;
7700 if row == 0 && col == 0 {
7701 return mag;
7702 }
7703 let near_origin = match class {
7704 TxClass::TwoD => row < 2 && col < 2,
7705 TxClass::Horiz => col == 0,
7706 TxClass::Vert => row == 0,
7707 };
7708 if near_origin { mag + 7 } else { mag + 14 }
7709}
7710
7711fn dc_vote(dc: Option<bool>) -> i32 {
7712 match dc {
7713 None => 0,
7714 Some(true) => -1,
7715 Some(false) => 1,
7716 }
7717}
7718
7719fn dc_sign_ctx(vote: i32) -> usize {
7720 match vote.signum() {
7721 0 => 0,
7722 -1 => 1,
7723 _ => 2,
7724 }
7725}
7726
7727/// The `tx_type` a CDF symbol names, given the width of the row it was read
7728/// from.
7729///
7730/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7731/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7732/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7733/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7734/// members are a prefix of the five.
7735///
7736/// One function rather than a `match` at each reader, so
7737/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7738/// tests the mapping the readers actually use.
7739pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7740 match cdf_len {
7741 17 => TxType::from_symbol_all16(t),
7742 13 => TxType::from_symbol_set2_12(t),
7743 8 => TxType::from_symbol_set1(t),
7744 _ => TxType::from_symbol(t),
7745 }
7746}
7747
7748/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7749/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7750/// (class `table-and-reader-move-together` -- the writer picks its symbol
7751/// through the reader's own map, so the two cannot drift).
7752pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7753 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7754}
7755
7756/// The remainder of a level the base and base-range syntax could not reach
7757/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7758/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7759pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7760 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7761 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7762 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7763 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7764 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7765 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7766 // stream_can_carry` enumerates that whole value domain.
7767 //
7768 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7769 // earlier desync (class `refusal-hides-a-defect`), and every historical
7770 // instance was closed by fixing that desync -- lane-dgolomb's
7771 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7772 // Raising the cap only trades a clean refusal for silent corruption:
7773 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7774 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7775 // from a refusal into a frame-0 LUMA MISMATCH.
7776 let mut length = 1u32;
7777 while dec.literal(1) == 0 {
7778 length += 1;
7779 if length > 20 {
7780 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7781 }
7782 }
7783 let mut x = 1u32;
7784 for _ in 1..length {
7785 x = (x << 1) | dec.literal(1);
7786 }
7787 Ok(x - 1)
7788}
7789
7790/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7791/// [`crate::tile`]'s `write_eob`.
7792fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7793 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7794 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7795
7796 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7797 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7798 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7799 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7800 // `eob_multi_ctx`). Missing that split desynced the very first
7801 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7802 // against a real aomdec trace).
7803 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7804 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7805 (_, Some(class1)) => class1,
7806 };
7807 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7808 let (range, value) = dec.debug_state();
7809 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7810 }
7811 let group = dec.symbol(eob_pt) + 1;
7812 if trace {
7813 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7814 }
7815 let bits = OFFSET_BITS[group];
7816 let mut offset = 0u32;
7817 if bits > 0 {
7818 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7819 if trace {
7820 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
7821 }
7822 offset = top << (bits - 1);
7823 if bits > 1 {
7824 offset |= dec.literal(bits - 1);
7825 }
7826 }
7827 GROUP_START[group] + offset as usize
7828}
7829
7830/// One transform block's levels, the inverse of [`crate::tile`]'s
7831/// `write_coeffs`, returned as a `side * side` grid in raster order, along
7832/// with the transform type that grid was coded under (`DCT_DCT` when the
7833/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
7834/// 64-point transforms, which never code anything else).
7835///
7836/// # Errors
7837/// Returns an error if the `tx_type` symbol decodes to a value outside its
7838/// CDF's own set (a corrupt or unsupported bitstream) — every value the
7839/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
7840/// produce dispatches to a real inverse transform.
7841/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
7842/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
7843/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
7844/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
7845/// the plane's own predicted mode instead. Every entry this table can
7846/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
7847/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
7848/// table ever names), so unlike the CDF-coded luma path there is no
7849/// ext-tx-set membership check to fall back from here.
7850pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
7851 use crate::intra::{
7852 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
7853 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
7854 };
7855 match mode {
7856 DC_PRED | D45_PRED => TxType::DctDct,
7857 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
7858 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
7859 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
7860 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
7861 }
7862}
7863
7864/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
7865/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
7866/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
7867fn is_smooth_mode(mode: usize) -> bool {
7868 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
7869}
7870
7871/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
7872/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7873/// nine of them inside the base/sign loops pinned nine sets of values in the
7874/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
7875/// traffic). Out of line, the loop keeps its values in registers and the
7876/// trace output is character-for-character what it was.
7877#[cold]
7878#[inline(never)]
7879fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7880 eprintln!(
7881 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
7882 );
7883}
7884
7885#[cold]
7886#[inline(never)]
7887fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7888 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
7889}
7890
7891#[cold]
7892#[inline(never)]
7893fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
7894 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
7895}
7896
7897#[cold]
7898#[inline(never)]
7899fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
7900 let (rng, _) = dec.debug_state();
7901 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
7902}
7903
7904#[cold]
7905#[inline(never)]
7906fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
7907 let (rng, _) = dec.debug_state();
7908 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
7909}
7910
7911#[cold]
7912#[inline(never)]
7913fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
7914 let (rng, _) = dec.debug_state();
7915 eprintln!(
7916 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
7917 negative as i32
7918 );
7919}
7920
7921#[cold]
7922#[inline(never)]
7923fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
7924 let (rng, _) = dec.debug_state();
7925 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
7926}
7927
7928#[cold]
7929#[inline(never)]
7930fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
7931 let (rng, _) = dec.debug_state();
7932 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
7933}
7934
7935// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
7936#[track_caller]
7937fn read_coeffs(
7938 dec: &mut SymbolDecoder,
7939 coding: &mut TxbTables,
7940 scan: &[u16],
7941 skip_ctx: usize,
7942 sign_ctx: usize,
7943 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
7944 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
7945 // nothing at all; `DctDct` for every luma call and every chroma call at
7946 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
7947 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
7948 default_tx_type: TxType,
7949 // `Some((w, h))` with `w != h` when this read is a superblock-level
7950 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
7951 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
7952 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
7953 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
7954 // caller's block genuinely is `side` x `side`.
7955 rect_shape: Option<(usize, usize)>,
7956) -> Result<(Grid, TxType)> {
7957 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7958 let side = coding.side;
7959 // lane-av1readcensus: this unit's own entry state, so the census line
7960 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
7961 // (which prints `r->ec.rng` before the same `txb_skip` read).
7962 let census_entry_rng = dec.debug_state().0;
7963 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
7964 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7965 let (range, value) = dec.debug_state();
7966 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
7967 }
7968 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
7969 let (range, value) = dec.debug_state();
7970 let bit = dec.debug_bitpos();
7971 eprintln!(
7972 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
7973 );
7974 }
7975 let dbg_txbskip = if coeff_trace_on() {
7976 coding.txb_skip[skip_ctx]
7977 } else {
7978 [0; 3]
7979 };
7980 let sq_bit = if coeff_trace_on() {
7981 dec.debug_bitpos()
7982 } else {
7983 0
7984 };
7985 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7986 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
7987 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
7988 // filter on it before pairing anything against the oracle.
7989 if crate::envflags::env_flag!("EC_IBCTX") {
7990 eprintln!(
7991 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
7992 coding.side,
7993 std::panic::Location::caller(),
7994 );
7995 }
7996 if coeff_trace_on() {
7997 let (rng, _) = dec.debug_state();
7998 eprintln!(
7999 "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={}",
8000 coding.side,
8001 all_zero as i32,
8002 dec.debug_bitpos()
8003 );
8004 }
8005 if crate::envflags::env_flag!("EC_AV1_TELL") {
8006 eprintln!(
8007 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
8008 all_zero as u8,
8009 dec.debug_bitpos(),
8010 dec.debug_state().0
8011 );
8012 }
8013 if trace {
8014 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
8015 }
8016 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8017 let (range, value) = dec.debug_state();
8018 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
8019 }
8020 if all_zero {
8021 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
8022 // shared zero grid instead of allocating and zeroing its own.
8023 census_unit(
8024 census_w,
8025 census_h,
8026 TxType::DctDct,
8027 0,
8028 true,
8029 census_entry_rng,
8030 dec,
8031 );
8032 return Ok((Grid::Zero(side * side), TxType::DctDct));
8033 }
8034 let mut grid = vec![0i32; side * side];
8035 let mut tx_type = default_tx_type;
8036 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8037 // The CDF row's own width names its set (lane-cdffwd2: extended
8038 // past the original two-way intra split once wider `reduced_tx_set
8039 // == 0` inter sets joined the table): 17 slots (16 symbols) is
8040 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
8041 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
8042 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
8043 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
8044 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
8045 let len = tx_type_cdf.len();
8046 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
8047 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
8048 }
8049 let t = dec.symbol(tx_type_cdf);
8050 crate::census::tx_type(len, t);
8051 if coeff_trace_on() {
8052 let (rng, _) = dec.debug_state();
8053 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
8054 }
8055 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8056 let (range, value) = dec.debug_state();
8057 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
8058 }
8059 if trace {
8060 eprintln!("TRACE tx_type value={t} len={len}");
8061 }
8062 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8063 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8064 })?;
8065 }
8066
8067 let class = TxClass::of(tx_type);
8068 if class != TxClass::TwoD {
8069 hit!(TX_CLASS1_HITS);
8070 hit!(RECT_CLASS1_HITS);
8071 }
8072 let eob = read_eob(dec, coding, class);
8073 if trace {
8074 eprintln!("TRACE eob value={eob}");
8075 }
8076 let ec_trace_coeff = coeff_trace_on();
8077 if ec_trace_coeff {
8078 let (rng, _) = dec.debug_state();
8079 let cls = match class {
8080 TxClass::TwoD => "2d",
8081 TxClass::Horiz => "horiz",
8082 TxClass::Vert => "vert",
8083 };
8084 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
8085 }
8086 let class_scan;
8087 let scan: &[u16] = if class == TxClass::TwoD {
8088 scan
8089 } else {
8090 class_scan = class_scan_table(side, class);
8091 &class_scan
8092 };
8093 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
8094 // coefficient `pos / side`, `pos % side` was a hardware divide where a
8095 // shift and a mask say the same thing, and the level buffer fits a fixed
8096 // 32x32 frame of stack instead of a heap allocation per transform block.
8097 debug_assert!(side.is_power_of_two() && side <= 32);
8098 let sh = side.trailing_zeros();
8099 let col_mask = side - 1;
8100 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
8101 // `stride = side + 4` columns and four spare rows, so the widest read
8102 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
8103 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
8104 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
8105 let stride = side + 4;
8106 let mut levels_buf = [0u8; 36 * 36];
8107 let levels = &mut levels_buf[..stride * stride];
8108 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
8109 // `pos >> sh` / `& mask` decomposition and load the level back out of the
8110 // padded frame just to skip the zeros. The base pass already knows both,
8111 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
8112 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
8113 // pass walks that list in reverse (the base pass runs in reverse scan
8114 // order, so reversing it is forward scan order: the same coefficients, in
8115 // the same order, with the same `c` the trace prints).
8116 let mut nz_buf = [0u16; 1024];
8117 let mut nz_n = 0usize;
8118 let (base_taps, br_taps) = flat_taps(stride, class);
8119 for scan_idx in (0..eob).rev() {
8120 let pos = scan[scan_idx] as usize;
8121 let (row, col) = (pos >> sh, pos & col_mask);
8122 let idx = row * stride + col;
8123 let level = if scan_idx == eob - 1 {
8124 let ctx = eob_coeff_ctx(scan_idx, side * side);
8125 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8126 if trace {
8127 trace_base_eob(scan_idx, pos, row, col, ctx, v);
8128 }
8129 v
8130 } else {
8131 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
8132 if row == 0 && col == 0 {
8133 0
8134 } else {
8135 base_mag(levels, idx, &base_taps)
8136 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8137 }
8138 } else {
8139 base_ctx(levels, stride, row, col, class, rect_shape)
8140 };
8141 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8142 if ec_trace_coeff {
8143 // `pos` in libaom's column-major `coeff_idx` convention, so
8144 // the ladder lines up with instrumented `aomdec`.
8145 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
8146 }
8147 if trace {
8148 trace_base(scan_idx, pos, row, col, ctx, v);
8149 }
8150 v
8151 };
8152 let level = if level > NUM_BASE_LEVELS {
8153 let ctx = {
8154 let mag = br_mag(levels, idx, &br_taps);
8155 if row == 0 && col == 0 {
8156 mag
8157 } else {
8158 let near_origin = match class {
8159 TxClass::TwoD => row < 2 && col < 2,
8160 TxClass::Horiz => col == 0,
8161 TxClass::Vert => row == 0,
8162 };
8163 if near_origin { mag + 7 } else { mag + 14 }
8164 }
8165 };
8166 let mut level = level;
8167 let mut sent = 0;
8168 loop {
8169 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8170 if ec_trace_coeff {
8171 // lane-leaf8tx r3: the `br` rung was missing from THIS
8172 // path's trace, so the cross-decoder range ladder was
8173 // blind to every base-range symbol and mis-reported the
8174 // first divergence (class [[gate-blind-to-feature]]).
8175 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8176 }
8177 if trace {
8178 trace_br(scan_idx, pos, row, col, ctx, k);
8179 }
8180 level += k;
8181 sent += BR_STEP;
8182 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8183 break;
8184 }
8185 }
8186 level
8187 } else {
8188 level
8189 };
8190 if ec_trace_coeff && scan_idx == eob - 1 {
8191 coeff_step_base_eob_level(dec, level);
8192 }
8193 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8194 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8195 // added in the sign pass below, straight into `grid`), so the context
8196 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8197 // byte gather (lane-coefbuf).
8198 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8199 levels[idx] = level as u8;
8200 if level != 0 {
8201 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8202 nz_n += 1;
8203 }
8204 }
8205 if ec_trace_coeff {
8206 let (rng, _) = dec.debug_state();
8207 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8208 }
8209
8210 for &packed in nz_buf[..nz_n].iter().rev() {
8211 let c = (packed >> 4) as usize;
8212 let pos = scan[c] as usize;
8213 let level = (packed & 15) as i32;
8214 let negative = if pos == 0 {
8215 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8216 if trace {
8217 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8218 }
8219 v
8220 } else {
8221 dec.literal(1) == 1
8222 };
8223 if ec_trace_coeff {
8224 coeff_step_sign(dec, c, negative);
8225 }
8226 let level = if level > MAX_BR_LEVEL {
8227 let g = read_golomb(dec)?;
8228 if trace {
8229 eprintln!("TRACE golomb pos={pos} value={g}");
8230 }
8231 level + g as i32
8232 } else {
8233 level
8234 };
8235 if ec_trace_coeff {
8236 coeff_step_post_golomb(dec, c, level);
8237 }
8238 grid[pos] = if negative { -level } else { level };
8239 }
8240 census_unit(
8241 census_w,
8242 census_h,
8243 tx_type,
8244 eob,
8245 false,
8246 census_entry_rng,
8247 dec,
8248 );
8249 Ok((Grid::Own(grid), tx_type))
8250}
8251
8252/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8253/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8254/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8255/// can ever produce, since every `tx_type` this decoder's rect sets can read
8256/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8257/// rather than guess-decode if a non-2D class ever shows up here, since
8258/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8259/// form for those.
8260
8261// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
8262// of this reader -- the only thing that identifies a unit's route. No plane is
8263// printed here: the plane is the ORACLE's side of the pairing, and a label
8264// here is one more thing that can disagree with it.
8265#[track_caller]
8266fn read_coeffs_rect(
8267 dec: &mut SymbolDecoder,
8268 coding: &mut TxbTables,
8269 scan: &[u16],
8270 w: usize,
8271 h: usize,
8272 skip_ctx: usize,
8273 sign_ctx: usize,
8274 default_tx_type: TxType,
8275 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8276 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8277 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8278 // independent lane reports.
8279 plane: usize,
8280) -> Result<(Grid, TxType)> {
8281 let rect_trace = coeff_trace_on();
8282 let entry_rng = dec.debug_state().0;
8283 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8284 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8285 // plane itself rather than inheriting whichever reader did last. The
8286 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8287 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8288 // value -- and the other plane-owning readers stamp on entry.
8289 set_census_plane(plane);
8290 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
8291 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
8292 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8293 if rect_trace {
8294 eprintln!(
8295 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
8296 all_zero as i32,
8297 dec.debug_state().0,
8298 dec.debug_bitpos()
8299 );
8300 }
8301 if ibctx_on {
8302 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
8303 // range: the only collision-free key for pairing this unit against the
8304 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
8305 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
8306 // either way, which is exactly the artifact that made an earlier
8307 // round of this lane claim a false exactness.
8308 eprintln!(
8309 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
8310 dec.debug_bitpos(),
8311 std::panic::Location::caller(),
8312 );
8313 }
8314 if all_zero {
8315 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8316 return Ok((Grid::Zero(w * h), TxType::DctDct));
8317 }
8318 let mut grid = vec![0i32; w * h];
8319 hit!(RECT_COEFF_TU_HITS);
8320 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8321 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8322 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8323 // context offsets -- both of which now have rect forms
8324 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8325 // The rect sets that carry no symbol at all still pass `None` here.
8326 let mut tx_type = default_tx_type;
8327 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8328 let len = tx_type_cdf.len();
8329 let t = dec.symbol(tx_type_cdf);
8330 crate::census::tx_type(len, t);
8331 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8332 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8333 })?;
8334 if rect_trace {
8335 eprintln!(
8336 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8337 dec.debug_state().0
8338 );
8339 }
8340 }
8341 let class = TxClass::of(tx_type);
8342 if class != TxClass::TwoD {
8343 hit!(TX_CLASS1_HITS);
8344 }
8345 let eob = read_eob(dec, coding, class);
8346 if rect_trace {
8347 eprintln!(
8348 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8349 dec.debug_state().0
8350 );
8351 }
8352 let class_scan;
8353 let scan: &[u16] = if class == TxClass::TwoD {
8354 scan
8355 } else {
8356 class_scan = class_scan_table_wh(w, h, class);
8357 &class_scan
8358 };
8359 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8360 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8361 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8362 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8363 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8364 // mask rather than a hardware divide.
8365 let stride = w + 4;
8366 let n = stride * (h + 4);
8367 if !(w.is_power_of_two() && n <= 36 * 36) {
8368 panic!("rect coeff scratch w={w} h={h} n={n}");
8369 }
8370 let (mut b96, mut b256, mut b768);
8371 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8372 let levels: &mut [u8] = if n <= 96 {
8373 b96 = [0u8; 96];
8374 &mut b96[..n]
8375 } else if n <= 256 {
8376 b256 = [0u8; 256];
8377 &mut b256[..n]
8378 } else {
8379 b768 = [0u8; 768];
8380 &mut b768[..n]
8381 };
8382 let wsh = w.trailing_zeros();
8383 let wmask = w - 1;
8384 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8385 let mut nz_buf = [0u16; 1024];
8386 let mut nz_n = 0usize;
8387 let (base_taps, br_taps) = flat_taps(stride, class);
8388 let (wlt, wgt) = (w < h, w > h);
8389 for scan_idx in (0..eob).rev() {
8390 let pos = scan[scan_idx] as usize;
8391 let (row, col) = (pos >> wsh, pos & wmask);
8392 let idx = row * stride + col;
8393 // libaom's column-major `coeff_idx`, for ladder comparison.
8394 let _apos = col * h + row;
8395 let level = if scan_idx == eob - 1 {
8396 let ctx = eob_coeff_ctx(scan_idx, w * h);
8397 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8398 if rect_trace {
8399 eprintln!(
8400 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8401 dec.debug_state().0
8402 );
8403 }
8404 v
8405 } else {
8406 let ctx = if class == TxClass::TwoD {
8407 if row == 0 && col == 0 {
8408 0
8409 } else {
8410 let m = base_mag(levels, idx, &base_taps);
8411 if wlt && row < 2 {
8412 m + 11
8413 } else if wgt && col < 2 {
8414 m + 16
8415 } else {
8416 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8417 }
8418 }
8419 } else {
8420 base_ctx_rect(levels, stride, w, h, row, col, class)
8421 };
8422 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8423 if rect_trace {
8424 eprintln!(
8425 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8426 dec.debug_state().0
8427 );
8428 }
8429 v
8430 };
8431 let level = if level > NUM_BASE_LEVELS {
8432 let ctx = {
8433 let mag = br_mag(levels, idx, &br_taps);
8434 if row == 0 && col == 0 {
8435 mag
8436 } else {
8437 let near_origin = match class {
8438 TxClass::TwoD => row < 2 && col < 2,
8439 TxClass::Horiz => col == 0,
8440 TxClass::Vert => row == 0,
8441 };
8442 if near_origin { mag + 7 } else { mag + 14 }
8443 }
8444 };
8445 let mut level = level;
8446 let mut sent = 0;
8447 loop {
8448 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8449 if rect_trace {
8450 eprintln!(
8451 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8452 dec.debug_state().0
8453 );
8454 }
8455 level += k;
8456 sent += BR_STEP;
8457 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8458 break;
8459 }
8460 }
8461 level
8462 } else {
8463 level
8464 };
8465 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8466 levels[idx] = level as u8;
8467 if level != 0 {
8468 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8469 nz_n += 1;
8470 }
8471 if rect_trace {
8472 let (rng, _) = dec.debug_state();
8473 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
8474 }
8475 }
8476 if rect_trace {
8477 let (rng, _) = dec.debug_state();
8478 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8479 }
8480 for &packed in nz_buf[..nz_n].iter().rev() {
8481 let pos = scan[(packed >> 4) as usize] as usize;
8482 let level = (packed & 15) as i32;
8483 let negative = if pos == 0 {
8484 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8485 } else {
8486 dec.literal(1) == 1
8487 };
8488 if rect_trace {
8489 let (rng, _) = dec.debug_state();
8490 eprintln!(
8491 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8492 u8::from(negative)
8493 );
8494 }
8495 let level = if level > MAX_BR_LEVEL {
8496 let g = read_golomb(dec)?;
8497 level + g as i32
8498 } else {
8499 level
8500 };
8501 grid[pos] = if negative { -level } else { level };
8502 }
8503 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8504 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8505 // grids differ is a reader defect, one whose grids agree is a transform
8506 // defect.
8507 if crate::envflags::env_flag!("EC_DQCOEFF") {
8508 let nz: Vec<String> = grid
8509 .iter()
8510 .enumerate()
8511 .filter(|&(_, &v)| v != 0)
8512 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8513 .collect();
8514 eprintln!(
8515 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8516 nz.join(",")
8517 );
8518 }
8519 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8520 Ok((Grid::Own(grid), tx_type))
8521}
8522
8523/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8524/// [`read_plane`] family already has.
8525///
8526/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8527/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8528/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8529/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8530/// enforces that for every strip that reads its chroma through it, but the rect
8531/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8532/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8533/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8534/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8535/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8536/// symbol -- and therefore every later pixel -- is decoded from the wrong
8537/// place, without ever tripping a refusal (the desynced values stay inside
8538/// every coded alphabet).
8539fn read_chroma_coeffs_rect(
8540 dec: &mut SymbolDecoder,
8541 coding: &mut TxbTables,
8542 scan: &[u16],
8543 w: usize,
8544 h: usize,
8545 skip_ctx: usize,
8546 sign_ctx: usize,
8547 default_tx_type: TxType,
8548 fctx: &crate::decode::FrameCtx,
8549 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8550 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8551 // V-plane read was indistinguishable from a luma one in the log).
8552 plane: usize,
8553) -> Result<(Grid, TxType)> {
8554 if mono(fctx) {
8555 return Ok((Grid::Zero(w * h), TxType::DctDct));
8556 }
8557 read_coeffs_rect(
8558 dec,
8559 coding,
8560 scan,
8561 w,
8562 h,
8563 skip_ctx,
8564 sign_ctx,
8565 default_tx_type,
8566 plane,
8567 )
8568}
8569
8570/// What one coded block leaves behind for the blocks that read it as a
8571/// neighbour: whether it coded anything at all, and the sign of its DC —
8572/// [`crate::tile`]'s own private `Neighbour`.
8573#[derive(Clone, Copy, Default)]
8574struct Neighbour {
8575 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8576 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8577 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8578 /// boolean (`level != 0`) is enough for every context this decoder read
8579 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8580 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8581 /// needs the actual magnitude tier of its above/left neighbours, not
8582 /// just whether they coded anything.
8583 level: u8,
8584 dc: Option<bool>,
8585}
8586
8587/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8588/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8589/// grid is dropped, never a panic. One `memset` per grid row instead of a
8590/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8591/// is contiguous, so this writes exactly the cells the cell loop did,
8592/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8593/// next row.
8594#[inline]
8595fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8596 let end = (start + n).min(dst.len());
8597 if start < end {
8598 dst[start..end].fill(v);
8599 }
8600}
8601
8602fn neighbour_state(grid: &[i32]) -> Neighbour {
8603 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8604 // sum has no early exit, so the 60% of units that code nothing used to
8605 // walk their whole grid here.
8606 if is_zero_grid(grid) {
8607 return Neighbour::default();
8608 }
8609 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8610 Neighbour {
8611 level: cul.min(7) as u8,
8612 dc: (grid[0] != 0).then_some(grid[0] < 0),
8613 }
8614}
8615
8616/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8617/// transform unit smaller than the block it sits in): `top`/`left` are the
8618/// above/left neighbours' magnitude tiers, each already clamped to 4.
8619pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8620 [1, 2, 2, 2, 3],
8621 [2, 4, 4, 4, 5],
8622 [2, 4, 4, 4, 5],
8623 [2, 4, 4, 4, 5],
8624 [3, 5, 5, 5, 6],
8625];
8626
8627/// The `skip` flag, its written-instrument bit, and the covering coded
8628/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8629/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8630/// nothing else, so a block's row is one fill instead of four, and the
8631/// deblocker's `pu_edge` reads origin and dims off one cache line.
8632#[derive(Clone, Copy)]
8633struct BlkCell {
8634 skip: bool,
8635 written: bool,
8636 org: [u16; 2],
8637 dim: [u8; 2],
8638}
8639
8640/// The neighbour state a block's contexts are read from — a duplicate of
8641/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8642/// territory this round), kept at the same two granularities the real writer
8643/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8644/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8645/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8646/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8647/// chroma transform straddling the true, odd-sized frame edge see its
8648/// neighbour's state clamped at its own subsampled edge rather than luma's.
8649#[derive(Clone)]
8650struct Neighbours {
8651 above: Vec<[Neighbour; 3]>,
8652 left: Vec<[Neighbour; 3]>,
8653 above_mode: Vec<usize>,
8654 left_mode: Vec<usize>,
8655 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8656 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8657 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8658 /// luma one -- the same block can (and often does) code a different
8659 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8660 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8661 /// within-block neighbour finer than this grid) is luma-only -- a known,
8662 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8663 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8664 above_uv_mode: Vec<usize>,
8665 left_uv_mode: Vec<usize>,
8666 above_side: Vec<usize>,
8667 left_side: Vec<usize>,
8668 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8669 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8670 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8671 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8672 /// array cannot tell the second leaf's partition symbol that the first
8673 /// one was coded at 8x8.
8674 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8675 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8676 above_side_mi: Vec<u8>,
8677 left_side_mi: Vec<u8>,
8678 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8679 /// / row, with the mi position it was written at
8680 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8681 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8682 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8683 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8684 /// leaf whose neighbour is another split group needs that group's leaf 3
8685 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8686 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8687 /// fall back to the coarse slot whenever the real neighbour was a block
8688 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8689 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8690 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8691 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8692 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8693 /// frame is 65536 px = 16384 mi).
8694 sub8_mode_col: Vec<(u16, u8)>,
8695 sub8_mode_row: Vec<(u16, u8)>,
8696 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8697 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8698 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8699 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8700 /// the leaf above writes the same row slot the block to the left owns.
8701 uv_mode_col: Vec<(u16, u8)>,
8702 uv_mode_row: Vec<(u16, u8)>,
8703 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8704 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8705 /// blockd.h). lane-t900 r12: the one-slot-per-column
8706 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8707 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8708 /// overwrote the row the pair's chroma-ref half then wanted to read --
8709 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8710 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8711 uv_mode_grid: Vec<u8>,
8712 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8713 /// every other band here).
8714 uv_grid_cols: usize,
8715 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
8716 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
8717 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
8718 /// the `+ss_y` read compares written by the same block?", which is the
8719 /// whole question the `+ss_y` term turns on: the term is only observable
8720 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
8721 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
8722 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
8723 /// in this tile can never be mistaken for a written one.
8724 uv_owner: Vec<u32>,
8725 /// Whether the block above/left of this column/row was coded `skip` --
8726 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8727 /// key-frame writer never tracks (its skip context is always zero); a
8728 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8729 /// `left_skip`.
8730 above_skip: Vec<bool>,
8731 left_skip: Vec<bool>,
8732 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8733 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8734 /// pixels last written over each unit by `set_txfm_ctxs`/
8735 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8736 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8737 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8738 /// array is exactly libaom's per-superblock-row reset, since each mi row
8739 /// is only ever visited inside one superblock row.
8740 above_txfm: Vec<u8>,
8741 left_txfm: Vec<u8>,
8742 /// Whether the block above/left of this column/row coded `skip_mode`
8743 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8744 /// lane-av1comp round 14.
8745 above_skip_mode: Vec<bool>,
8746 left_skip_mode: Vec<bool>,
8747 /// Whether the block above/left was coded inter -- the `is_inter`
8748 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8749 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8750 above_inter: Vec<bool>,
8751 left_inter: Vec<bool>,
8752 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8753 /// alphabet) the block above/left of this column/row coded, or `-1` for
8754 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8755 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8756 /// just "was it inter" (lane-av1refs: every inter block used to be
8757 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8758 /// enough).
8759 above_ref: Vec<i8>,
8760 left_ref: Vec<i8>,
8761 /// The block above/left's *second* reference frame when it was coded
8762 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8763 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8764 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8765 /// `i8`, once a compound `read_ref_frames` lands.
8766 /// lane-publish2 audit: the "always `None` today" note this doc used to
8767 /// carry is long stale -- compound blocks do occur, and
8768 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8769 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8770 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8771 /// [`crate::mvstack::NeighbourRef`] construction (class
8772 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8773 above_ref1: Vec<Option<i8>>,
8774 left_ref1: Vec<Option<i8>>,
8775 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8776 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8777 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8778 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8779 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8780 above_comp_group_idx: Vec<u8>,
8781 left_comp_group_idx: Vec<u8>,
8782 above_compound_idx: Vec<u8>,
8783 left_compound_idx: Vec<u8>,
8784 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8785 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8786 /// block above/left of this column/row -- spec
8787 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8788 above_filter: Vec<[u8; 2]>,
8789 left_filter: Vec<[u8; 2]>,
8790 mi_cols: usize,
8791 mi_rows: usize,
8792 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8793 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8794 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8795 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8796 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8797 /// granularity by [`apply_cdef`] since `skip` is constant across every
8798 /// mi cell one coded block covers.
8799 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8800 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8801 /// the `skip` bit at this mi cell during this frame. A fresh
8802 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8803 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8804 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
8805 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
8806 /// unobservable from the pixels alone. Counted by
8807 /// [`cdef_unwritten_skip_units`].
8808 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
8809 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
8810 /// which re-enables the loop filter at a prediction boundary between two
8811 /// skipped inter blocks (lane-mergefix r4). Written by
8812 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
8813 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
8814 /// that cell -- the other half of `pu_edge`: libaom tests the edge
8815 /// coordinate against the block's size in the FILTERED plane's own
8816 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
8817 blk_grid: Vec<BlkCell>,
8818 skip_grid_cols_mi: usize,
8819 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
8820 /// never splits a coded block's transform below its own size (round 2:
8821 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
8822 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
8823 /// edge-length lookup (`apply_deblock`).
8824 tx_grid: Vec<u8>,
8825 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
8826 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
8827 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
8828 tx_h_grid: Vec<u8>,
8829 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
8830 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
8831 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
8832 /// does NOT follow luma's `tx_depth` split, so deriving it as
8833 /// `tx_grid / 2` invented chroma transform edges the deblocker then
8834 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
8835 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
8836 /// every caller routes through.
8837 uv_tx_grid: Vec<u8>,
8838 uv_tx_h_grid: Vec<u8>,
8839 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
8840 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
8841 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
8842 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
8843 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
8844 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
8845 /// reference onto `LAST_FRAME`'s own delta).
8846 ref_grid: Vec<i8>,
8847 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
8848 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
8849 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
8850 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
8851 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
8852 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
8853 /// to know which mode produced the value.
8854 delta_lf_grid: Vec<[i8; 4]>,
8855 /// The block above/left's own palette-Y size (0 = not a palette block)
8856 /// and its base colours -- `av1_get_palette_mode_ctx`/
8857 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
8858 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
8859 above_palette_size: Vec<u8>,
8860 left_palette_size: Vec<u8>,
8861 above_palette_colors: Vec<[u16; 8]>,
8862 left_palette_colors: Vec<[u16; 8]>,
8863 /// As the four fields above, for the neighbour's own chroma (U-channel
8864 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
8865 /// palette size/colours (lane-palette2 r1).
8866 above_palette_uv_size: Vec<u8>,
8867 left_palette_uv_size: Vec<u8>,
8868 above_palette_uv_colors: Vec<[u16; 8]>,
8869 left_palette_uv_colors: Vec<[u16; 8]>,
8870 /// This tile's own top-left corner, in 4x4 mode-info units (spec
8871 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
8872 /// neighbour" check compares against this instead of literal `0`, since a
8873 /// block at the tile's own top/left edge has no usable neighbour even
8874 /// though a decoded block sits there in the picture (spec `decode_tile`'s
8875 /// per-tile `clear_above_context`/`left_available`/`up_available`).
8876 /// `0` for a single-tile frame, matching every existing caller exactly.
8877 tile_row0_mi: usize,
8878 tile_col0_mi: usize,
8879}
8880
8881#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8882impl Neighbours {
8883 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
8884 /// true (unpadded) size in 4x4 mode-info units.
8885 fn new(
8886 cols: usize,
8887 rows: usize,
8888 mi_cols: usize,
8889 mi_rows: usize,
8890 fctx: &crate::decode::FrameCtx,
8891 ) -> Self {
8892 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
8893 // neighbour state over the whole 64-row extent, past the frame's last
8894 // mi row (mi_rows 198, block rows 192..208). libaom's own context
8895 // buffers are superblock-aligned for exactly that reason
8896 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
8897 // side arrays to a superblock multiple and leave those cells unread --
8898 // every availability check uses the true `mi_rows`/`mi_cols` below.
8899 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
8900 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
8901 Self {
8902 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
8903 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
8904 above_mode: vec![DC_PRED; cols],
8905 left_mode: vec![DC_PRED; rows],
8906 above_uv_mode: vec![DC_PRED; cols],
8907 left_uv_mode: vec![DC_PRED; rows],
8908 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
8909 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
8910 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
8911 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
8912 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8913 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8914 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8915 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8916 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
8917 uv_grid_cols: cols * (SUB / MI),
8918 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
8919 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
8920 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
8921 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
8922 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
8923 // 16x16 block beside it, which a SUB-grid slot cannot name
8924 // (class context-read-from-one-cell).
8925 above_skip: vec![false; cols * (SUB / MI)],
8926 left_skip: vec![false; rows * (SUB / MI)],
8927 above_skip_mode: vec![false; cols * (SUB / MI)],
8928 left_skip_mode: vec![false; rows * (SUB / MI)],
8929 above_inter: vec![false; cols * (SUB / MI)],
8930 left_inter: vec![false; rows * (SUB / MI)],
8931 above_ref: vec![-1; cols * (SUB / MI)],
8932 left_ref: vec![-1; rows * (SUB / MI)],
8933 above_ref1: vec![None; cols * (SUB / MI)],
8934 left_ref1: vec![None; rows * (SUB / MI)],
8935 above_comp_group_idx: vec![0; cols * (SUB / MI)],
8936 left_comp_group_idx: vec![0; rows * (SUB / MI)],
8937 above_compound_idx: vec![0; cols * (SUB / MI)],
8938 left_compound_idx: vec![0; rows * (SUB / MI)],
8939 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
8940 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
8941 mi_cols,
8942 mi_rows,
8943 blk_grid: vec![
8944 BlkCell {
8945 skip: false,
8946 written: false,
8947 org: [0; 2],
8948 dim: [1; 2]
8949 };
8950 cols * (SUB / MI) * rows * (SUB / MI)
8951 ],
8952 skip_grid_cols_mi: cols * (SUB / MI),
8953 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8954 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8955 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8956 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8957 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
8958 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
8959 above_palette_size: vec![0; cols * (SUB / MI)],
8960 left_palette_size: vec![0; rows * (SUB / MI)],
8961 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8962 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8963 above_palette_uv_size: vec![0; cols * (SUB / MI)],
8964 left_palette_uv_size: vec![0; rows * (SUB / MI)],
8965 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8966 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8967 tile_row0_mi: 0,
8968 tile_col0_mi: 0,
8969 }
8970 }
8971
8972 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
8973 /// tile's own column span (`col1_mi` exclusive), plus recording
8974 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
8975 /// availability check below. Left context resets every superblock row
8976 /// regardless of tile ([`Self::start_row`], already called once per SB
8977 /// row by every caller) so it needs no tile-specific reset here.
8978 fn start_tile(
8979 &mut self,
8980 row0_mi: usize,
8981 col0_mi: usize,
8982 col1_mi: usize,
8983 fctx: &crate::decode::FrameCtx,
8984 ) {
8985 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
8986 // are tile-relative, same as every other neighbour lookup here.
8987 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
8988 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
8989 // tile writes, so the `+ss_y` read's "different block?" probe never
8990 // compares against a cell a previous tile left behind.
8991 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
8992 self.tile_row0_mi = row0_mi;
8993 self.tile_col0_mi = col0_mi;
8994 let end = col1_mi.min(self.above.len());
8995 for i in col0_mi.min(end)..end {
8996 self.above[i] = Default::default();
8997 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
8998 }
8999 let (sc0, sc1) = (
9000 col0_mi / (SUB / MI),
9001 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
9002 );
9003 for i in sc0.min(sc1)..sc1 {
9004 self.above_mode[i] = DC_PRED;
9005 self.above_side[i] = NO_NEIGHBOUR_SIDE;
9006 }
9007 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
9008 // the tile's own mi column span directly.
9009 let mend = col1_mi.min(self.above_skip.len());
9010 for i in col0_mi.min(mend)..mend {
9011 self.above_skip[i] = false;
9012 self.above_skip_mode[i] = false;
9013 self.above_inter[i] = false;
9014 self.above_ref[i] = -1;
9015 self.above_ref1[i] = None;
9016 self.above_comp_group_idx[i] = 0;
9017 self.above_compound_idx[i] = 0;
9018 self.above_filter[i] = [3u8; 2];
9019 }
9020 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
9021 // stale `(row, mode)` from the tile to the LEFT names an mi row this
9022 // tile's first block would read as its own above neighbour.
9023 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
9024 for i in col0_mi.min(mcol_end)..mcol_end {
9025 self.sub8_mode_col[i] = (u16::MAX, 0);
9026 self.uv_mode_col[i] = (u16::MAX, 0);
9027 }
9028 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
9029 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
9030 // not zero) -- without it a second tile column reads the first one's
9031 // resolved transform sizes as its own above context.
9032 let tend = col1_mi.min(self.above_txfm.len());
9033 for i in col0_mi.min(tend)..tend {
9034 self.above_txfm[i] = TXFM_CTX_INIT;
9035 }
9036 }
9037
9038 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
9039 /// for a non-palette block, clearing any stale neighbour state) into every
9040 /// [`SUB`]-grid cell it covers on both the above and left edges --
9041 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
9042 /// call sites are all square blocks).
9043 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
9044 self.record_palette_y_rect(
9045 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9046 side,
9047 side,
9048 size,
9049 colors,
9050 );
9051 }
9052
9053 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
9054 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
9055 /// [`Self::record`]): a true rect strip's above/left neighbour spans
9056 /// differ.
9057 fn record_palette_y_rect(
9058 &mut self,
9059 mi: (usize, usize),
9060 w: usize,
9061 h: usize,
9062 size: usize,
9063 colors: [u16; 8],
9064 ) {
9065 let (r, c) = mi;
9066 if crate::envflags::env_flag!("EC_PALPUB") {
9067 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
9068 }
9069 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
9070 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
9071 // cell immediately left of the block, not its 16px [`SUB`] cell. The
9072 // old SUB grid let a 16x8 strip pair share one slot, so the second
9073 // strip of mi(0,8) read the FIRST strip's palette size and the colour
9074 // cache came out one entry short (class [[context-read-from-one-cell]]).
9075 for cell in 0..(w / MI).max(1) {
9076 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
9077 *e = size as u8;
9078 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
9079 // neighbour's colours only where its palette size > 0, so a
9080 // non-palette block need not stamp 16 bytes of zeroes here.
9081 if size > 0 {
9082 self.above_palette_colors[c + cell] = colors;
9083 }
9084 }
9085 }
9086 for cell in 0..(h / MI).max(1) {
9087 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
9088 *e = size as u8;
9089 if size > 0 {
9090 self.left_palette_colors[r + cell] = colors;
9091 }
9092 }
9093 }
9094 }
9095
9096 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
9097 /// neighbours that are themselves a palette-Y block, plus
9098 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
9099 /// cache (pred_common.c:73).
9100 ///
9101 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
9102 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
9103 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
9104 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
9105 /// the ctx too made every superblock in the frame's second SB row read
9106 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
9107 /// palette block decoded as "no palette" and the tile desynced from
9108 /// there (class [[cdf-row-held-constant]]).
9109 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
9110 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9111 }
9112
9113 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
9114 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
9115 /// drops the above neighbour on a 64-px superblock boundary
9116 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
9117 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
9118 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
9119 /// every strip in an SB's top cell row, which libaom does not do.
9120 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
9121 let (r, c) = mi;
9122 let above_ok = r % 16 != 0;
9123 // `xd->above_mbmi` exists for every row but the tile's own first.
9124 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
9125 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
9126 (
9127 usize::from(self.above_palette_size[c]),
9128 self.above_palette_colors[c],
9129 )
9130 } else {
9131 (0, [0u16; 8])
9132 };
9133 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
9134 // is NULL whenever the block sits at its TILE's own left column
9135 // (`left_available`), not the frame's -- without this guard a second
9136 // tile column reads the previous tile's palette colours into its cache
9137 // and its `palette_y_mode` ctx.
9138 let left_ok = c > self.tile_col0_mi;
9139 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
9140 (
9141 usize::from(self.left_palette_size[r]),
9142 self.left_palette_colors[r],
9143 )
9144 } else {
9145 (0, [0u16; 8])
9146 };
9147 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
9148 let mut cache = Vec::with_capacity(16);
9149 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9150 if cache.last() != Some(&v) {
9151 cache.push(v);
9152 }
9153 };
9154 let (mut ai, mut li) = (0usize, 0usize);
9155 while ai < above_n && li < left_n {
9156 let (va, vl) = (above_colors[ai], left_colors[li]);
9157 if vl < va {
9158 push_dedup(&mut cache, vl);
9159 li += 1;
9160 } else {
9161 push_dedup(&mut cache, va);
9162 ai += 1;
9163 if vl == va {
9164 li += 1;
9165 }
9166 }
9167 }
9168 while ai < above_n {
9169 push_dedup(&mut cache, above_colors[ai]);
9170 ai += 1;
9171 }
9172 while li < left_n {
9173 push_dedup(&mut cache, left_colors[li]);
9174 li += 1;
9175 }
9176 (ctx, cache)
9177 }
9178
9179 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
9180 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9181 /// same way (lane-palette2 r1).
9182 fn record_palette_uv(
9183 &mut self,
9184 at: (usize, usize),
9185 side: usize,
9186 size: usize,
9187 colors: [u16; 8],
9188 ) {
9189 self.record_palette_uv_rect(
9190 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9191 side,
9192 side,
9193 size,
9194 colors,
9195 );
9196 }
9197
9198 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9199 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9200 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9201 /// luma resolution regardless of which plane the recorded state is for).
9202 fn record_palette_uv_rect(
9203 &mut self,
9204 mi: (usize, usize),
9205 w: usize,
9206 h: usize,
9207 size: usize,
9208 colors: [u16; 8],
9209 ) {
9210 let (r, c) = mi;
9211 // mi granularity, see [`Self::record_palette_y_rect`].
9212 for cell in 0..(w / MI).max(1) {
9213 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9214 *e = size as u8;
9215 if size > 0 {
9216 self.above_palette_uv_colors[c + cell] = colors;
9217 }
9218 }
9219 }
9220 for cell in 0..(h / MI).max(1) {
9221 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9222 *e = size as u8;
9223 if size > 0 {
9224 self.left_palette_uv_colors[r + cell] = colors;
9225 }
9226 }
9227 }
9228 }
9229
9230 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9231 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9232 /// no neighbour lookup at all (it is this block's own just-decided Y
9233 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9234 /// so only the cache is wanted here.
9235 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9236 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9237 }
9238
9239 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9240 /// [`Self::palette_ctx_and_cache_mi`].
9241 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9242 let (r, c) = mi;
9243 let above_ok = r % 16 != 0;
9244 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9245 (
9246 usize::from(self.above_palette_uv_size[c]),
9247 self.above_palette_uv_colors[c],
9248 )
9249 } else {
9250 (0, [0u16; 8])
9251 };
9252 // Same tile-relative left availability as the luma cache above.
9253 let left_ok = c > self.tile_col0_mi;
9254 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9255 (
9256 usize::from(self.left_palette_uv_size[r]),
9257 self.left_palette_uv_colors[r],
9258 )
9259 } else {
9260 (0, [0u16; 8])
9261 };
9262 let mut cache = Vec::with_capacity(16);
9263 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9264 if cache.last() != Some(&v) {
9265 cache.push(v);
9266 }
9267 };
9268 let (mut ai, mut li) = (0usize, 0usize);
9269 while ai < above_n && li < left_n {
9270 let (va, vl) = (above_colors[ai], left_colors[li]);
9271 if vl < va {
9272 push_dedup(&mut cache, vl);
9273 li += 1;
9274 } else {
9275 push_dedup(&mut cache, va);
9276 ai += 1;
9277 if vl == va {
9278 li += 1;
9279 }
9280 }
9281 }
9282 while ai < above_n {
9283 push_dedup(&mut cache, above_colors[ai]);
9284 ai += 1;
9285 }
9286 while li < left_n {
9287 push_dedup(&mut cache, left_colors[li]);
9288 li += 1;
9289 }
9290 cache
9291 }
9292
9293 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9294 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9295 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9296 /// units as [`Self::fill_skip_grid`].
9297 fn fill_lf_grid(
9298 &mut self,
9299 at_mi: (usize, usize),
9300 side_mi: usize,
9301 tx_px: u8,
9302 ref_frame: i8,
9303 fctx: &crate::decode::FrameCtx,
9304 ) {
9305 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9306 }
9307
9308 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9309 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9310 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9311 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9312 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9313 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9314 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9315 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9316 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9317 /// block's published transform extent to its own size is exactly that
9318 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9319 /// that needs it is the 128 root, whose chroma extent is the one
9320 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9321 /// never suppressed (libaom's `is_inter_block` term), so this is called
9322 /// only from the skipped-inter branch.
9323 ///
9324 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
9325 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
9326 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
9327 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
9328 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
9329 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
9330 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
9331 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
9332 /// no format guard was possible inside this method until now.
9333 ///
9334 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
9335 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
9336 /// every edge it lets through then meets the SAME libaom rule applied at
9337 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
9338 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
9339 /// skip_at && skip_at`. Inside one skipped block both cells are that same
9340 /// block, so all four terms hold and the edge dies there too. The masking
9341 /// is TOTAL, not incidental: this method is only ever called for a block
9342 /// that is itself skipped, so no input exists on which one side of an
9343 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
9344 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
9345 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
9346 /// differ from each other in not one sample. The gate for this value is
9347 /// therefore a source scan, not a pixel gate --
9348 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
9349 fn suppress_internal_lf_edges(
9350 &mut self,
9351 at_mi: (usize, usize),
9352 w_mi: usize,
9353 h_mi: usize,
9354 fctx: &FrameCtx,
9355 ) {
9356 let (mi_r, mi_c) = at_mi;
9357 let (uv_w, uv_h) = (
9358 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
9359 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
9360 );
9361 for rr in 0..h_mi {
9362 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9363 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9364 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9365 }
9366 }
9367
9368 fn fill_lf_grid_rect(
9369 &mut self,
9370 at_mi: (usize, usize),
9371 w_mi: usize,
9372 h_mi: usize,
9373 tx_px: u8,
9374 tx_h_px: u8,
9375 ref_frame: i8,
9376 fctx: &crate::decode::FrameCtx,
9377 ) {
9378 let (mi_r, mi_c) = at_mi;
9379 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9380 // half its luma one (min 4 px, the smallest transform), capped at
9381 // TX_32X32 -- independent of this block's luma `tx_depth`.
9382 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9383 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9384 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9385 eprintln!(
9386 "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}"
9387 );
9388 }
9389 crate::census::tx(tx_px, tx_h_px);
9390 let cur = fctx.current_delta_lf.with(|c| c.get());
9391 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9392 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9393 } else {
9394 [cur[0].clamp(-63, 63) as i8; 4]
9395 };
9396 for rr in 0..h_mi {
9397 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9398 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9399 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9400 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9401 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9402 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9403 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9404 }
9405 if fctx.intra_only.with(std::cell::Cell::get) {
9406 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9407 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9408 // xd)` for EVERY block, an intra-only frame's included, and
9409 // `get_tx_size_context` / `txfm_partition_context` read those two
9410 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9411 // over the same footprint, so the publish is this write: the
9412 // `skip && is_inter` term is 0 for every intra-only block that is
9413 // not an intrabc one, and the bodies that can code an intrabc
9414 // block publish their own (the term is then the BLOCK size, a value
9415 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9416 // Inter frames publish at their own sites and are excluded here
9417 // because their skipped-block term needs the block size too.
9418 txfm_partition_update_rect(
9419 self,
9420 at_mi,
9421 (tx_px as usize, tx_h_px as usize),
9422 (w_mi * MI, h_mi * MI),
9423 );
9424 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9425 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9426 // instead of its transform band. Every block stamps its own cells
9427 // here; the intrabc bodies re-stamp theirs `true` afterwards
9428 // (`record_intrabc_inter_bands`).
9429 for i in 0..w_mi {
9430 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9431 *cell = false;
9432 }
9433 }
9434 for i in 0..h_mi {
9435 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9436 *cell = false;
9437 }
9438 }
9439 }
9440 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9441 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9442 // not just the intrabc ones. A later intrabc block's DV predictor is
9443 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9444 // `MB_MODE_INFO` for EVERY block and steps by
9445 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9446 // non-intrabc neighbour reads as uncovered and the scan advances it
9447 // by one cell instead of by its real width.
9448 fctx.intrabc_mi_grid.with(|g| {
9449 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9450 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9451 }
9452 });
9453 }
9454
9455 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9456 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9457 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9458 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9459 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9460 /// dims from the LEAF span and so invented chroma transform edges the
9461 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9462 /// are already correct from the block's own fill over the same span.
9463 fn fill_lf_grid_leaf_luma(
9464 &mut self,
9465 at_mi: (usize, usize),
9466 w_mi: usize,
9467 h_mi: usize,
9468 tx_px: u8,
9469 tx_h_px: u8,
9470 ) {
9471 let (mi_r, mi_c) = at_mi;
9472 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9473 eprintln!(
9474 "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}"
9475 );
9476 }
9477 for rr in 0..h_mi {
9478 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9479 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9480 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9481 }
9482 }
9483
9484 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9485 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9486 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9487 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9488 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9489 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9490 }
9491
9492 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9493 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9494 let (mi_r, mi_c) = at_mi;
9495 if skip && w_mi != h_mi {
9496 hit!(RECT_SKIP_BAND_HITS);
9497 }
9498 // lane-census: an INTRA frame's blocks never reach the inter
9499 // publisher, and this one is what every coded block writes.
9500 crate::census::block_intra_frame(w_mi, h_mi, skip);
9501 for rr in 0..h_mi {
9502 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9503 fill_span(
9504 &mut self.blk_grid,
9505 start,
9506 w_mi,
9507 BlkCell {
9508 skip,
9509 written: true,
9510 org: [mi_r as u16, mi_c as u16],
9511 dim: [w_mi as u8, h_mi as u8],
9512 },
9513 );
9514 }
9515 }
9516
9517 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
9518 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
9519 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
9520 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
9521 /// straddle the region with a mix of skip/non-skip blocks).
9522 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
9523 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
9524 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
9525 /// filtered edge's two sides are each exactly one coded block wide.
9526 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
9527 self.blk_grid
9528 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9529 .is_some_and(|c| c.skip)
9530 }
9531
9532 /// The `skip_txfm` context of a block whose top-left mi cell is
9533 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
9534 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
9535 /// with an absent neighbour contributing 0. The mi grid is per tile, so
9536 /// row/column 0 is a tile edge and has no neighbour on that axis.
9537 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
9538 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
9539 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
9540 }
9541
9542 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
9543 (0..2).all(|rr| {
9544 (0..2).all(|cc| {
9545 self.blk_grid
9546 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
9547 .is_some_and(|c| c.skip)
9548 })
9549 })
9550 }
9551
9552 fn start_row(&mut self) {
9553 self.left.iter_mut().for_each(|l| *l = Default::default());
9554 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
9555 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
9556 self.left_side
9557 .iter_mut()
9558 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
9559 self.left_side_mi
9560 .iter_mut()
9561 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
9562 self.left_skip.iter_mut().for_each(|s| *s = false);
9563 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
9564 self.left_inter.iter_mut().for_each(|i| *i = false);
9565 self.left_ref.iter_mut().for_each(|r| *r = -1);
9566 self.left_ref1.iter_mut().for_each(|r| *r = None);
9567 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
9568 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9569 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
9570 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
9571 // context (a tile/SB-row boundary has no left neighbour).
9572 self.sub8_mode_row
9573 .iter_mut()
9574 .for_each(|s| *s = (u16::MAX, 0));
9575 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
9576 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
9577 // are per-mi maps like every other one here, so they reset with the
9578 // row too -- the left guard above is what actually stops a cross-tile
9579 // read, this keeps a stale colour out of the arrays at all.
9580 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
9581 self.left_palette_colors
9582 .iter_mut()
9583 .for_each(|c| *c = [0u16; 8]);
9584 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
9585 self.left_palette_uv_colors
9586 .iter_mut()
9587 .for_each(|c| *c = [0u16; 8]);
9588 // lane-mergefix r2: `av1_zero_left_context` memsets
9589 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
9590 // every superblock row of every tile -- the var-tx left context does
9591 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
9592 // previous tile column's last block otherwise).
9593 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9594 }
9595
9596 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
9597 /// block that reads it as a neighbour -- [`crate::tile`]'s
9598 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9599 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9600 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9601 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9602 /// the real value, not just `is_inter`).
9603 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9604 fn record_inter(
9605 &mut self,
9606 at: (usize, usize),
9607 side: usize,
9608 skip: bool,
9609 is_inter: bool,
9610 ref_frame: i8,
9611 filter: [u8; 2],
9612 skip_mode: bool,
9613 ) {
9614 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9615 }
9616
9617 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9618 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9619 /// r1: a true rectangular strip's above-context span (its own width) and
9620 /// left-context span (its own height) differ, unlike every caller before
9621 /// this round (class neighbour-votes-all-its-fields).
9622 #[allow(clippy::too_many_arguments)]
9623 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9624 fn record_inter_rect(
9625 &mut self,
9626 at: (usize, usize),
9627 w_sub: usize,
9628 h_sub: usize,
9629 skip: bool,
9630 is_inter: bool,
9631 ref_frame: i8,
9632 filter: [u8; 2],
9633 skip_mode: bool,
9634 ) {
9635 let (r, c) = at;
9636 self.record_inter_rect_mi(
9637 (r * (SUB / MI), c * (SUB / MI)),
9638 w_sub / MI,
9639 h_sub / MI,
9640 skip,
9641 is_inter,
9642 ref_frame,
9643 filter,
9644 skip_mode,
9645 );
9646 }
9647
9648 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9649 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9650 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9651 /// routes through the wrapper above.
9652 #[allow(clippy::too_many_arguments)]
9653 fn record_inter_rect_mi(
9654 &mut self,
9655 at_mi: (usize, usize),
9656 w_mi: usize,
9657 h_mi: usize,
9658 skip: bool,
9659 is_inter: bool,
9660 ref_frame: i8,
9661 filter: [u8; 2],
9662 skip_mode: bool,
9663 ) {
9664 let (r, c) = at_mi;
9665 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9666 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9667 // writes for a whole block class): an INTER block left the luma mode
9668 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9669 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9670 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9671 // block in that pixel row -- the directional edge filter then ran at
9672 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9673 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9674 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9675 // already stamped it).
9676 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9677 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9678 // uv map must read DC_PRED over an inter block's cells too.
9679 if is_inter {
9680 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9681 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9682 }
9683 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9684 self.above_skip[c..c + w_mi].fill(skip);
9685 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9686 self.above_inter[c..c + w_mi].fill(is_inter);
9687 self.above_ref[c..c + w_mi].fill(ref_frame);
9688 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9689 // this with the block's real second reference for a compound block,
9690 // called right after this one (lane-publish2 audit).
9691 self.above_ref1[c..c + w_mi].fill(None);
9692 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9693 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9694 // as `3`/`1` even though this block has no second reference.
9695 // `record_compound_ctx` overwrites this with the real bit for an
9696 // actual compound block's cells, called right after this one.
9697 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9698 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9699 self.above_filter[c..c + w_mi].fill(filter);
9700 self.left_skip[r..r + h_mi].fill(skip);
9701 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9702 self.left_inter[r..r + h_mi].fill(is_inter);
9703 self.left_ref[r..r + h_mi].fill(ref_frame);
9704 self.left_ref1[r..r + h_mi].fill(None);
9705 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9706 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9707 self.left_filter[r..r + h_mi].fill(filter);
9708 }
9709
9710 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9711 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9712 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9713 /// `get_comp_index_context`) -- called right after `record_inter` for
9714 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9715 /// stamps `above_ref1`/`left_ref1` with the block's real second
9716 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9717 /// this is the one caller that actually knows it) -- so the next block's
9718 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9719 /// neighbour instead of `record_inter`'s single-ref default.
9720 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9721 fn record_compound_ctx(
9722 &mut self,
9723 at: (usize, usize),
9724 side: usize,
9725 ref1: i8,
9726 comp_group_idx: u8,
9727 compound_idx: u8,
9728 ) {
9729 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
9730 }
9731
9732 /// [`Self::record_compound_ctx`] with independent above/left extents,
9733 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
9734 #[allow(clippy::too_many_arguments)]
9735 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9736 fn record_compound_ctx_rect(
9737 &mut self,
9738 at: (usize, usize),
9739 w_sub: usize,
9740 h_sub: usize,
9741 ref1: i8,
9742 comp_group_idx: u8,
9743 compound_idx: u8,
9744 ) {
9745 let (r, c) = at;
9746 self.record_compound_ctx_rect_mi(
9747 (r * (SUB / MI), c * (SUB / MI)),
9748 w_sub / MI,
9749 h_sub / MI,
9750 ref1,
9751 comp_group_idx,
9752 compound_idx,
9753 );
9754 }
9755
9756 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
9757 /// [`Self::record_inter_rect_mi`]).
9758 fn record_compound_ctx_rect_mi(
9759 &mut self,
9760 at_mi: (usize, usize),
9761 w_mi: usize,
9762 h_mi: usize,
9763 ref1: i8,
9764 comp_group_idx: u8,
9765 compound_idx: u8,
9766 ) {
9767 let (r, c) = at_mi;
9768 crate::census::compound();
9769 for cell in 0..w_mi {
9770 self.above_ref1[c + cell] = Some(ref1);
9771 self.above_comp_group_idx[c + cell] = comp_group_idx;
9772 self.above_compound_idx[c + cell] = compound_idx;
9773 }
9774 for cell in 0..h_mi {
9775 self.left_ref1[r + cell] = Some(ref1);
9776 self.left_comp_group_idx[r + cell] = comp_group_idx;
9777 self.left_compound_idx[r + cell] = compound_idx;
9778 }
9779 }
9780
9781 /// The context of a block's partition symbol: delegates to the mi-precise
9782 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9783 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
9784 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
9785 /// only touches the finer mi arrays -- leaves them stale for the *next*
9786 /// sibling's own partition symbol.
9787 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
9788 let (r, c) = at;
9789 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
9790 }
9791
9792 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
9793 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
9794 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
9795 /// than the enclosing 16x16 slot's stale, shared state.
9796 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9797 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
9798 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
9799 }
9800
9801 /// The gathered coded/DC-sign state of the blocks above and to the left
9802 /// of a block `side` samples across, per plane.
9803 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9804 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
9805 }
9806
9807 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
9808 /// units, for the same reason [`Self::record_mi`] does.
9809 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9810 let side_mi = side / MI;
9811 // One pass over the cells accumulating all three planes, not one pass
9812 // per plane: the three planes of a cell live in the same
9813 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
9814 // cache lines three times (lane-publish). Clamp each edge to the true
9815 // frame extent: a block at the right/bottom edge may be padded beyond
9816 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
9817 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
9818 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
9819 let mut out = [(false, false, 0i32); 3];
9820 for cell in 0..above_mi {
9821 let above = &self.above[mi_c + cell];
9822 for (plane, o) in out.iter_mut().enumerate() {
9823 o.0 |= above[plane].level != 0;
9824 o.2 += dc_vote(above[plane].dc);
9825 }
9826 }
9827 for cell in 0..left_mi {
9828 let left = &self.left[mi_r + cell];
9829 for (plane, o) in out.iter_mut().enumerate() {
9830 o.1 |= left[plane].level != 0;
9831 o.2 += dc_vote(left[plane].dc);
9832 }
9833 }
9834 out
9835 }
9836
9837 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
9838 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
9839 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
9840 /// spans TWO luma mi columns. Both cells of a column carry the covering
9841 /// unit's whole-unit dc sign (the same value libaom stores), so the
9842 /// per-luma-mi sum counts each chroma column twice -- and
9843 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
9844 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
9845 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
9846 /// Sampling every second above cell counts each chroma column once,
9847 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
9848 /// its per-mi cells already line up one-to-one. The level booleans are
9849 /// ORs over duplicated cells, so the sampling cannot change them.
9850 fn around_mi_422_chroma(
9851 &self,
9852 (mi_r, mi_c): (usize, usize),
9853 w: usize,
9854 h: usize,
9855 ) -> [(bool, bool, i32); 3] {
9856 let (w_mi, h_mi) = (w / MI, h / MI);
9857 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9858 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9859 let mut out = [(false, false, 0i32); 3];
9860 for cell in (0..above_mi).step_by(2) {
9861 let above = &self.above[mi_c + cell];
9862 for (plane, o) in out.iter_mut().enumerate() {
9863 o.0 |= above[plane].level != 0;
9864 o.2 += dc_vote(above[plane].dc);
9865 }
9866 }
9867 for cell in 0..left_mi {
9868 let left = &self.left[mi_r + cell];
9869 for (plane, o) in out.iter_mut().enumerate() {
9870 o.1 |= left[plane].level != 0;
9871 o.2 += dc_vote(left[plane].dc);
9872 }
9873 }
9874 if crate::envflags::env_flag!("EC_DCDUMP") {
9875 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
9876 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
9877 // The above rows are the SAMPLED (every-second) cells.
9878 for (plane, o) in out.iter().enumerate() {
9879 let vote = o.2;
9880 let ab: Vec<String> = (0..above_mi)
9881 .step_by(2)
9882 .map(|k| {
9883 format!(
9884 "{:?}/{}",
9885 self.above[mi_c + k][plane].dc,
9886 self.above[mi_c + k][plane].level
9887 )
9888 })
9889 .collect();
9890 let lf: Vec<String> = (0..left_mi)
9891 .map(|k| {
9892 format!(
9893 "{:?}/{}",
9894 self.left[mi_r + k][plane].dc,
9895 self.left[mi_r + k][plane].level
9896 )
9897 })
9898 .collect();
9899 eprintln!(
9900 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9901 ab.join(","),
9902 lf.join(",")
9903 );
9904 }
9905 }
9906 out
9907 }
9908
9909 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
9910 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
9911 /// extent pattern for a true rectangular strip's own coefficient context.
9912 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
9913 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
9914 }
9915
9916 /// [`Self::around_rect`] taking the block's position directly in 4x4
9917 /// mode-info units, mirroring [`Self::around_mi`].
9918 fn around_mi_rect(
9919 &self,
9920 (mi_r, mi_c): (usize, usize),
9921 w: usize,
9922 h: usize,
9923 ) -> [(bool, bool, i32); 3] {
9924 let (w_mi, h_mi) = (w / MI, h / MI);
9925 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9926 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9927 // [`Self::around_mi`]'s single pass, with the two extents split.
9928 let mut out = [(false, false, 0i32); 3];
9929 for cell in 0..above_mi {
9930 let above = &self.above[mi_c + cell];
9931 for (plane, o) in out.iter_mut().enumerate() {
9932 o.0 |= above[plane].level != 0;
9933 o.2 += dc_vote(above[plane].dc);
9934 }
9935 }
9936 for cell in 0..left_mi {
9937 let left = &self.left[mi_r + cell];
9938 for (plane, o) in out.iter_mut().enumerate() {
9939 o.1 |= left[plane].level != 0;
9940 o.2 += dc_vote(left[plane].dc);
9941 }
9942 }
9943 if crate::envflags::env_flag!("EC_DCDUMP") {
9944 for (plane, o) in out.iter().enumerate() {
9945 let vote = o.2;
9946 let ab: Vec<String> = (0..above_mi)
9947 .map(|k| {
9948 format!(
9949 "{:?}/{}",
9950 self.above[mi_c + k][plane].dc,
9951 self.above[mi_c + k][plane].level
9952 )
9953 })
9954 .collect();
9955 let lf: Vec<String> = (0..left_mi)
9956 .map(|k| {
9957 format!(
9958 "{:?}/{}",
9959 self.left[mi_r + k][plane].dc,
9960 self.left[mi_r + k][plane].level
9961 )
9962 })
9963 .collect();
9964 eprintln!(
9965 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9966 ab.join(","),
9967 lf.join(",")
9968 );
9969 }
9970 }
9971 out
9972 }
9973
9974 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
9975 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
9976 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
9977 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
9978 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
9979 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
9980 /// is always 0, spec's `plane_bsize == tx_size` branch).
9981 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
9982 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
9983 }
9984
9985 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
9986 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
9987 /// context over `tx_size_wide` and the left one over `tx_size_high`.
9988 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
9989 let side_mi = w_mi;
9990 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9991 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9992 let mut top = 0u8;
9993 let mut left = 0u8;
9994 for cell in 0..above_mi {
9995 top |= self.above[mi_c + cell][0].level;
9996 }
9997 for cell in 0..left_mi {
9998 left |= self.left[mi_r + cell][0].level;
9999 }
10000 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
10001 if crate::envflags::env_flag!("EC_ECDUMP") {
10002 let ab: Vec<String> = (0..above_mi)
10003 .map(|k| self.above[mi_c + k][0].level.to_string())
10004 .collect();
10005 let lf: Vec<String> = (0..left_mi)
10006 .map(|k| self.left[mi_r + k][0].level.to_string())
10007 .collect();
10008 // lane-av1mix: the last few msac register states, so the
10009 // byte-position of the `all_zero` read can be matched against
10010 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
10011 // second run.
10012 let recent = crate::msac::symtrace::ecdump_recent(4)
10013 .iter()
10014 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
10015 .collect::<Vec<_>>()
10016 .join(" ");
10017 eprintln!(
10018 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
10019 ab.join(","),
10020 lf.join(","),
10021 recent
10022 );
10023 }
10024 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10025 eprintln!(
10026 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
10027 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
10028 );
10029 }
10030 ctx
10031 }
10032
10033 /// Writes one coded block into every cell it covers, on both grids: the
10034 /// mode/side arrays up to `side`'s own width, and the coefficient-context
10035 /// arrays up to the true frame edge — the units past it are left at their
10036 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
10037 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
10038 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
10039 /// not from this block's own side).
10040 fn record(
10041 &mut self,
10042 at: (usize, usize),
10043 side: usize,
10044 mode: usize,
10045 uv_mode: usize,
10046 grids: &[&[i32]; 3],
10047 ) {
10048 self.record_rect(at, side, side, mode, uv_mode, grids);
10049 }
10050
10051 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
10052 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
10053 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
10054 /// spec's per-edge partition-context rule, so a true rectangular block
10055 /// naturally wants two different values here rather than one.
10056 /// Writes this block's luma `mode` into the mi-granular
10057 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
10058 /// position a *later* neighbour would read it from: the block's LAST mi
10059 /// row for every column it spans (what the block below reads via
10060 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
10061 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
10062 /// read these back, and only when the recorded position is exactly their
10063 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
10064 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
10065 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
10066 let mode = mode as u8;
10067 for cell in 0..mi_w {
10068 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
10069 *slot = (last_r, mode);
10070 }
10071 }
10072 for cell in 0..mi_h {
10073 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
10074 *slot = (last_c, mode);
10075 }
10076 }
10077 }
10078
10079 /// The mi-exact above/left neighbour luma mode for a block whose top-left
10080 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
10081 /// mi position (then the coarse [`SUB`]-grid slot is right by
10082 /// construction). See [`Self::record_mode_mi`].
10083 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10084 match self.sub8_mode_col.get(mi_c) {
10085 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
10086 Some(usize::from(m))
10087 }
10088 _ => None,
10089 }
10090 }
10091
10092 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10093 match self.sub8_mode_row.get(mi_r) {
10094 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
10095 Some(usize::from(m))
10096 }
10097 _ => None,
10098 }
10099 }
10100
10101 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
10102 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
10103 fn record_uv_mode_mi(
10104 &mut self,
10105 mi_r: usize,
10106 mi_c: usize,
10107 mi_w: usize,
10108 mi_h: usize,
10109 uv_mode: usize,
10110 ) {
10111 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
10112 fill_span(
10113 &mut self.uv_mode_col,
10114 mi_c,
10115 mi_w,
10116 (last_r as u16, uv_mode as u8),
10117 );
10118 fill_span(
10119 &mut self.uv_mode_row,
10120 mi_r,
10121 mi_h,
10122 (last_c as u16, uv_mode as u8),
10123 );
10124 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
10125 // covers, so the chroma neighbour read below is a plain grid read.
10126 let stride = self.uv_grid_cols;
10127 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
10128 for row in mi_r..=last_r {
10129 fill_span(
10130 &mut self.uv_mode_grid,
10131 row * stride + mi_c,
10132 n,
10133 uv_mode as u8,
10134 );
10135 }
10136 // lane-av1leftwit: stamp the writing block's own mi over its extent,
10137 // the same cells and the same clipping as `uv_mode_grid` above.
10138 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
10139 for row in mi_r..=last_r {
10140 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
10141 }
10142 if crate::envflags::env_flag!("EC_LEFTSSY") {
10143 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
10144 }
10145 }
10146
10147 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
10148 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
10149 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
10150 /// block has recorded the exact neighbouring mi.
10151 fn smooth_uv_neighbour(
10152 &self,
10153 mi_r: usize,
10154 mi_c: usize,
10155 r: usize,
10156 c: usize,
10157 fctx: &crate::decode::FrameCtx,
10158 ) -> bool {
10159 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
10160 // REFERENCE block, not off the mi that carries the chroma syntax.
10161 // `set_mi_row_col` (`blockd.h`) takes
10162 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
10163 // only then `chroma_above_mbmi = base_mi[-stride]` /
10164 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
10165 // the ODD mi, so without the snap we looked one mi row/column too far
10166 // down/right -- the mi-exact slot never matched and the coarse
10167 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
10168 // 8x4 at (688, 100) = mi (51, 344): libaom's
10169 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
10170 // `UV_SMOOTH_PRED`), ours was 0, which flips
10171 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
10172 // false for type 1, TRUE for type 0) and upsampled an edge libaom
10173 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
10174 // predicting from it (class `context-read-from-one-cell`).
10175 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
10176 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
10177 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
10178 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
10179 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
10180 let snap_y = (1usize << ss_y(fctx)) - 1;
10181 let snap_x = (1usize << ss_x(fctx)) - 1;
10182 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
10183 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
10184 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
10185 // the two chroma-reference offsets on top of it -- see its own comment
10186 // for which axis each one moves.
10187 self.smooth_uv_neighbour_unsnapped(
10188 mi_r & !snap_y,
10189 mi_c & !snap_x,
10190 r,
10191 c,
10192 ss_x(fctx),
10193 ss_y(fctx),
10194 true,
10195 )
10196 }
10197
10198 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
10199 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
10200 /// counter wants this: it measures how often the snap CHANGES the answer,
10201 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
10202 /// decode path uses the snapping form.
10203 /// `decode_path` is `true` only for the snapping form every decode call
10204 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
10205 /// `+ss_y` counters measure a read that actually filters a chroma edge and
10206 /// not the counter-only one.
10207 ///
10208 /// lane-av1leftwit: the mirror's justification used to be "no committed
10209 /// fixture reaches the shape on the decode path", and that was false --
10210 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
10211 /// counter-only mirror at an ODD mi row is still not a decode-path read,
10212 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
10213 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
10214 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
10215 fn smooth_uv_neighbour_unsnapped(
10216 &self,
10217 mi_r: usize,
10218 mi_c: usize,
10219 r: usize,
10220 c: usize,
10221 ss_x: usize,
10222 ss_y: usize,
10223 decode_path: bool,
10224 ) -> bool {
10225 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10226 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10227 // array that `start_tile` does not clear, so a block on a tile's first
10228 // mi row used to read the uv_mode of the block above it in the tile
10229 // ABOVE and filter its chroma edge at that neighbour's strength
10230 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10231 // at chroma (120, 32), the top-right tile's first block).
10232 let have_above = mi_r > self.tile_row0_mi;
10233 let have_left = mi_c > self.tile_col0_mi;
10234 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10235 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10236 {
10237 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10238 }
10239 // The mi grid is libaom's own read; the two maps below stay as the
10240 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10241 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10242 (col < self.uv_grid_cols)
10243 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10244 .flatten()
10245 .filter(|&m| m != u8::MAX)
10246 .map(usize::from)
10247 };
10248 // libaom's two chroma-reference mi, from `set_mi_row_col`
10249 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10250 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10251 // snap -- i.e. already libaom's `base_mi`:
10252 //
10253 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10254 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10255 //
10256 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10257 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10258 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10259 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10260 // boolean it feeds is simply not exercised differently by that stream
10261 // at its blocks. One chroma column spans two luma mi columns, so the
10262 // chroma edge reaches into the right-hand luma block, and that is where
10263 // its reference lives.
10264 //
10265 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10266 // last open item lane-av1422warp carried. libaom puts the left
10267 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10268 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10269 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10270 // read (the above) and regressed the byte-exact 4:2:0 control, which
10271 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10272 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10273 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10274 // measured. Measured over all 48 committed fixtures that decode
10275 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10276 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10277 // put a 1-mi-tall left neighbour in front of a decode-path read at
10278 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10279 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10280 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10281 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10282 // changing is what is still unwitnessed.
10283 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10284 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10285 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10286 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10287 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10288 // row at every subsampling. The term is only observable when the two
10289 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10290 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10291 // and only libaom's is the chroma reference. Three counters measure
10292 // that, and the third is the one the other two need: a read can only
10293 // differ if the two cells are written by DIFFERENT blocks, which
10294 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10295 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10296 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10297 // reads > 0 is the term being unobservable on real material, not
10298 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10299 // whether the mode value, and the boolean this feeds
10300 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10301 // edge filter), actually moved.
10302 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10303 let read_left = |row: usize| -> usize {
10304 match self.uv_mode_row.get(row) {
10305 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10306 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10307 _ if have_left => self.left_uv_mode[r],
10308 _ => DC_PRED,
10309 }
10310 };
10311 let above = match self.uv_mode_col.get(above_mi.1) {
10312 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10313 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10314 _ if have_above => self.above_uv_mode[c],
10315 _ => DC_PRED,
10316 };
10317 let left = read_left(left_mi.0);
10318 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10319 // how many chroma edge-filter-type reads took this path at all, so a
10320 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10321 // term did not change the answer". The two DIFF buckets compare
10322 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10323 // every committed fixture and every one of the ~1000 encodes swept in
10324 // `lanes/av1leftref.report.md`, which is what makes the read change a
10325 // proven no-op on today's material rather than an unmeasured guess.
10326 if decode_path && have_left && ss_y > 0 {
10327 hit!(UV_LEFT_SS_Y_READS);
10328 // The pre-lane read, kept as the counter's own-row arm: it is what
10329 // this decoder answered before the `+ss_y` term landed, and
10330 // comparing against it is what proves the term is load-bearing.
10331 let own_row = read_left(mi_r);
10332 if own_row != left {
10333 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10334 }
10335 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10336 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10337 }
10338 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10339 // cells are one left mi column apart, so they are two different
10340 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10341 let col = left_mi.1;
10342 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10343 let own = (col < self.uv_grid_cols)
10344 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10345 .flatten()
10346 .filter(|o| o & 0xff00_0000 == epoch)
10347 .unwrap_or(0);
10348 let down = self
10349 .uv_owner
10350 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10351 .copied()
10352 .filter(|o| o & 0xff00_0000 == epoch)
10353 .unwrap_or(0);
10354 if own != 0 && down != 0 && own != down {
10355 hit!(UV_LEFT_1MI_SPLIT_HITS);
10356 if crate::envflags::env_flag!("EC_LEFTSSY") {
10357 eprintln!(
10358 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10359 owners=({},{})->({},{}) modes={own_row}/{left}",
10360 epoch >> 24,
10361 own >> 12 & 0xfff,
10362 own & 0xfff,
10363 down >> 12 & 0xfff,
10364 down & 0xfff,
10365 );
10366 }
10367 }
10368 }
10369 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10370 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10371 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10372 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10373 }) {
10374 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10375 }
10376 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10377 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10378 // have been filtered at the wrong strength by the coarse map alone.
10379 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10380 hit!(UV_MODE_MI_OVERRIDE_HITS);
10381 }
10382 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10383 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10384 {
10385 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10386 }
10387 is_smooth_mode(above) || is_smooth_mode(left)
10388 }
10389
10390 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10391 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10392 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10393 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10394 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10395 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10396 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10397 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10398 /// a different CDF for the same mode value).
10399 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10400 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10401 /// only when `up_available` and `left_mbmi` only when `left_available`;
10402 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10403 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10404 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10405 /// strip's mode as its "left neighbour" (measured on the band fixture at
10406 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10407 fn modes_above_left_mi(
10408 &self,
10409 mi_r: usize,
10410 mi_c: usize,
10411 fallback: (usize, usize),
10412 ) -> (usize, usize) {
10413 let above = if mi_r > self.tile_row0_mi {
10414 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10415 } else {
10416 DC_PRED
10417 };
10418 let left = if mi_c > self.tile_col0_mi {
10419 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10420 } else {
10421 DC_PRED
10422 };
10423 (above, left)
10424 }
10425
10426 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10427 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10428 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10429 /// per superblock row and never per tile, so the first block column of
10430 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10431 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10432 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10433 /// `up_available`/`left_available` and uses DC_PRED otherwise
10434 /// ([`Self::modes_above_left_mi`]).
10435 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10436 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10437 let (above, left) =
10438 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10439 if above != self.above_mode[c] || left != self.left_mode[r] {
10440 hit!(MODE_MI_OVERRIDE_HITS);
10441 }
10442 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10443 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10444 {
10445 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10446 }
10447 // A neighbour the coarse band offered where the tile edge makes it
10448 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10449 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10450 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10451 {
10452 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10453 }
10454 (above, left)
10455 }
10456
10457 fn record_rect(
10458 &mut self,
10459 at: (usize, usize),
10460 w: usize,
10461 h: usize,
10462 mode: usize,
10463 uv_mode: usize,
10464 grids: &[&[i32]; 3],
10465 ) {
10466 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10467 }
10468
10469 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10470 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10471 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10472 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10473 /// the [`SUB`]-unit path does).
10474 fn record_rect_mi(
10475 &mut self,
10476 at_mi: (usize, usize),
10477 w: usize,
10478 h: usize,
10479 mode: usize,
10480 uv_mode: usize,
10481 grids: &[&[i32]; 3],
10482 ) {
10483 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10484 self.record_mi_rect(at_mi, w, h, grids);
10485 }
10486
10487 /// [`Self::record_rect_mi`]'s mode and transform-size half, without the
10488 /// coefficient-context stamp.
10489 fn record_rect_mi_modes(
10490 &mut self,
10491 at_mi: (usize, usize),
10492 w: usize,
10493 h: usize,
10494 mode: usize,
10495 uv_mode: usize,
10496 ) {
10497 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
10498 // lane-inter4 r2: a strip whose own footprint runs past the frame's
10499 // last 16-px column/row stamps only the cells that exist (libaom's
10500 // arrays are padded past the frame and those cells are never read).
10501 for cell in 0..w / SUB {
10502 if c + cell >= self.above_mode.len() {
10503 break;
10504 }
10505 self.above_mode[c + cell] = mode;
10506 self.above_uv_mode[c + cell] = uv_mode;
10507 self.above_side[c + cell] = w;
10508 }
10509 for cell in 0..h / SUB {
10510 if r + cell >= self.left_mode.len() {
10511 break;
10512 }
10513 self.left_mode[r + cell] = mode;
10514 self.left_uv_mode[r + cell] = uv_mode;
10515 self.left_side[r + cell] = h;
10516 }
10517 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
10518 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
10519 }
10520
10521 /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv
10522 /// plane block is SEVERAL transform units, each of which stamped its own
10523 /// span through [`Self::record_mi_chroma`]. Writing one whole-block state
10524 /// over them is the `override-slot-on-one-arm` class: libaom keeps the
10525 /// per-unit above/left contexts distinct, and the next block's first
10526 /// unit reads them. The luma plane has one unit here, so it is stamped
10527 /// exactly as the whole-block record stamps it.
10528 fn record_rect_mi_luma_only(
10529 &mut self,
10530 at_mi: (usize, usize),
10531 w: usize,
10532 h: usize,
10533 mode: usize,
10534 uv_mode: usize,
10535 luma_grid: &[i32],
10536 ) {
10537 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10538 fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8);
10539 fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8);
10540 self.record_mi_luma_rect(at_mi, w, h, luma_grid);
10541 }
10542
10543 /// The coefficient-context half of [`Self::record`], taking the block's
10544 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
10545 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
10546 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
10547 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
10548 self.record_mi_rect(at_mi, side, side, grids);
10549 }
10550
10551 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
10552 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
10553 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
10554 let (mi_r, mi_c) = at_mi;
10555 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
10556 let (w_mi, h_mi) = (w / MI, h / MI);
10557 if crate::envflags::env_flag!("EC_ECPUB") {
10558 eprintln!(
10559 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
10560 states[0].level
10561 );
10562 }
10563 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10564 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10565 // A chroma 4x4 unit straddling the true luma edge is still whole in
10566 // chroma's own halved grid, so libaom rounds the luma bound up to the
10567 // plane's own 4x4 unit before clamping a subsampled plane
10568 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
10569 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10570 let bound_h = [
10571 self.mi_rows,
10572 round_up_even(self.mi_rows),
10573 round_up_even(self.mi_rows),
10574 ];
10575 let bound_w = [
10576 self.mi_cols,
10577 round_up_even(self.mi_cols),
10578 round_up_even(self.mi_cols),
10579 ];
10580 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
10581 // past the padded side arrays (mi_rows 198, block rows 192..208);
10582 // libaom's own arrays are superblock-sized, so those cells simply
10583 // have no reader -- [`fill_span`] drops them, as the `break` did.
10584 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
10585 // predicate is three contiguous runs: all planes, chroma only, none
10586 // (lane-mi).
10587 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
10588 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
10589 let uv_only = [Neighbour::default(), states[1], states[2]];
10590 fill_span(&mut self.left, mi_r, luma_h, states);
10591 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
10592 fill_span(
10593 &mut self.left,
10594 mi_r + chroma_h,
10595 h_mi - chroma_h,
10596 [Neighbour::default(); 3],
10597 );
10598 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
10599 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
10600 let uv_only_w = [Neighbour::default(), states[1], states[2]];
10601 fill_span(&mut self.above, mi_c, luma_w, states);
10602 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
10603 fill_span(
10604 &mut self.above,
10605 mi_c + chroma_w,
10606 w_mi - chroma_w,
10607 [Neighbour::default(); 3],
10608 );
10609 }
10610
10611 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
10612 /// inside a coded block whose luma transform is smaller than its own
10613 /// side (`TxMode::Select`): the real per-transform-unit coefficient
10614 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
10615 /// coarse per-block `tx_grid`/`fill_lf_grid` state
10616 /// [`Self::record_split_luma`] still writes once for the whole block.
10617 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
10618 /// the caller's own [`Self::record_split_luma`] call sets those once,
10619 /// at the block's own true side, not this TU's.
10620 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
10621 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
10622 }
10623
10624 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
10625 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
10626 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
10627 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
10628 /// coefficient-context arrays are indexed by luma mi, the convention
10629 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
10630 /// clamp included.
10631 fn record_mi_chroma(
10632 &mut self,
10633 (mi_r, mi_c): (usize, usize),
10634 w_px: usize,
10635 h_px: usize,
10636 plane: usize,
10637 grid: &[i32],
10638 ) {
10639 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10640 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10641 let state = neighbour_state(grid);
10642 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
10643 eprintln!(
10644 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
10645 state.level,
10646 state.dc.map_or(-1, |s| i32::from(s))
10647 );
10648 }
10649 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
10650 self.left[mi_r + cell][plane] = state;
10651 }
10652 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
10653 self.above[mi_c + cell][plane] = state;
10654 }
10655 }
10656
10657 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
10658 /// r1): the above context spans the unit's width, the left context its
10659 /// height, which for a square unit is the same loop it always was.
10660 fn record_mi_luma_rect(
10661 &mut self,
10662 (mi_r, mi_c): (usize, usize),
10663 w_px: usize,
10664 h_px: usize,
10665 grid: &[i32],
10666 ) {
10667 let state = neighbour_state(grid);
10668 if crate::envflags::env_flag!("EC_ECPUB") {
10669 eprintln!(
10670 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
10671 state.level
10672 );
10673 }
10674 for cell in 0..h_px / MI {
10675 if mi_r + cell < self.mi_rows {
10676 self.left[mi_r + cell][0] = state;
10677 }
10678 }
10679 for cell in 0..w_px / MI {
10680 if mi_c + cell < self.mi_cols {
10681 self.above[mi_c + cell][0] = state;
10682 }
10683 }
10684 }
10685
10686 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
10687 /// block whose luma was decoded as several transform units through
10688 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
10689 /// whole-block luma write -- everything [`Self::record`] does except
10690 /// plane 0, which is already correct per-TU by the time this runs.
10691 fn record_split_luma(
10692 &mut self,
10693 at: (usize, usize),
10694 side: usize,
10695 mode: usize,
10696 uv_mode: usize,
10697 chroma_grids: [&[i32]; 2],
10698 ) {
10699 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
10700 }
10701
10702 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
10703 /// extents in pixels (lane-rectsplit r1), the same relationship
10704 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
10705 /// luma transform split into several square units needs exactly this
10706 /// bookkeeping, at its own true rectangular extents.
10707 fn record_split_luma_rect(
10708 &mut self,
10709 at: (usize, usize),
10710 w: usize,
10711 h: usize,
10712 mode: usize,
10713 uv_mode: usize,
10714 chroma_grids: [&[i32]; 2],
10715 ) {
10716 let (r, c) = at;
10717 self.record_split_luma_rect_mi(
10718 (r * (SUB / MI), c * (SUB / MI)),
10719 w,
10720 h,
10721 mode,
10722 uv_mode,
10723 chroma_grids,
10724 );
10725 }
10726
10727 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
10728 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
10729 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
10730 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
10731 /// convention [`decode_block_rect4`] already established for 1:4 strips.
10732 fn record_split_luma_rect_mi(
10733 &mut self,
10734 at_mi: (usize, usize),
10735 w: usize,
10736 h: usize,
10737 mode: usize,
10738 uv_mode: usize,
10739 chroma_grids: [&[i32]; 2],
10740 ) {
10741 self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10742 let (mi_r, _) = at_mi;
10743 let (w_mi, h_mi) = (w / MI, h / MI);
10744 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10745 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10746 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
10747 let plane = plane_idx + 1;
10748 let state = neighbour_state(grid);
10749 for cell in 0..h_mi {
10750 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
10751 self.left[mi_r + cell][plane] = state;
10752 }
10753 }
10754 for cell in 0..w_mi {
10755 if cell < w_mi.min(bound_w.saturating_sub(at_mi.1)) {
10756 self.above[at_mi.1 + cell][plane] = state;
10757 }
10758 }
10759 }
10760 }
10761
10762 /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half,
10763 /// without the per-plane coefficient stamp -- see
10764 /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block
10765 /// must not take the whole-block stamp.
10766 fn record_split_luma_rect_mi_modes(
10767 &mut self,
10768 at_mi: (usize, usize),
10769 w: usize,
10770 h: usize,
10771 mode: usize,
10772 uv_mode: usize,
10773 ) {
10774 let (mi_r, mi_c) = at_mi;
10775 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10776 for cell in 0..w.div_ceil(SUB) {
10777 if c + cell >= self.above_mode.len() {
10778 break;
10779 }
10780 self.above_mode[c + cell] = mode;
10781 self.above_uv_mode[c + cell] = uv_mode;
10782 self.above_side[c + cell] = w;
10783 }
10784 for cell in 0..h.div_ceil(SUB) {
10785 if r + cell >= self.left_mode.len() {
10786 break;
10787 }
10788 self.left_mode[r + cell] = mode;
10789 self.left_uv_mode[r + cell] = uv_mode;
10790 self.left_side[r + cell] = h;
10791 }
10792
10793 let (w_mi, h_mi) = (w / MI, h / MI);
10794 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
10795 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
10796 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10797 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10798 }
10799}
10800
10801/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
10802/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
10803/// exactly — including its skip context, which the real key-frame writer
10804/// always writes at a fixed context of zero (it never tracks a neighbour-based
10805/// one for intra blocks; that is the inter-frame writer's rule instead).
10806/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
10807/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
10808/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
10809/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
10810/// plain DC chroma.
10811/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
10812/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
10813/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
10814/// instead (the defect commit 1a89ed9 fixed at the square sites).
10815pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
10816 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
10817 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
10818}
10819
10820/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
10821/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
10822/// bound (spec `filter_intra_mode_info` never reads a symbol there).
10823pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
10824 match side {
10825 4 => Some(0),
10826 8 => Some(1),
10827 16 => Some(2),
10828 32 => Some(3),
10829 _ => None,
10830 }
10831}
10832
10833/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
10834/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
10835/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
10836/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
10837fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
10838 match (bw, bh) {
10839 (32, 16) => Some(4),
10840 (16, 32) => Some(5),
10841 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
10842 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
10843 // here dropped that symbol on every DC_PRED strip of that size and
10844 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
10845 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
10846 (16, 8) => Some(6),
10847 (8, 16) => Some(7),
10848 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
10849 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
10850 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
10851 (4, 8) => Some(8),
10852 (8, 4) => Some(9),
10853 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
10854 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
10855 // `use_filter_intra` symbol on those strips although aomenc writes
10856 // one for every DC_PRED block of that shape with
10857 // `--enable-filter-intra=1` (its default), silently desyncing the
10858 // tile (class symbol-consumption-gap).
10859 (32, 8) => Some(10),
10860 (8, 32) => Some(11),
10861 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
10862 // strips), rows 17/16 of `default_filter_intra_cdfs`.
10863 (16, 4) => Some(12),
10864 (4, 16) => Some(13),
10865 _ if bw == bh => filter_intra_size_class(bw),
10866 _ => None,
10867 }
10868}
10869
10870/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
10871/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
10872/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
10873/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
10874/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
10875pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
10876 palette_bsize_ctx_wh(side, side)
10877}
10878
10879/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
10880/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
10881/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
10882/// for ANY bsize, not just the square ones a hand-picked table happened to
10883/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
10884/// row breaks the moment its indexing field moves off the diagonal, and a
10885/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
10886/// block dimension is a power of two, so `bw*bh` always is too and
10887/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
10888/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
10889fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
10890 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
10891 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
10892 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
10893 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
10894 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
10895 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
10896 if bw > 64 || bh > 64 || bw * bh < 64 {
10897 return None;
10898 }
10899 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
10900}
10901
10902/// A just-decoded palette-Y block's own size, base colours (only the first
10903/// `size` entries are real), and per-pixel colour-index map (`side*side`,
10904/// row-major, each entry `< size`).
10905struct PaletteY {
10906 size: usize,
10907 colors: [u16; 8],
10908 map: Vec<u8>,
10909}
10910
10911/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
10912/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
10913/// shared between U and V, both co-located after 4:2:0 subsampling) plus
10914/// each plane's own base colours.
10915struct PaletteUv {
10916 size: usize,
10917 u_colors: [u16; 8],
10918 v_colors: [u16; 8],
10919 map: Vec<u8>,
10920}
10921
10922/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
10923/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
10924/// `get_unsigned_bits`, which is the same formula): smallest `n` with
10925/// `2^n >= x`, `0` for `x <= 1`.
10926pub(crate) fn ceil_log2(x: u32) -> u32 {
10927 if x < 2 {
10928 0
10929 } else {
10930 32 - (x - 1).leading_zeros()
10931 }
10932}
10933
10934/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
10935/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
10936fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
10937 let l = ceil_log2(n as u32);
10938 let m = (1usize << l) - n;
10939 let v = dec.literal(l - 1) as usize;
10940 if v < m {
10941 v
10942 } else {
10943 (v << 1) - m + dec.literal(1) as usize
10944 }
10945}
10946
10947/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
10948/// colours (already-known, from the above/left neighbours) with the
10949/// ascending `transmitted` ones (delta-coded off the wire) back into one
10950/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
10951/// value picks the cached copy first, matching the C `<=`.
10952fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
10953 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
10954 let (mut ci, mut ti) = (0, 0);
10955 while ci < cached.len() && ti < transmitted.len() {
10956 if cached[ci] <= transmitted[ti] {
10957 out.push(cached[ci]);
10958 ci += 1;
10959 } else {
10960 out.push(transmitted[ti]);
10961 ti += 1;
10962 }
10963 }
10964 out.extend_from_slice(&cached[ci..]);
10965 out.extend_from_slice(&transmitted[ti..]);
10966 out
10967}
10968
10969/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
10970/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
10971/// each delta's width, the `range` bound and the clamp) is sized by
10972/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
10973/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
10974/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
10975/// the msac range, so a cross-decoder range ladder stays bit-identical
10976/// through the whole miscount -- only the decoded VALUE differs (class
10977/// `compare-range-not-tell`'s blind spot). (this
10978/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
10979/// (one flag bit each, in cache order), then delta-codes the remainder
10980/// (first value raw, each following delta `>= 1` off a shrinking bit width),
10981/// and merges the two ascending lists back together.
10982fn read_palette_colors_y(
10983 dec: &mut SymbolDecoder,
10984 n: usize,
10985 cache: &[u16],
10986 fctx: &crate::decode::FrameCtx,
10987) -> [u16; 8] {
10988 let mut cached = Vec::with_capacity(n);
10989 for &c in cache {
10990 if cached.len() >= n {
10991 break;
10992 }
10993 if dec.literal(1) == 1 {
10994 cached.push(c);
10995 }
10996 }
10997 let bd = u32::from(bit_depth(fctx));
10998 let max_val = (1i32 << bd) - 1;
10999 let mut colors = [0u16; 8];
11000 let n_cached = cached.len();
11001 if n_cached < n {
11002 let mut transmitted = Vec::with_capacity(n - n_cached);
11003 let first = dec.literal(bd) as u16;
11004 transmitted.push(first);
11005 if n_cached + 1 < n {
11006 let min_bits = bd - 3;
11007 let mut bits = min_bits + dec.literal(2);
11008 let mut range = (1i32 << bd) - i32::from(first) - 1;
11009 for _ in (n_cached + 1)..n {
11010 let delta = dec.literal(bits) as i32 + 1;
11011 let prev = *transmitted.last().unwrap();
11012 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
11013 range -= i32::from(val) - i32::from(prev);
11014 bits = bits.min(ceil_log2(range.max(0) as u32));
11015 transmitted.push(val);
11016 }
11017 }
11018 let merged = merge_colors(&transmitted, &cached);
11019 colors[..n].copy_from_slice(&merged);
11020 } else {
11021 colors[..n].copy_from_slice(&cached[..n]);
11022 }
11023 colors
11024}
11025
11026/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
11027/// `bit_depth` (see [`read_palette_colors_y`]): U reads
11028/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
11029/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
11030/// unbiased by `+1` -- both differences from Y's own reader, matching the C
11031/// side by side). V never uses a cache: a leading bit picks either `n` raw
11032/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
11033/// rather than clamp.
11034fn read_palette_colors_uv(
11035 dec: &mut SymbolDecoder,
11036 n: usize,
11037 cache: &[u16],
11038 fctx: &crate::decode::FrameCtx,
11039) -> ([u16; 8], [u16; 8]) {
11040 let mut cached = Vec::with_capacity(n);
11041 for &c in cache {
11042 if cached.len() >= n {
11043 break;
11044 }
11045 if dec.literal(1) == 1 {
11046 cached.push(c);
11047 }
11048 }
11049 let bd = u32::from(bit_depth(fctx));
11050 let max_val = 1i32 << bd;
11051 let mut u_colors = [0u16; 8];
11052 let n_cached = cached.len();
11053 if n_cached < n {
11054 let mut transmitted = Vec::with_capacity(n - n_cached);
11055 let first = dec.literal(bd) as u16;
11056 transmitted.push(first);
11057 if n_cached + 1 < n {
11058 let min_bits = bd - 3;
11059 let mut bits = min_bits + dec.literal(2);
11060 let mut range = max_val - i32::from(first);
11061 for _ in (n_cached + 1)..n {
11062 let delta = dec.literal(bits) as i32;
11063 let prev = *transmitted.last().unwrap();
11064 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
11065 range -= i32::from(val) - i32::from(prev);
11066 bits = bits.min(ceil_log2(range.max(0) as u32));
11067 transmitted.push(val);
11068 }
11069 }
11070 let merged = merge_colors(&transmitted, &cached);
11071 u_colors[..n].copy_from_slice(&merged);
11072 } else {
11073 u_colors[..n].copy_from_slice(&cached[..n]);
11074 }
11075 let mut v_colors = [0u16; 8];
11076 if dec.literal(1) == 1 {
11077 let min_bits_v = bd - 4;
11078 let bits = min_bits_v + dec.literal(2);
11079 v_colors[0] = dec.literal(bd) as u16;
11080 for i in 1..n {
11081 let mut delta = dec.literal(bits) as i32;
11082 if delta != 0 && dec.literal(1) == 1 {
11083 delta = -delta;
11084 }
11085 let mut val = i32::from(v_colors[i - 1]) + delta;
11086 if val < 0 {
11087 val += max_val;
11088 }
11089 if val >= max_val {
11090 val -= max_val;
11091 }
11092 v_colors[i] = val as u16;
11093 }
11094 } else {
11095 for i in 0..n {
11096 v_colors[i] = dec.literal(bd) as u16;
11097 }
11098 }
11099 (u_colors, v_colors)
11100}
11101
11102/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
11103/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
11104/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
11105const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
11106
11107/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
11108/// map's own per-pixel context and colour-order permutation, from the
11109/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
11110/// selection sort). `map`'s stride is `side` (this decoder never crops a
11111/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
11112/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
11113/// actual colour index to store.
11114pub(crate) fn palette_color_index_context(
11115 map: &[u8],
11116 side: usize,
11117 row: usize,
11118 col: usize,
11119 n: usize,
11120) -> (usize, [u8; 8]) {
11121 let left = if col >= 1 {
11122 Some(map[row * side + col - 1])
11123 } else {
11124 None
11125 };
11126 let up_left = if col >= 1 && row >= 1 {
11127 Some(map[(row - 1) * side + col - 1])
11128 } else {
11129 None
11130 };
11131 let up = if row >= 1 {
11132 Some(map[(row - 1) * side + col])
11133 } else {
11134 None
11135 };
11136 let mut scores = [0i32; 8];
11137 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
11138 if let Some(v) = neighbour {
11139 scores[v as usize] += weight;
11140 }
11141 }
11142 let mut color_order = [0u8; 8];
11143 for i in 0..8 {
11144 color_order[i] = i as u8;
11145 }
11146 for i in 0..3 {
11147 let mut max = scores[i];
11148 let mut max_idx = i;
11149 for j in (i + 1)..n {
11150 if scores[j] > max {
11151 max = scores[j];
11152 max_idx = j;
11153 }
11154 }
11155 if max_idx != i {
11156 let max_score = scores[max_idx];
11157 let max_color = color_order[max_idx];
11158 for k in (i + 1..=max_idx).rev() {
11159 scores[k] = scores[k - 1];
11160 color_order[k] = color_order[k - 1];
11161 }
11162 scores[i] = max_score;
11163 color_order[i] = max_color;
11164 }
11165 }
11166 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
11167 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
11168 (ctx as usize, color_order)
11169}
11170
11171/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
11172/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
11173/// cut by the frame's bottom or right mi edge codes its colour-index map only
11174/// over this part and replicates it outward -- reading the full `bw x bh` grid
11175/// consumed symbols libaom never wrote and desynced the rest of the tile
11176/// (lane-svtinter; class map-read-past-frame-edge).
11177fn palette_onscreen(
11178 mi_r: usize,
11179 mi_c: usize,
11180 bw: usize,
11181 bh: usize,
11182 fctx: &crate::decode::FrameCtx,
11183) -> (usize, usize) {
11184 // lane-palw: the ENCODER's own in-process reconstruct runs on a
11185 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
11186 // frame encoders publish the header's mi dims onto it themselves
11187 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
11188 // clamp and `tile::write_color_index_map`'s now agree there too.
11189 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
11190 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
11191}
11192
11193/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
11194/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
11195/// compute the same on-screen extent or the decoder reads a different number
11196/// of symbols than the encoder wrote.
11197pub(crate) fn palette_onscreen_dims(
11198 mi_r: usize,
11199 mi_c: usize,
11200 bw: usize,
11201 bh: usize,
11202 (mi_rows, mi_cols): (usize, usize),
11203) -> (usize, usize) {
11204 (
11205 bw.min(mi_cols.saturating_sub(mi_c) * MI),
11206 bh.min(mi_rows.saturating_sub(mi_r) * MI),
11207 )
11208}
11209
11210/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
11211/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
11212/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
11213/// together or a cut 8-wide block reads its chroma map at the wrong width.
11214/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
11215/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
11216/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
11217pub(crate) fn palette_onscreen_uv(
11218 luma: (usize, usize),
11219 on: (usize, usize),
11220 chroma: (usize, usize),
11221 ss: (usize, usize),
11222) -> (usize, usize) {
11223 (
11224 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
11225 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
11226 )
11227}
11228
11229/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
11230/// map's wavefront decode over a `side x side` grid, read over the on-screen
11231/// `on_side x on_side` corner (see [`palette_onscreen`]).
11232fn decode_color_index_map(
11233 dec: &mut SymbolDecoder,
11234 cdfs: &mut Cdfs,
11235 n: usize,
11236 side: usize,
11237 on: (usize, usize),
11238 uv: bool,
11239) -> Vec<u8> {
11240 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
11241}
11242
11243/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
11244/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
11245/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
11246/// independently rather than one shared `side` -- the square call above is
11247/// just `bw == bh`.
11248fn decode_color_index_map_wh(
11249 dec: &mut SymbolDecoder,
11250 cdfs: &mut Cdfs,
11251 n: usize,
11252 bw: usize,
11253 bh: usize,
11254 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
11255 on: (usize, usize),
11256 uv: bool,
11257) -> Vec<u8> {
11258 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
11259 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11260 if on_bw < bw || on_bh < bh {
11261 hit!(PALETTE_ONSCREEN_CUT_HITS);
11262 }
11263 let mut map = vec![0u8; bw * bh];
11264 if trace {
11265 let (rng, _) = dec.debug_state();
11266 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
11267 }
11268 map[0] = read_uniform(dec, n) as u8;
11269 if trace {
11270 let (rng, _) = dec.debug_state();
11271 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11272 }
11273 for i in 1..(on_bw + on_bh - 1) {
11274 let j_hi = i.min(on_bw - 1);
11275 let j_lo = i.saturating_sub(on_bh - 1);
11276 for j in (j_lo..=j_hi).rev() {
11277 let row = i - j;
11278 let col = j;
11279 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11280 if trace {
11281 let (rng, _) = dec.debug_state();
11282 let row_cdf = if uv {
11283 &cdfs.palette_uv_color_index[n - 2][ctx]
11284 } else {
11285 &cdfs.palette_y_color_index[n - 2][ctx]
11286 };
11287 eprintln!(
11288 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11289 row_cdf[0], row_cdf[n]
11290 );
11291 }
11292 let symbol = if uv {
11293 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11294 } else {
11295 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11296 };
11297 map[row * bw + col] = color_order[symbol];
11298 if trace {
11299 let (rng, _) = dec.debug_state();
11300 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11301 }
11302 }
11303 }
11304 palette_replicate(&mut map, bw, bh, on);
11305 map
11306}
11307
11308/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11309/// last on-screen column then the last on-screen row are replicated over the
11310/// off-screen remainder, so the prediction still covers the whole block. The
11311/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11312/// so the pixels it prices and reconstructs are the ones the on-screen
11313/// symbols it writes really decode to.
11314pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11315 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11316 for row in 0..on_bh {
11317 let last = map[row * bw + on_bw - 1];
11318 map[row * bw + on_bw..row * bw + bw].fill(last);
11319 }
11320 for row in on_bh..bh {
11321 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11322 }
11323}
11324
11325/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11326/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11327/// size class comes from [`filter_intra_size_class_rect`] instead of the
11328/// square-only [`filter_intra_size_class`], and the palette read (when
11329/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11330/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11331/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11332/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11333#[allow(clippy::too_many_arguments)]
11334fn read_intra_mode_rect(
11335 dec: &mut SymbolDecoder,
11336 cdfs: &mut Cdfs,
11337 above_mode: usize,
11338 left_mode: usize,
11339 cfl: bool,
11340 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11341 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11342 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11343 // chroma is coded once, on the closing strip). Every other caller is a
11344 // block big enough to own its chroma and passes `true`.
11345 has_chroma: bool,
11346 bw: usize,
11347 bh: usize,
11348 enable_filter_intra: bool,
11349 skip_ctx: usize,
11350 allow_screen_content_tools: bool,
11351 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11352 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11353 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11354 palette: Option<(usize, &[u16])>,
11355 palette_uv_cache: &[u16],
11356 mi_r: usize,
11357 mi_c: usize,
11358 fctx: &crate::decode::FrameCtx,
11359) -> Result<(
11360 bool,
11361 usize,
11362 i32,
11363 usize,
11364 i32,
11365 Option<(i32, i32)>,
11366 Option<usize>,
11367 Option<PaletteY>,
11368 Option<PaletteUv>,
11369 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11370 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11371 // straight out of `read_intra_frame_mode_info` then, so every later field
11372 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11373 // no filter intra). A caller that can reconstruct intrabc at its shape
11374 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11375 // name with the same string it always did.
11376 Option<(i32, i32)>,
11377)> {
11378 // lane-av1mono: libaom guards every chroma symbol read with
11379 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11380 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11381 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11382 // into the same `has_chroma` this reader already gates on.
11383 let has_chroma = has_chroma && !mono(fctx);
11384 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11385 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11386 if ec_istep {
11387 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11388 // (decodemv.c:818), printed at the same point: before the first
11389 // mode-info symbol of the block, so a cross-decoder range ladder can
11390 // be keyed on the BLOCK, not just on the symbol sequence.
11391 eprintln!(
11392 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11393 enable_filter_intra as i32,
11394 filter_intra_size_class_rect(bw, bh),
11395 dec.debug_state().0
11396 );
11397 }
11398 macro_rules! istep {
11399 ($name:literal, $val:expr) => {
11400 if ec_istep {
11401 let (rng, _) = dec.debug_state();
11402 eprintln!(
11403 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11404 $name, $val
11405 );
11406 }
11407 };
11408 }
11409 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11410 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11411 // the one point every rect caller routes through, so no call site can
11412 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11413 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11414 let cfl = if cfl && bw.max(bh) > 32 {
11415 hit!(NOCFL_UV_MODE_HITS);
11416 false
11417 } else {
11418 cfl
11419 };
11420 // lane-intra14 r1: on the INTER block path everything up to and including
11421 // `is_inter` was already read by [`decode_inter_block`], so this reader
11422 // starts at the mode syntax with the `skip` that caller read.
11423 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11424 let skip = if let Some((_, skip)) = inter {
11425 skip
11426 } else {
11427 // Same `intra_segment_id` placement as the square reader above.
11428 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11429 if seg_id_pre_skip(fctx) {
11430 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11431 }
11432 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11433 istep!("skip", skip as i32);
11434 if !seg_id_pre_skip(fctx) {
11435 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11436 }
11437 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11438 istep!("cdef", 0);
11439 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11440 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11441 // `false`.
11442 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11443 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11444 istep!("dq", 0);
11445 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11446 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11447 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11448 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11449 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11450 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11451 // decoder at the FIRST symbol of the first rect block of every
11452 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11453 // block at this shape is out of scope, so the flag is consumed and
11454 // refused by name when it fires.
11455 if allow_intrabc_frame(fctx) {
11456 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11457 hit!(RECT_INTRABC_READS);
11458 istep!("intrabc", use_intrabc as i32);
11459 if use_intrabc {
11460 hit!(INTRABC_HITS);
11461 // libaom `read_intrabc_info`: the DV read, then an immediate
11462 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
11463 // no angle deltas, no palette, no filter intra. The caller owns
11464 // the reconstruction at its own shape.
11465 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
11466 return Ok((
11467 skip,
11468 DC_PRED,
11469 0,
11470 DC_PRED,
11471 0,
11472 None,
11473 None,
11474 None,
11475 None,
11476 Some(dv),
11477 ));
11478 }
11479 }
11480 skip
11481 };
11482 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
11483 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
11484 // off `kf_y_mode_cdf[above][left]`).
11485 let mode = if let Some((size_group, _)) = inter {
11486 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
11487 dec.symbol(&mut cdfs.y_mode[size_group])
11488 } else {
11489 let above_ctx = INTRA_MODE_CTX[above_mode];
11490 let left_ctx = INTRA_MODE_CTX[left_mode];
11491 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
11492 };
11493 istep!("mode", mode as i32);
11494 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11495 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11496 } else {
11497 0
11498 };
11499 istep!("angle_y", angle_delta_y);
11500 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
11501 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
11502 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
11503 // here, from the block's own size, is the single point every caller routes
11504 // through -- a caller passing `true` for a >32 strip used to pick the
11505 // 14-symbol CFL CDF, same value but a different range (class
11506 // wrong-alphabet-same-value).
11507 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
11508 let uv_mode = if !has_chroma {
11509 DC_PRED
11510 } else if cfl {
11511 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11512 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11513 } else {
11514 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11515 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11516 };
11517 istep!("uv_mode", uv_mode as i32);
11518 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
11519 Some(read_cfl_alphas(dec, cdfs))
11520 } else {
11521 None
11522 };
11523 if has_chroma && (9..=12).contains(&uv_mode) {
11524 hit!(SMOOTH_UV_HITS);
11525 }
11526 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
11527 hit!(DIRECTIONAL_UV_HITS);
11528 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11529 } else {
11530 0
11531 };
11532 istep!("angle_uv", angle_delta_uv);
11533 if angle_delta_uv != 0 {
11534 hit!(UV_ANGLE_DELTA_HITS);
11535 }
11536 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
11537 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
11538 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
11539 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
11540 // colours only here, the colour-index maps deferred past `filter_intra`
11541 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
11542 // runs from the caller, after the whole mode-info read).
11543 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11544 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11545 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
11546 // r6: this is the exact site the removed blanket refusal used to
11547 // guard -- reached for EVERY rect strip in a screen-content frame,
11548 // independent of whether the block ends up using a palette.
11549 hit!(RECT_SCREEN_CONTENT_HITS);
11550 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11551 let use_palette_y =
11552 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11553 if use_palette_y {
11554 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11555 let colors = read_palette_colors_y(dec, n, cache, fctx);
11556 palette_y_pending = Some((n, colors));
11557 }
11558 let palette_uv_mode_ctx = usize::from(use_palette_y);
11559 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
11560 if has_chroma
11561 && uv_mode == DC_PRED
11562 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
11563 {
11564 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11565 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
11566 palette_uv_pending = Some((n, u_colors, v_colors));
11567 }
11568 }
11569 let mut filter_intra = None;
11570 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11571 let (rng, _) = dec.debug_state();
11572 eprintln!(
11573 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
11574 class={:?} rng={rng}",
11575 enable_filter_intra as i32,
11576 filter_intra_size_class_rect(bw, bh)
11577 );
11578 }
11579 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
11580 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
11581 if mode == DC_PRED
11582 && enable_filter_intra
11583 && palette_y_pending.is_none()
11584 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11585 {
11586 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11587 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11588 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
11589 }
11590 istep!("use_filter_intra", use_filter_intra as i32);
11591 if use_filter_intra {
11592 hit!(FILTER_INTRA_HITS);
11593 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11594 istep!("filter_intra_mode", fi_mode as i32);
11595 filter_intra = Some(fi_mode);
11596 }
11597 }
11598 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
11599 // same order as [`read_intra_mode`]'s own square path.
11600 let palette_y = palette_y_pending.map(|(n, colors)| {
11601 let map = decode_color_index_map_wh(
11602 dec,
11603 cdfs,
11604 n,
11605 bw,
11606 bh,
11607 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11608 false,
11609 );
11610 hit!(PALETTE_HITS);
11611 hit!(PALETTE_RECT_HITS);
11612 PaletteY {
11613 size: n,
11614 colors,
11615 map,
11616 }
11617 });
11618 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11619 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
11620 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
11621 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
11622 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
11623 // chroma palette and desynced the tile from there.
11624 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11625 let on = palette_onscreen_uv(
11626 (bw, bh),
11627 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11628 (cw, ch),
11629 (ss_x(fctx), ss_y(fctx)),
11630 );
11631 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11632 hit!(PALETTE_UV_HITS);
11633 PaletteUv {
11634 size: n,
11635 u_colors,
11636 v_colors,
11637 map,
11638 }
11639 });
11640 Ok((
11641 skip,
11642 mode,
11643 angle_delta_y,
11644 uv_mode,
11645 angle_delta_uv,
11646 alpha,
11647 filter_intra,
11648 palette_y,
11649 palette_uv,
11650 None,
11651 ))
11652}
11653
11654/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
11655/// at the strip's REAL mi position. `av1_get_palette_cache` reads
11656/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
11657/// block, so each strip owns its own rows and columns and no aliasing rule
11658/// is needed (lane-kf900 r6).
11659#[allow(clippy::too_many_arguments)]
11660fn record_strip_palette(
11661 n: &mut Neighbours,
11662 mi: (usize, usize),
11663 bw: usize,
11664 bh: usize,
11665 y_size: usize,
11666 y_colors: [u16; 8],
11667 uv_size: usize,
11668 uv_colors: [u16; 8],
11669) {
11670 let (r, c) = mi;
11671 // lane-t900 r23 rung: every publication of a block's palette state into
11672 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
11673 // path left a stale `left_palette_size` behind when
11674 // `av1_get_palette_mode_ctx` disagrees with libaom's.
11675 if crate::envflags::env_flag!("EC_PALPUB") {
11676 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
11677 }
11678 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
11679 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
11680 // existed because the 16px [`SUB`] cell held one slot for all the strips
11681 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
11682 // real neighbour leaf 1 reads.
11683 {
11684 for cell in 0..(bw / MI).max(1) {
11685 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
11686 *e = y_size as u8;
11687 n.above_palette_uv_size[c + cell] = uv_size as u8;
11688 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
11689 // colours of a size-0 neighbour are never read.
11690 if y_size > 0 {
11691 n.above_palette_colors[c + cell] = y_colors;
11692 }
11693 if uv_size > 0 {
11694 n.above_palette_uv_colors[c + cell] = uv_colors;
11695 }
11696 }
11697 }
11698 }
11699 {
11700 for cell in 0..(bh / MI).max(1) {
11701 if n.left_palette_size.get(r + cell).is_none() {
11702 break;
11703 }
11704 n.left_palette_size[r + cell] = y_size as u8;
11705 n.left_palette_uv_size[r + cell] = uv_size as u8;
11706 if y_size > 0 {
11707 n.left_palette_colors[r + cell] = y_colors;
11708 }
11709 if uv_size > 0 {
11710 n.left_palette_uv_colors[r + cell] = uv_colors;
11711 }
11712 }
11713 }
11714}
11715
11716/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
11717fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
11718 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
11719 i32::from(y.data[ly * y.width + lx])
11720 })
11721}
11722
11723/// Everything a rect strip already read out of the stream before its luma
11724/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
11725/// (nine values that would otherwise be nine more parameters).
11726struct RectStripModes {
11727 skip: bool,
11728 mode: usize,
11729 angle_delta_y: i32,
11730 uv_predict_mode: usize,
11731 angle_delta_uv: i32,
11732 alpha: Option<(i32, i32)>,
11733 filter_intra: Option<usize>,
11734 smooth_neighbor: bool,
11735 smooth_neighbor_uv: bool,
11736 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
11737 /// mapped through the colour table), sliced per transform unit below --
11738 /// palette prediction reads no edge pixels, so a unit's slice of the
11739 /// whole-block map IS its prediction. Without this a palette strip whose
11740 /// transform splits predicted DC and came out flat grey while the entropy
11741 /// stream stayed in sync (the coefficients are read either way).
11742 palette_y: Option<Vec<u16>>,
11743 /// As `palette_y`, for the un-split chroma transform (U, V).
11744 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
11745}
11746
11747/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
11748/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
11749/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
11750/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
11751/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
11752/// TX_32X16`) and only the second reaches a square -- the reason
11753/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
11754/// already square) mis-tiled 1:4 strips.
11755fn depth_to_tx_wh(
11756 bw: usize,
11757 bh: usize,
11758 depth: usize,
11759 fctx: &crate::decode::FrameCtx,
11760) -> (usize, usize) {
11761 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
11762 // `read_tx_size`: the lossless early return comes before
11763 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
11764 if lossless(fctx) {
11765 return (4, 4);
11766 }
11767 let (mut w, mut h) = (bw.min(64), bh.min(64));
11768 for _ in 0..depth {
11769 match w.cmp(&h) {
11770 std::cmp::Ordering::Greater => w /= 2,
11771 std::cmp::Ordering::Less => h /= 2,
11772 std::cmp::Ordering::Equal => {
11773 w /= 2;
11774 h /= 2;
11775 }
11776 }
11777 }
11778 (w, h)
11779}
11780
11781/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
11782/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
11783/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
11784/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
11785/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
11786/// 2-px-wide area is not a transform shape. The strip pairs with its
11787/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
11788/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
11789/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
11790/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
11791/// the entropy context on the floored cell. Returns
11792/// `(pair block width, pair block height, write anchor x, entropy mi column)`
11793/// for that pair, or `None` when the strip keeps its own plane block at its
11794/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
11795/// 2 px wide) and every 4:2:2 strip of 8 px or more.
11796fn chroma422_pair_plane(
11797 ss_x: bool,
11798 ss_y: bool,
11799 mi_col: usize,
11800 bw: usize,
11801 bh: usize,
11802) -> Option<(usize, usize, usize, usize)> {
11803 if ss_x && !ss_y && (bw >> 1) == 2 {
11804 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
11805 } else {
11806 None
11807 }
11808}
11809
11810/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
11811/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
11812/// rect path here refused by name until now ("per-unit rect prediction is not
11813/// ported").
11814///
11815/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
11816/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
11817/// strip the very first step already lands on a SQUARE transform
11818/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
11819/// every further step halves a square) -- so each unit is square and reads
11820/// through the ordinary square [`read_plane`]. What is genuinely rectangular
11821/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
11822/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
11823/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
11824/// split by luma's depth.
11825///
11826/// Each unit predicts off whatever the earlier units of this same block
11827/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
11828/// inside `av1_foreach_transformed_block`, raster order), which is exactly
11829/// what predicting the whole strip in one shot got wrong.
11830#[allow(clippy::too_many_arguments)]
11831fn decode_rect_split(
11832 dec: &mut SymbolDecoder,
11833 cdfs: &mut Cdfs,
11834 neighbours: &mut Neighbours,
11835 at_mi: (usize, usize),
11836 bw: usize,
11837 bh: usize,
11838 // The transform unit's own width and height in pixels. Square for every
11839 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
11840 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
11841 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
11842 tx_w: usize,
11843 tx_h: usize,
11844 m: &RectStripModes,
11845 y: &mut PlaneBuf<'static>,
11846 u: &mut PlaneBuf<'static>,
11847 v: &mut PlaneBuf<'static>,
11848 base_q_idx: u8,
11849 reduced_tx_set: bool,
11850 fctx: &crate::decode::FrameCtx,
11851) -> Result<()> {
11852 let (mi_r, mi_c) = at_mi;
11853 let (px, py) = (mi_c * MI, mi_r * MI);
11854 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
11855 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
11856 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
11857 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
11858 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
11859 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
11860 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
11861 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
11862 // measurement). The plane is still coded -- `decode_token_recon_block`
11863 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
11864 // 4x8 rect units, plane-major.
11865 let chroma_422_oob = ss_x(fctx) == 1
11866 && ss_y(fctx) == 0
11867 && matches!(
11868 (bw, bh),
11869 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
11870 );
11871 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
11872 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
11873 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
11874 // plane is then `(4, chroma_h)` written at the FLOORED cell
11875 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
11876 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
11877 // the same walk the (8, 32) class takes). The lossless raster arm keeps
11878 // the strip's own geometry: no caller of this function can present a
11879 // 4-wide strip yet (the enumeration test pins the five callers at
11880 // `8 <= min`), and the skip/tiled arms are the routes a future caller
11881 // needs.
11882 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
11883 let chroma_422_pair_wide = chroma422_pair.is_some();
11884 let (chroma_block_w, chroma_block_h, chroma_x) =
11885 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
11886 // The chroma transform is picked before any symbol is read, so an
11887 // unsupported chroma shape refuses before this strip desyncs the tile.
11888 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
11889 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
11890 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
11891 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
11892 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
11893 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
11894 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
11895 // squares a rect transform down to a CDF set by
11896 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
11897 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
11898 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
11899 // paths already prove for these same shapes.
11900 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
11901 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
11902 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
11903 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
11904 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
11905 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
11906 _ => None,
11907 };
11908 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
11909 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
11910 // below; everything else still needs a single-unit table.
11911 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
11912 // halves only the width, so a rect luma strip codes a SQUARE chroma block
11913 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
11914 // rect strip's chroma is itself rect, so the square rows are unreachable
11915 // there and cannot change their results.
11916 // lane-av1-422blockhalf: the tiled arms below handle every shape this
11917 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
11918 // diagnostic names only the shapes that would actually refuse -- it used
11919 // to fire for every tiled square too (the parent lane's `chroma=8x8`
11920 // rows) and sent the next lane chasing handled shapes.
11921 let chroma_tiled = chroma_422_pair_wide
11922 || chroma_422_oob
11923 || matches!(
11924 (chroma_w, chroma_h),
11925 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
11926 );
11927 if !m.skip {
11928 if let Some(i) = match (chroma_w, chroma_h) {
11929 (32, 8) => Some(0),
11930 (8, 32) => Some(1),
11931 (8, 4) => Some(2),
11932 (4, 8) => Some(3),
11933 _ => None,
11934 } {
11935 hit_do! {
11936 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
11937 let mut hits = c.get();
11938 hits[i] += 1;
11939 c.set(hits);
11940 });
11941 }
11942 }
11943 if !m.skip && chroma.is_none() && !chroma_tiled {
11944 // Diagnostic for the next caller that lands here (class
11945 // refusal-names-a-correlate: the message names the tool, not the
11946 // shape); the refusal below keeps its inventory-pinned wording.
11947 eprintln!(
11948 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
11949 chroma={chroma_w}x{chroma_h}"
11950 );
11951 }
11952 }
11953 // lane-rectsplit r2 (verifier finding): with both callers wired
11954 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
11955 // 64x32/32x64) every shape that reaches here has a table above, so this
11956 // arm is UNREACHABLE today. It stays as the shape guard for the next
11957 // caller -- a new strip size would otherwise hit the `expect` below and
11958 // panic instead of refusing by name -- and so stays in
11959 // `refusal_inventory::REFUSALS`.
11960 if !m.skip && chroma.is_none() && !chroma_tiled {
11961 return Err(unsupported(
11962 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
11963 ));
11964 }
11965 hit!(RECT_SPLIT_TX_HITS);
11966 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
11967 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
11968 }
11969 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
11970 // A square unit reads through the ordinary square [`read_plane`]; a rect
11971 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
11972 // the very tables the unsplit 16x8/32x16 paths use.
11973 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
11974 (w, h) if w == h => None,
11975 (16, 8) | (8, 16) => Some((
11976 if reduced_tx_set {
11977 TxbSet::LumaRect16x8
11978 } else {
11979 TxbSet::LumaRect16x8Set1
11980 },
11981 if tx_w == 16 {
11982 &SCAN_16X8[..]
11983 } else {
11984 &SCAN_8X16[..]
11985 },
11986 )),
11987 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
11988 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
11989 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
11990 // strip, read through the `luma_64corner` arm below instead of a rect
11991 // table -- a 64-length axis codes only its low 32 coefficients
11992 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
11993 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
11994 // depth-0 arm already reads on the key-frame path.
11995 //
11996 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
11997 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
11998 // sub-8x8 intra leaves still refused: with those lifted (r2) the
11999 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
12000 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
12001 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
12002 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
12003 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
12004 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
12005 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
12006 (64, 32) | (32, 64) => None,
12007 _ => {
12008 return Err(unsupported(format!(
12009 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
12010 coefficient tables for that shape here)"
12011 )));
12012 }
12013 };
12014 // The `None` above that is NOT the square arm.
12015 let luma_64corner = tx_w != tx_h;
12016 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
12017 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
12018 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
12019 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
12020 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
12021 // per-unit rect walk stay wired above/below; the round that finds that
12022 // defect deletes this refusal and nothing else.
12023 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
12024 let luma_scan = default_scan(tx_w.min(tx_h));
12025 let zero_tu = vec![0i32; tx_w * tx_h];
12026 // The strip's OWN edge availability, the fallback for a transform unit
12027 // whose top-right/bottom-left pixels fall outside the strip.
12028 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12029 for tu_row in 0..bh / tx_h {
12030 for tu_col in 0..bw / tx_w {
12031 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
12032 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12033 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
12034 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
12035 // libaom clips `av1_foreach_transformed_block_in_plane` to
12036 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
12037 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
12038 // TOP-LEFT sample falls outside the frame is never coded. We read
12039 // coefficients for those phantom units and desynced the stream at
12040 // the very next symbol.
12041 if tu_px >= y.true_width || tu_py >= y.true_height {
12042 continue;
12043 }
12044 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
12045 // transform unit INSIDE a block, which is a different rule from
12046 // the standalone-block table [`Reach::of`] applies -- and the
12047 // reason a depth-2 superblock strip came out one sample off
12048 // before this: `Reach::of(tx, ..)` answered as if the unit were
12049 // its own block at that superblock position.
12050 // * top-right: if the unit's right neighbour is still inside the
12051 // strip the pixels are already reconstructed (`col_off +
12052 // tx_wide < plane_bw`); otherwise only the strip's own top row
12053 // of units can reach past it, through the block-level answer.
12054 // * bottom-left: a unit that is not in the strip's left column
12055 // has none (`col_off > 0` returns 0); inside the strip
12056 // (`row_off + tx_high < plane_bh`) they are the left
12057 // neighbour's, already reconstructed; the last row falls back
12058 // to the block-level answer.
12059 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
12060 // The unit's own window on the block's palette prediction.
12061 if let Some(buf) = &m.palette_y {
12062 let tu_buf: Vec<u16> = (0..tx_h)
12063 .flat_map(|i| {
12064 let base = (row_off + i) * bw + col_off;
12065 buf[base..base + tx_w].iter().copied()
12066 })
12067 .collect();
12068 set_palette_pred(tu_buf, fctx);
12069 }
12070 if m.skip {
12071 push_intra_rect(
12072 0,
12073 tu_px,
12074 tu_py,
12075 tx_w,
12076 tx_h,
12077 m.mode,
12078 m.angle_delta_y,
12079 tu_reach,
12080 &zero_tu,
12081 None,
12082 m.filter_intra,
12083 m.smooth_neighbor,
12084 fctx,
12085 );
12086 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12087 } else if luma_64corner && luma_rect.is_none() {
12088 // The un-split 64-level luma transform: `read_coeffs` on the
12089 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
12090 // and the real rect shape passed through for
12091 // `av1_nz_map_ctx_offset` -- byte for byte
12092 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
12093 // 64-level strip gate already proves. `tx_type` is not coded
12094 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
12095 // the square-up size is TX_64X64), and this unit covers its
12096 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
12097 if crate::envflags::env_flag!("EC_RECT64TU") {
12098 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
12099 }
12100 hit_do! {
12101 RECT64_CORNER_TU_HITS.with(|c| {
12102 let mut v = c.get();
12103 v[usize::from(tx_h > tx_w)] += 1;
12104 c.set(v);
12105 });
12106 }
12107 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12108 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
12109 let (corner, tu_tx_type) = read_coeffs(
12110 dec,
12111 &mut coding,
12112 default_scan(TX32),
12113 0,
12114 dc_sign_ctx(tu_around.2),
12115 TxType::DctDct,
12116 Some((tx_w, tx_h)),
12117 )?;
12118 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
12119 let mut tu_grid = vec![0i32; tx_w * tx_h];
12120 for row in 0..ch {
12121 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
12122 }
12123 let residual = dequant_and_inverse_typed_wh(
12124 &tu_grid,
12125 tx_w,
12126 tx_h,
12127 crate::decode::bit_depth(fctx),
12128 block_q_idx(fctx),
12129 plane_q_delta(0, fctx).0,
12130 plane_q_delta(0, fctx).1,
12131 tu_tx_type,
12132 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12133 );
12134 push_intra_rect(
12135 0,
12136 tu_px,
12137 tu_py,
12138 tx_w,
12139 tx_h,
12140 m.mode,
12141 m.angle_delta_y,
12142 tu_reach,
12143 &residual,
12144 None,
12145 m.filter_intra,
12146 m.smooth_neighbor,
12147 fctx,
12148 );
12149 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12150 } else if let Some((rect_set, rect_scan)) = luma_rect {
12151 // The rect-unit twin of the square arm below: same contexts,
12152 // same order, through the rect coefficient reader. The
12153 // `tx_type` CDF row of a filter-intra block is
12154 // `fimode_to_intradir[filter_intra_mode]`, never the block's
12155 // own (always DC_PRED) mode -- [`read_plane`] applies that
12156 // for the square arm, so this one must too.
12157 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12158 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
12159 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
12160 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
12161 // neighbour-magnitude table is for a unit SMALLER than its
12162 // block. [`decode_block_rect`]'s own unsplit read passes a
12163 // literal 0 for the same reason; this arm applied the table
12164 // unconditionally and desynced every depth-0 rect strip that
12165 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
12166 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
12167 0
12168 } else {
12169 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
12170 };
12171 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
12172 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12173 dec,
12174 &mut coding,
12175 rect_scan,
12176 tx_w,
12177 tx_h,
12178 tu_skip_ctx,
12179 dc_sign_ctx(tu_around.2),
12180 TxType::DctDct,
12181 0,
12182 )?;
12183 let residual = dequant_and_inverse_typed_wh(
12184 &tu_grid,
12185 tx_w,
12186 tx_h,
12187 crate::decode::bit_depth(fctx),
12188 block_q_idx(fctx),
12189 plane_q_delta(0, fctx).0,
12190 plane_q_delta(0, fctx).1,
12191 tu_tx_type,
12192 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12193 );
12194 push_intra_rect(
12195 0,
12196 tu_px,
12197 tu_py,
12198 tx_w,
12199 tx_h,
12200 m.mode,
12201 m.angle_delta_y,
12202 tu_reach,
12203 &residual,
12204 None,
12205 m.filter_intra,
12206 m.smooth_neighbor,
12207 fctx,
12208 );
12209 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12210 } else {
12211 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12212 // This unit is smaller than the block it sits in, so
12213 // `txb_skip_ctx` is the neighbour-magnitude table, not the
12214 // lone-TU 0 (spec `get_txb_ctx_general`).
12215 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12216 let tu_grid = read_plane(
12217 dec,
12218 cdfs,
12219 luma_set,
12220 &luma_scan,
12221 0,
12222 tu_around,
12223 m.mode,
12224 m.mode,
12225 m.angle_delta_y,
12226 tu_reach,
12227 y,
12228 tu_px,
12229 tu_py,
12230 tx_w,
12231 tx_w,
12232 base_q_idx,
12233 None,
12234 m.filter_intra,
12235 Some(tu_skip_ctx),
12236 m.smooth_neighbor,
12237 fctx,
12238 )?;
12239 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12240 }
12241 }
12242 }
12243 // CHROMA: one un-split rect transform for the whole strip.
12244 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
12245 // units -- each stamps its own neighbour context as it is read, and the
12246 // whole-block `record_split_luma_rect_mi` below would overwrite all of
12247 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
12248 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
12249 // collected here and replayed after that record.
12250 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12251 // The chroma_tiled arm below stamps each unit's coefficient context
12252 // immediately (so the NEXT unit reads it), then the whole-strip
12253 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
12254 // whole-strip state and the per-unit DC signs and levels are lost
12255 // (class `override-slot-on-one-arm`). The units are collected here and
12256 // replayed after that record, the way the lossless arm's
12257 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
12258 // already do.
12259 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12260 let ac = m.alpha.map(|_| {
12261 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
12262 // luma -- the 8-px-wide region the floored 4-px chroma block covers
12263 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
12264 if chroma_422_pair_wide {
12265 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
12266 } else {
12267 cfl_src_rect(px, py, bw, bh)
12268 }
12269 });
12270 let reach = if chroma_422_pair_wide {
12271 // The chroma units predict off the PAIR block's edges: an odd-column
12272 // strip's pair starts 4 luma px to the strip's left, so the strip's
12273 // own answer names the wrong above/right samples (the pair16 arm's
12274 // `pair_reach`, one partition level up).
12275 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12276 } else {
12277 block_reach
12278 };
12279 let (u_grid, v_grid) = if mono(fctx) {
12280 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12281 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12282 // section -- the skipped-strip pushes, the lossless raster and the
12283 // un-split `read_coeffs_rect` below -- is bypassed.
12284 let zero = Grid::Zero(chroma_w * chroma_h);
12285 (zero.clone(), zero)
12286 } else if m.skip {
12287 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12288 if chroma_422_pair_wide || chroma_422_oob {
12289 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12290 // per transform unit even when the strip is skipped
12291 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12292 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12293 // units -- one whole-plane push here would ask the intra
12294 // predictor for a 1:8 rect it never needs.
12295 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12296 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12297 // grid at the floored anchor `chroma_x`.
12298 let (uw, uh) = (4usize, 8usize);
12299 for plane_idx in 1..=2 {
12300 if let Some((ub, vb)) = &m.palette_uv {
12301 let buf = if plane_idx == 1 { ub } else { vb };
12302 set_palette_pred(buf.clone(), fctx);
12303 }
12304 for cu_row in 0..chroma_block_h / uh {
12305 for cu_col in 0..chroma_block_w / uw {
12306 push_intra_rect(
12307 plane_idx,
12308 chroma_x + cu_col * uw,
12309 cpy + cu_row * uh,
12310 uw,
12311 uh,
12312 m.uv_predict_mode,
12313 m.angle_delta_uv,
12314 reach,
12315 &ZERO_RESIDUAL[..uw * uh],
12316 m.alpha
12317 .zip(ac.clone())
12318 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12319 None,
12320 m.smooth_neighbor_uv,
12321 fctx,
12322 );
12323 }
12324 }
12325 }
12326 } else {
12327 if let Some((ub, _)) = &m.palette_uv {
12328 set_palette_pred(ub.clone(), fctx);
12329 }
12330 push_intra_rect(
12331 1,
12332 cpx,
12333 cpy,
12334 chroma_w,
12335 chroma_h,
12336 m.uv_predict_mode,
12337 m.angle_delta_uv,
12338 reach,
12339 &zero,
12340 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12341 None,
12342 m.smooth_neighbor_uv,
12343 fctx,
12344 );
12345 if let Some((_, vb)) = &m.palette_uv {
12346 set_palette_pred(vb.clone(), fctx);
12347 }
12348 push_intra_rect(
12349 2,
12350 cpx,
12351 cpy,
12352 chroma_w,
12353 chroma_h,
12354 m.uv_predict_mode,
12355 m.angle_delta_uv,
12356 reach,
12357 &zero,
12358 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12359 None,
12360 m.smooth_neighbor_uv,
12361 fctx,
12362 );
12363 }
12364 (zero.clone(), zero)
12365 } else if lossless(fctx) {
12366 // lane-lossless: the strip's chroma plane block is coded as 4x4
12367 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12368 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12369 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12370 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12371 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12372 // offset (our `+3` row base) whenever the plane block is bigger than
12373 // the transform.
12374 let scan4 = default_scan(4);
12375 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12376 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12377 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12378 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12379 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12380 // cell), and the 8-px step made every unit past the first column/row
12381 // read its `txb_skip` context at the WRONG mi (two cells over) and
12382 // stamp a 2-cell span with one unit's state -- the polluted above-band
12383 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12384 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12385 // ours read `above[28..29]` where the oracle read `above[26]`).
12386 let span_x = 4 << ss_x(fctx);
12387 let span_y = 4 << ss_y(fctx);
12388 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12389 for plane_idx in 1..=2 {
12390 for cu_row in 0..ch_n {
12391 for cu_col in 0..cw_n {
12392 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12393 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
12394 let cu_reach = tu_reach(
12395 bw,
12396 bh,
12397 cu_col * span_x,
12398 cu_row * span_y,
12399 span_x,
12400 block_reach,
12401 px,
12402 py,
12403 y.width,
12404 y.height,
12405 fctx,
12406 );
12407 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12408 if let Some((ub, vb)) = &m.palette_uv {
12409 let pbuf = if plane_idx == 1 { ub } else { vb };
12410 set_palette_pred(
12411 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12412 fctx,
12413 );
12414 }
12415 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12416 let grid = read_plane(
12417 dec,
12418 cdfs,
12419 TxbSet::Chroma4,
12420 &scan4,
12421 plane_idx,
12422 cu_around[plane_idx],
12423 m.mode,
12424 m.uv_predict_mode,
12425 m.angle_delta_uv,
12426 cu_reach,
12427 plane,
12428 cu_x,
12429 cu_y,
12430 4,
12431 4,
12432 base_q_idx,
12433 m.alpha
12434 .zip(ac)
12435 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12436 None,
12437 offset,
12438 m.smooth_neighbor_uv,
12439 fctx,
12440 )?;
12441 if span_x == 4 && span_y == 4 {
12442 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
12443 }
12444 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
12445 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
12446 last[plane_idx - 1] = grid;
12447 }
12448 }
12449 }
12450 let [ug, vg] = last;
12451 (ug, vg)
12452 } else if chroma_tiled {
12453 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
12454 if chroma_422_pair_wide || chroma_422_oob {
12455 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
12456 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
12457 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
12458 // see above). For the 4-wide strip the units tile the PAIR's
12459 // plane, stepping from the floored anchor.
12460 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
12461 } else {
12462 match (chroma_w, chroma_h) {
12463 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
12464 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
12465 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
12466 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
12467 // through the square reader like every other square chroma unit.
12468 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
12469 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
12470 _ => unreachable!("chroma_tiled"),
12471 }
12472 };
12473 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
12474 // frame's square chroma units count it.
12475 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12476 hit!(CHROMA422_SQUARE_HITS);
12477 }
12478 if chroma_422_pair_wide {
12479 hit!(CHROMA422_PAIR_WIDE_HITS);
12480 }
12481 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
12482 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
12483 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
12484 // the pinned Release oracle), so its txb_skip rows always carry the
12485 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
12486 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
12487 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12488 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
12489 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
12490 // mode-indexed default, the same rule the unsplit arm below applies.
12491 let default_tx = if uw.max(uh) >= 32 {
12492 TxType::DctDct
12493 } else {
12494 default_intra_tx_type(m.uv_predict_mode as u8)
12495 };
12496 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
12497 for plane_idx in 1..=2 {
12498 for cu_row in 0..nh {
12499 for cu_col in 0..nw {
12500 let luma_span_x = uw << ss_x(fctx);
12501 let luma_span_y = uh << ss_y(fctx);
12502 let cu_mi = (
12503 mi_r + cu_row * (luma_span_y / MI),
12504 if chroma_422_pair_wide {
12505 mi_c & !1
12506 } else {
12507 mi_c
12508 } + cu_col * (luma_span_x / MI),
12509 );
12510 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
12511 // chroma context per chroma cell
12512 // ([`Neighbours::around_mi_422_chroma`], the block-8
12513 // rule) -- the plain rect walk samples one chroma cell
12514 // twice at ss_x 1. Every pre-existing shape keeps its own
12515 // walk.
12516 // lane-av1422mi24: the plain rect walk's double-count
12517 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
12518 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
12519 // read its above dc votes twice and its U dc_sign one
12520 // ctx row high (t422 frame 1). Route every ss (1,0)
12521 // unit through the every-second-above-cell sampling;
12522 // 4:2:0/4:4:4 keep the plain walk verbatim.
12523 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
12524 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
12525 } else {
12526 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
12527 };
12528 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
12529 let cfl = m.alpha.map(|(au, av)| {
12530 let alpha = if plane_idx == 1 { au } else { av };
12531 (
12532 alpha,
12533 if chroma_422_pair_wide {
12534 // The unit's co-located luma is the PAIR's
12535 // 8-px-wide band at the floored mi column.
12536 cfl_src_rect(
12537 (mi_c & !1) * MI + cu_col * luma_span_x,
12538 py + cu_row * luma_span_y,
12539 luma_span_x,
12540 luma_span_y,
12541 )
12542 } else {
12543 cfl_src_rect(
12544 px + cu_col * luma_span_x,
12545 py + cu_row * luma_span_y,
12546 luma_span_x,
12547 luma_span_y,
12548 )
12549 },
12550 )
12551 });
12552 // lane-av1-422kf: the palette colour map is consumed per
12553 // unit here like every other chroma arm (`av1_visit_palette`
12554 // feeds the whole plane block; window it to this unit).
12555 // Without this the square chroma rows decoded a uv-palette
12556 // strip's chroma as plain DC (class same-symbols-silent-
12557 // prediction: the rng stayed in sync, only the prediction
12558 // was dropped).
12559 if let Some((ub, vb)) = &m.palette_uv {
12560 let buf = if plane_idx == 1 { ub } else { vb };
12561 set_palette_pred(
12562 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
12563 fctx,
12564 );
12565 }
12566 // 32x32 does not fit read_coeffs_rect's scratch (768). The
12567 // square reader is the path every other 32x32 chroma unit uses.
12568 let levels = if uw == uh {
12569 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12570 read_plane(
12571 dec,
12572 cdfs,
12573 set,
12574 scan,
12575 plane_idx,
12576 cu_around[plane_idx],
12577 m.mode,
12578 m.uv_predict_mode,
12579 m.angle_delta_uv,
12580 reach,
12581 plane,
12582 cu_x,
12583 cu_y,
12584 uw,
12585 uw,
12586 base_q_idx,
12587 cfl,
12588 None,
12589 bigger.then_some(3),
12590 m.smooth_neighbor_uv,
12591 fctx,
12592 )?
12593 } else {
12594 let skip_ctx = usize::from(cu_around[plane_idx].0)
12595 + usize::from(cu_around[plane_idx].1)
12596 + usize::from(bigger) * 3;
12597 let mut coding = cdfs.txb(set, m.uv_predict_mode);
12598 let (levels, tx_type) = read_coeffs_rect(
12599 dec,
12600 &mut coding,
12601 scan,
12602 uw,
12603 uh,
12604 skip_ctx,
12605 dc_sign_ctx(cu_around[plane_idx].2),
12606 default_tx,
12607 plane_idx,
12608 )?;
12609 let residual = dequant_and_inverse_typed_wh(
12610 &levels,
12611 uw,
12612 uh,
12613 crate::decode::bit_depth(fctx),
12614 block_q_idx(fctx),
12615 plane_q_delta(plane_idx, fctx).0,
12616 plane_q_delta(plane_idx, fctx).1,
12617 tx_type,
12618 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
12619 );
12620 push_intra_rect(
12621 plane_idx,
12622 cu_x,
12623 cu_y,
12624 uw,
12625 uh,
12626 m.uv_predict_mode,
12627 m.angle_delta_uv,
12628 reach,
12629 &residual,
12630 cfl,
12631 None,
12632 m.smooth_neighbor_uv,
12633 fctx,
12634 );
12635 levels
12636 };
12637 neighbours.record_mi_chroma(
12638 cu_mi,
12639 luma_span_x,
12640 luma_span_y,
12641 plane_idx,
12642 &levels,
12643 );
12644 tiled_chroma_units.push((
12645 cu_mi,
12646 plane_idx,
12647 levels.clone(),
12648 luma_span_x,
12649 luma_span_y,
12650 ));
12651 last[plane_idx - 1] = levels;
12652 }
12653 }
12654 }
12655 (last[0].clone(), last[1].clone())
12656 } else {
12657 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
12658 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12659 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
12660 // so only the 16x8/8x16 pair takes the mode-indexed default.
12661 let default_tx = if chroma_w.max(chroma_h) >= 32 {
12662 TxType::DctDct
12663 } else {
12664 default_intra_tx_type(m.uv_predict_mode as u8)
12665 };
12666 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
12667 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
12668 // counts every chroma column's whole-unit dc sign twice (the t422
12669 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
12670 // row high). Luma keeps the per-mi gather; the two chroma planes
12671 // take [`Neighbours::around_mi_422_chroma`]'s every-second
12672 // above-cell sampling, like every other 4:2:2 chroma gather.
12673 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
12674 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12675 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
12676 around[1] = c[1];
12677 around[2] = c[2];
12678 }
12679 let mut grids: Vec<Grid> = Vec::with_capacity(2);
12680 for plane_idx in 1..=2 {
12681 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
12682 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
12683 let (levels, tx_type) = read_coeffs_rect(
12684 dec,
12685 &mut coding,
12686 chroma_scan,
12687 chroma_w,
12688 chroma_h,
12689 skip_ctx,
12690 dc_sign_ctx(around[plane_idx].2),
12691 default_tx,
12692 plane_idx,
12693 )?;
12694 // The same delta_q proof the unsplit rect64 path records
12695 // (lane-rectsplit r4: lifting the split-transform refusal moved
12696 // superblock strips onto this path, so only counting there would
12697 // leave the delta_q gate's counter silent for them).
12698 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
12699 hit!(RECT64_QIDX_DRIFT_HITS);
12700 }
12701 let residual = dequant_and_inverse_typed_wh(
12702 &levels,
12703 chroma_w,
12704 chroma_h,
12705 crate::decode::bit_depth(fctx),
12706 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
12707 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
12708 // reading `current_q_idx` here dropped the segment feature
12709 // that every other dequant site applies (class
12710 // `parsed-then-discarded`).
12711 block_q_idx(fctx),
12712 plane_q_delta(plane_idx, fctx).0,
12713 plane_q_delta(plane_idx, fctx).1,
12714 tx_type,
12715 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
12716 );
12717 let cfl = m
12718 .alpha
12719 .zip(ac)
12720 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
12721 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12722 if let Some((ub, vb)) = &m.palette_uv {
12723 let buf = if plane_idx == 1 { ub } else { vb };
12724 set_palette_pred(buf.clone(), fctx);
12725 }
12726 push_intra_rect(
12727 plane_idx,
12728 cpx,
12729 cpy,
12730 chroma_w,
12731 chroma_h,
12732 m.uv_predict_mode,
12733 m.angle_delta_uv,
12734 reach,
12735 &residual,
12736 cfl,
12737 None,
12738 m.smooth_neighbor_uv,
12739 fctx,
12740 );
12741 grids.push(levels);
12742 }
12743 let mut it = grids.into_iter();
12744 (it.next().unwrap(), it.next().unwrap())
12745 };
12746 neighbours.record_split_luma_rect_mi(
12747 at_mi,
12748 bw,
12749 bh,
12750 m.mode,
12751 m.uv_predict_mode,
12752 [&u_grid, &v_grid],
12753 );
12754 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
12755 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12756 }
12757 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
12758 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12759 }
12760 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
12761 neighbours.fill_lf_grid_rect(
12762 (mi_r, mi_c),
12763 bw / MI,
12764 bh / MI,
12765 tx_w as u8,
12766 tx_h as u8,
12767 0,
12768 fctx,
12769 );
12770 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12771 let (rng, _) = dec.debug_state();
12772 eprintln!(
12773 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
12774 tx={tx_w}x{tx_h} rng={rng}"
12775 );
12776 }
12777 Ok(())
12778}
12779
12780/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
12781/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
12782/// because it predicts squares only. Every pixel here goes through the rect
12783/// machinery the key-frame paths already prove: [`decode_rect_split`], which
12784/// at `depth == 0` is the unsplit strip as a single transform unit and
12785/// beyond it the per-unit walk of [`depth_to_tx_wh`].
12786///
12787/// What is genuinely different from [`decode_block_rect`] is the mode
12788/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
12789/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
12790/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
12791/// intra-in-inter arm's own reads at the rect footprint, including its
12792/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
12793/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
12794/// square and this arm) and a nonzero luma angle delta refused by name.
12795///
12796/// The strip's own neighbour records (luma per transform unit, chroma, skip
12797/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
12798/// inter-side bands and the mi map.
12799#[allow(clippy::too_many_arguments)]
12800/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
12801/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
12802/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
12803/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
12804/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
12805/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
12806/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
12807/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
12808/// table here rather than a shift of `bw.min(bh)`.
12809fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12810 Some(match (bw.min(bh), bw.max(bh)) {
12811 (8, 16) => (1usize, 1usize),
12812 (16, 32) => (2, 2),
12813 (32, 64) => (3, 3),
12814 (8, 32) => (1, 2),
12815 (16, 64) => (2, 3),
12816 _ => return None,
12817 })
12818}
12819
12820/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
12821/// block path"): the shapes that can reach that arm, enumerated against the
12822/// MEASURED domain of the inter block path
12823/// ([`INTER_BLOCK_SHAPES`], the census the gate
12824/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
12825/// fills from three real streams).
12826///
12827/// [`decode_intra_rect_in_inter`] is called from one site, under
12828/// `write_w != side || write_h != side`, and only after two earlier arms have
12829/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
12830/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
12831/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
12832/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
12833/// and each of those has a row, so the refusal names a shape no measured
12834/// stream can present.
12835#[test]
12836fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12837 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12838 // names that string exactly (placeholders included) and pins its guard
12839 // site. The enumeration below establishes the shape domain; on its own it
12840 // never said WHICH string the domain was about, so under a real function
12841 // boundary -- rather than a window that ran into the next test -- the row
12842 // read as unanchored.
12843 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)";
12844 assert!(
12845 include_str!("decode.rs").contains(REFUSAL),
12846 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12847 );
12848 let mut checked = 0;
12849 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12850 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
12851 continue;
12852 }
12853 assert!(
12854 intra_in_inter_size_row(w, h).is_some(),
12855 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
12856 the \"no size-group/tx-category row\" refusal"
12857 );
12858 checked += 1;
12859 }
12860 assert_eq!(
12861 checked, 10,
12862 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
12863 lookup, not the 10 this claim was measured over"
12864 );
12865}
12866
12867/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
12868/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
12869/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
12870/// matched before the square arm's `log2` shortcut).
12871///
12872/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
12873/// row here"; the enumeration below is what proves no conformant block can
12874/// reach it.
12875pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
12876 Some(match (write_w, write_h) {
12877 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
12878 // below maps 128 to row 4 (BLOCK_16X32).
12879 (64, 128) => 14,
12880 (128, 64) => 15,
12881 (128, 128) => 16,
12882 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
12883 (16, 32) => 4,
12884 (32, 16) => 5,
12885 (32, 64) => 6,
12886 (64, 32) => 7,
12887 (8, 32) => 8,
12888 (32, 8) => 9,
12889 (16, 64) => 10,
12890 (64, 16) => 11,
12891 // lane-inter4 r3: the 16x16-level rect inter leaves.
12892 (8, 16) => 12,
12893 (16, 8) => 13,
12894 _ => return None,
12895 })
12896}
12897
12898/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
12899/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
12900/// `block_size_wide`/`block_size_high`).
12901#[cfg(test)]
12902const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12903 (4, 4),
12904 (4, 8),
12905 (8, 4),
12906 (8, 8),
12907 (8, 16),
12908 (16, 8),
12909 (16, 16),
12910 (16, 32),
12911 (32, 16),
12912 (32, 32),
12913 (32, 64),
12914 (64, 32),
12915 (64, 64),
12916 (64, 128),
12917 (128, 64),
12918 (128, 128),
12919 (4, 16),
12920 (16, 4),
12921 (8, 32),
12922 (32, 8),
12923 (16, 64),
12924 (64, 16),
12925];
12926
12927/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
12928/// shape with no CDF row here" names a shape no conformant stream can present.
12929///
12930/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
12931/// whose `write_w.min(write_h) >= 8` clause is libaom's
12932/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
12933/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
12934/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
12935/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
12936/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
12937/// clause rejects before the lookup.
12938#[test]
12939fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12940 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12941 // names it and pins its guard site.
12942 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
12943 assert!(
12944 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
12945 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12946 );
12947 let mut rows = std::collections::BTreeSet::new();
12948 let mut excluded = 0;
12949 for (w, h) in BLOCK_SIZES_ALL_WH {
12950 if w.min(h) < 8 {
12951 excluded += 1;
12952 assert!(
12953 w == 4 || h == 4,
12954 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
12955 );
12956 continue;
12957 }
12958 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
12959 panic!(
12960 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
12961 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
12962 )
12963 });
12964 assert!(
12965 row < 17,
12966 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
12967 );
12968 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
12969 }
12970 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
12971 assert_eq!(
12972 rows.len(),
12973 17,
12974 "17 eligible footprints must fill all 17 rows of the motion_mode table"
12975 );
12976}
12977
12978/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
12979/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
12980/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
12981/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
12982/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
12983/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
12984/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
12985/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
12986#[test]
12987fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
12988 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
12989 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
12990 let ss10_invalid: &[(&str, bool)] = &[
12991 ("4x4", false),
12992 ("4x8", true),
12993 ("8x4", false),
12994 ("8x8", false),
12995 ("8x16", true),
12996 ("16x8", false),
12997 ("16x16", false),
12998 ("16x32", true),
12999 ("32x16", false),
13000 ("32x32", false),
13001 ("32x64", true),
13002 ("64x32", false),
13003 ("64x64", false),
13004 ("64x128", true),
13005 ("128x64", false),
13006 ("128x128", false),
13007 ("4x16", true),
13008 ("16x4", false),
13009 ("8x32", true),
13010 ("32x8", false),
13011 ("16x64", true),
13012 ("64x16", false),
13013 ];
13014 for (footprint, invalid10) in ss10_invalid {
13015 let (w, h) = footprint.split_once('x').unwrap();
13016 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
13017 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
13018 // valid because a (2, 4) plane area rounds UP to the 4x4 read
13019 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
13020 // [`decode_rect_split`] at all.
13021 if (bw, bh) == (4, 4) {
13022 continue;
13023 }
13024 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
13025 for (ss_x, ss_y) in [(false, false), (true, true)] {
13026 assert!(
13027 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
13028 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
13029 );
13030 }
13031 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
13032 // BLOCK_INVALID column, anchored at the floored mi column.
13033 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
13034 assert_eq!(
13035 pair.is_some(),
13036 *invalid10 && bw == 4,
13037 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
13038 );
13039 if let Some((block_w, block_h, x, ctx_col)) = pair {
13040 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
13041 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
13042 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
13043 // An even-column strip anchors at its own cell.
13044 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
13045 Some((_, _, x, c)) => (x, c),
13046 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
13047 };
13048 assert_eq!(
13049 (x_even, col_even),
13050 (12, 6),
13051 "even column keeps its own cell"
13052 );
13053 }
13054 }
13055 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
13056 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
13057 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
13058 for (bw, bh) in [
13059 (8usize, 16),
13060 (16, 32),
13061 (32, 64),
13062 (64, 128),
13063 (8, 32),
13064 (16, 64),
13065 ] {
13066 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
13067 }
13068}
13069
13070fn decode_intra_rect_in_inter(
13071 dec: &mut SymbolDecoder,
13072 cdfs: &mut Cdfs,
13073 neighbours: &mut Neighbours,
13074 at: (usize, usize),
13075 bw: usize,
13076 bh: usize,
13077 skip: bool,
13078 allow_screen_content_tools: bool,
13079 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
13080 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
13081 strip16: Option<(bool, bool)>,
13082 y: &mut PlaneBuf<'static>,
13083 u: &mut PlaneBuf<'static>,
13084 v: &mut PlaneBuf<'static>,
13085 base_q_idx: u8,
13086 fctx: &crate::decode::FrameCtx,
13087) -> Result<()> {
13088 // `at` is in MI units (the inter path's own unit since lane-inter4);
13089 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
13090 // below are still keyed by.
13091 let (mi_r, mi_c) = at;
13092 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
13093 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
13094 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
13095 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
13096 // finding -- the category is NOT the same for every strip size).
13097 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
13098 // it is refused by name rather than read from the wrong CDF row.
13099 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
13100 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
13101 // tx-depth category is 1 -- but nothing here has to know either, because
13102 // the strip decodes through the very body the KEY FRAME path proves for
13103 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
13104 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
13105 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
13106 // inter-frame difference is the mode-info read, which
13107 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
13108 // `y_mode[0]` plus the `skip` this caller already read.
13109 if let Some((horz, has_chroma)) = strip16 {
13110 // lane-t900 r22: the screen-content refusal here was STALE (class
13111 // stale-premise): [`decode_rect4_16_strip`] takes
13112 // `allow_screen_content_tools` and reads the whole palette syntax
13113 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
13114 // pair) -- the key frame proves that body. Lifted with the 10-bit
13115 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
13116 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
13117 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
13118 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
13119 let res = decode_rect4_16_strip(
13120 dec,
13121 cdfs,
13122 neighbours,
13123 (mi_r, mi_c),
13124 horz,
13125 has_chroma,
13126 // The inter strips of the same partition publish their own
13127 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
13128 // has nothing to add here.
13129 None,
13130 y,
13131 u,
13132 v,
13133 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13134 allow_screen_content_tools,
13135 base_q_idx,
13136 fctx.tx_select_inter.with(std::cell::Cell::get),
13137 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13138 fctx,
13139 );
13140 fctx.intra_in_inter_mode.with(|c| c.set(None));
13141 let (mode, uv, (tx_w, tx_h)) = res?;
13142 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
13143 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
13144 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
13145 // block of an inter frame, intra ones included, and
13146 // `txfm_partition_update` for the var-tx context. The key-frame body
13147 // writes neither (a key frame has no var-tx tree and its own readers
13148 // use the deblock grid), so the block AFTER this strip read a stale
13149 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
13150 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
13151 // 16x16 row.
13152 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13153 for i in 0..bw / MI {
13154 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13155 *cell = tx_w as u8;
13156 }
13157 }
13158 for i in 0..bh / MI {
13159 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13160 *cell = tx_h as u8;
13161 }
13162 }
13163 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
13164 // coarse 16-px cell holds one entry for the whole 16x16 and the last
13165 // block to write it wins).
13166 neighbours.above_mode[c] = mode;
13167 neighbours.left_mode[r] = mode;
13168 if let Some(uvm) = uv {
13169 neighbours.above_uv_mode[c] = uvm;
13170 neighbours.left_uv_mode[r] = uvm;
13171 }
13172 neighbours.above_side[c] = bw;
13173 neighbours.left_side[r] = bh;
13174 if crate::envflags::env_flag!("EC_INTRA16X4") {
13175 eprintln!(
13176 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
13177 mi_c * MI,
13178 mi_r * MI
13179 );
13180 }
13181 hit_do! {
13182 INTRA16X4_IN_INTER_HITS.with(|h| {
13183 let mut v = h.get();
13184 v[usize::from(!horz)] += 1;
13185 v[2] += usize::from(has_chroma);
13186 h.set(v);
13187 });
13188 }
13189 return Ok(());
13190 }
13191 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
13192 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
13193 // puts BLOCK_128X64/64X128/128X128 in group 3 and
13194 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
13195 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
13196 // block decodes through the very body the KEY FRAME path proves for this
13197 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
13198 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
13199 // `Reach` rule and the frame-edge write clip). The only inter-frame
13200 // differences live inside that body: the mode-info read
13201 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
13202 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
13203 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
13204 // palette (>64) do not exist at this size and are refused by name there.
13205 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
13206 // `intra128_in_inter_witness2.obu` (gate
13207 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
13208 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
13209 // all 15 frames, so the hits are counted out of exact frames (class
13210 // `counter-from-refused-stream`). What r16/r17 could not find, and what
13211 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
13212 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
13213 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
13214 // where the frame EDGE forces it: a partial last superblock row has
13215 // `has_rows128 == false`, so the 128x64 top half is implied, and a
13216 // partial last column implies the 64x128 left half. Put content no
13217 // reference holds (a fresh smooth ramp) in exactly those two bands of an
13218 // inter frame and the encoder codes those forced halves INTRA.
13219 if bw.max(bh) == 128 {
13220 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
13221 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
13222 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
13223 // palette_syntax`), so a 128-root half consumes no palette syntax and
13224 // a screen-content frame's half is syntactically identical to the
13225 // non-screen one this arm already decodes byte-exact.
13226 if coeff_trace_on() {
13227 // lane-t900 r16: which decode-order frame this arm fires in --
13228 // interleaved with the `EC_COEFF_FRAME` markers, this is what
13229 // proves the hit is counted out of a frame that compares exact
13230 // (class `counter-from-refused-stream`).
13231 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
13232 }
13233 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
13234 let res = decode_block_128rect(
13235 dec,
13236 cdfs,
13237 neighbours,
13238 (r, c),
13239 bw,
13240 bh,
13241 y,
13242 u,
13243 v,
13244 base_q_idx,
13245 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13246 allow_screen_content_tools,
13247 fctx.tx_select_inter.with(std::cell::Cell::get),
13248 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13249 fctx,
13250 );
13251 fctx.intra_in_inter_mode.with(|c| c.set(None));
13252 return res;
13253 }
13254 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
13255 if crate::envflags::env_flag!("EC_OBMCREC") {
13256 eprintln!(
13257 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
13258 );
13259 }
13260 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
13261 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
13262 // can arrive here are enumerated against the measured block-shape
13263 // census ([`INTER_BLOCK_SHAPES`]) by
13264 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
13265 // -- every one of them has a row, so this arm names a shape no stream
13266 // has been able to present.
13267 return Err(unsupported(format!(
13268 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13269 )));
13270 };
13271 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13272 // screen-content frame ("palette syntax is consumed for square blocks
13273 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13274 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13275 // it, while the 2:1 reader inlined further down now codes the same syntax
13276 // itself. A real `--tune-content=screen` inter stream reached this refusal
13277 // on 8x16 / 16x8 strips (gate
13278 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13279 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13280 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13281 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13282 // luma/chroma transform tables, the per-unit split walk and the strip's
13283 // own neighbour records). The ONLY difference on an inter frame is the
13284 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13285 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13286 // this caller already read. `tx_cat` above is the same category those
13287 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13288 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13289 if bw.max(bh) == 4 * bw.min(bh) {
13290 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13291 fctx.intra_in_inter_mode
13292 .with(|c| c.set(Some((size_group, skip))));
13293 let res = if bw.max(bh) == 64 {
13294 decode_block_rect64(
13295 dec,
13296 cdfs,
13297 neighbours,
13298 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13299 bw,
13300 bh,
13301 y,
13302 u,
13303 v,
13304 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13305 allow_screen_content_tools,
13306 base_q_idx,
13307 fctx.tx_select_inter.with(std::cell::Cell::get),
13308 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13309 fctx,
13310 )
13311 } else {
13312 decode_block_rect4(
13313 dec,
13314 cdfs,
13315 neighbours,
13316 (mi_r, mi_c),
13317 bw,
13318 bh,
13319 None,
13320 y,
13321 u,
13322 v,
13323 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13324 allow_screen_content_tools,
13325 base_q_idx,
13326 fctx.tx_select_inter.with(std::cell::Cell::get),
13327 fctx,
13328 )
13329 .map(|_| ())
13330 };
13331 fctx.intra_in_inter_mode.with(|c| c.set(None));
13332 res?;
13333 let shape = match (bw, bh) {
13334 (64, 16) => 0,
13335 (16, 64) => 1,
13336 (32, 8) => 2,
13337 _ => 3,
13338 };
13339 hit_do! {
13340 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13341 let mut v = h.get();
13342 v[shape] += 1;
13343 h.set(v);
13344 });
13345 }
13346 return Ok(());
13347 }
13348 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13349 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13350 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13351 // own, so a cross-decoder bisection could only see the block's first
13352 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13353 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13354 if step_trace {
13355 eprintln!(
13356 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13357 dec.debug_state().0
13358 );
13359 }
13360 if mode >= 13 {
13361 return Err(unsupported(
13362 "an intra mode this decoder does not code (round 2)",
13363 ));
13364 }
13365 // lane-angleinter (merged on main for the square intra-in-inter arm):
13366 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
13367 // directional predictor; this arm refused a nonzero one before the merge.
13368 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13369 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
13370 } else {
13371 0
13372 };
13373 if angle_delta_y != 0 {
13374 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
13375 }
13376 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
13377 // superblock-level strip reads the no-CFL alphabet -- the same split
13378 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
13379 //
13380 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
13381 // (libaom `decodemv.c:933`).
13382 let has_chroma = !mono(fctx);
13383 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
13384 let uv_mode = if !has_chroma {
13385 DC_PRED
13386 } else if cfl_allowed {
13387 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13388 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13389 } else {
13390 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13391 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13392 };
13393 if step_trace {
13394 eprintln!(
13395 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
13396 u8::from(cfl_allowed),
13397 dec.debug_state().0
13398 );
13399 }
13400 if (9..=12).contains(&uv_mode) {
13401 hit!(SMOOTH_UV_HITS);
13402 }
13403 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
13404 Some(read_cfl_alphas(dec, cdfs))
13405 } else {
13406 None
13407 };
13408 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13409 DC_PRED
13410 } else {
13411 uv_mode
13412 };
13413 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13414 hit!(DIRECTIONAL_UV_HITS);
13415 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13416 } else {
13417 0
13418 };
13419 if angle_delta_uv != 0 {
13420 hit!(UV_ANGLE_DELTA_HITS);
13421 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
13422 }
13423 // `read_palette_mode_info` (spec 5.11.13), in the position
13424 // `read_intra_block_mode_info` writes it: after the chroma mode and
13425 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
13426 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
13427 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
13428 // skipping the syntax here desynced the tile at the strip's own symbol.
13429 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
13430 // context and colour cache at its own mi position, and the two
13431 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
13432 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
13433 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
13434 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
13435 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13436 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13437 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
13438 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
13439 let use_palette_y =
13440 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
13441 if use_palette_y {
13442 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13443 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
13444 }
13445 // A 2:1 strip of at least 8x8 is always a chroma reference, so
13446 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
13447 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13448 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
13449 let use_palette_uv = has_chroma
13450 && uv_mode == DC_PRED
13451 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
13452 if crate::envflags::env_flag!("EC_PALSYN") {
13453 eprintln!(
13454 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
13455 use_palette_y as i32,
13456 use_palette_uv as i32,
13457 dec.debug_state().0
13458 );
13459 }
13460 if use_palette_uv {
13461 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13462 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
13463 palette_uv_pending = Some((n, u_colors, v_colors));
13464 }
13465 }
13466 // lane-fiinter (merged on main for the square intra-in-inter arm):
13467 // `read_filter_intra_mode_info` is the tail of
13468 // `read_intra_block_mode_info`, after the palette syntax (refused whole
13469 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
13470 // 2:1 strips with both sides <= 32 -- their own CDF rows
13471 // ([`filter_intra_size_class_rect`]).
13472 let mut filter_intra = None;
13473 if mode == DC_PRED
13474 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
13475 // `av1_filter_intra_allowed` excludes a palette-Y block.
13476 && palette_y_pending.is_none()
13477 && let Some(class) = filter_intra_size_class_rect(bw, bh)
13478 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
13479 {
13480 hit!(FILTER_INTRA_HITS);
13481 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
13482 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
13483 }
13484 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
13485 let palette_y = palette_y_pending.map(|(n, colors)| {
13486 let map = decode_color_index_map_wh(
13487 dec,
13488 cdfs,
13489 n,
13490 bw,
13491 bh,
13492 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13493 false,
13494 );
13495 hit!(PALETTE_HITS);
13496 hit!(PALETTE_RECT_HITS);
13497 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
13498 PaletteY {
13499 size: n,
13500 colors,
13501 map,
13502 }
13503 });
13504 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13505 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
13506 let on = palette_onscreen_uv(
13507 (bw, bh),
13508 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13509 (cw, ch),
13510 (ss_x(fctx), ss_y(fctx)),
13511 );
13512 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
13513 hit!(PALETTE_UV_HITS);
13514 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
13515 PaletteUv {
13516 size: n,
13517 u_colors,
13518 v_colors,
13519 map,
13520 }
13521 });
13522 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
13523 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
13524 // chroma ones -- [`decode_block_rect`]'s own pair.
13525 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
13526 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
13527 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
13528 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
13529 // one exactly as [`decode_leaf8`] already does (class
13530 // context-read-from-one-cell).
13531 let coarse_pair = neighbours.modes_above_left(r, c);
13532 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
13533 if (nb_above_mode, nb_left_mode) != coarse_pair {
13534 hit!(EDGE_FILTER_MI_FIX_HITS);
13535 }
13536 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13537 if smooth_neighbor {
13538 hit!(SMOOTH_LUMA_HITS);
13539 }
13540 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13541 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13542 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
13543 // an inter frame codes no depth symbol either (`xd->lossless` is per
13544 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
13545 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
13546 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
13547 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
13548 let d = match tx_cat {
13549 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
13550 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
13551 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
13552 };
13553 if step_trace {
13554 eprintln!(
13555 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
13556 dec.debug_state().0
13557 );
13558 }
13559 d
13560 } else {
13561 0
13562 };
13563 if depth != 0 || lossless(fctx) {
13564 hit!(TX_DEPTH_HITS);
13565 // lane-intrasplit r1: a split intra strip in an inter frame walks the
13566 // key frame's own per-TU path ([`decode_rect_split`] below); what was
13567 // wrong when this refusal was written was the depth SYMBOL, not the walk.
13568 hit_do! {
13569 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
13570 let mut v = h.get();
13571 v[depth.min(2)] += 1;
13572 h.set(v);
13573 });
13574 }
13575 }
13576 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
13577 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
13578 // the two are indistinguishable when the diagnostic fires on splits alone.
13579 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
13580 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
13581 }
13582 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13583 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
13584 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
13585 // of an inter frame, intra ones included -- with the skip term 0 it
13586 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
13587 // and `left_txfm_context` to `tx_size_high` over its height. This strip
13588 // wrote neither, so the next block's var-tx `txfm_partition` context read
13589 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
13590 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
13591 // mi(16,0) and desyncing the tile at that symbol.
13592 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13593 let modes = RectStripModes {
13594 skip,
13595 mode,
13596 angle_delta_y,
13597 uv_predict_mode,
13598 angle_delta_uv,
13599 alpha,
13600 filter_intra,
13601 smooth_neighbor,
13602 smooth_neighbor_uv,
13603 palette_y: palette_y
13604 .as_ref()
13605 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
13606 palette_uv: palette_uv.as_ref().map(|p| {
13607 (
13608 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13609 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13610 )
13611 }),
13612 };
13613 decode_rect_split(
13614 dec,
13615 cdfs,
13616 neighbours,
13617 (mi_r, mi_c),
13618 bw,
13619 bh,
13620 tx_w,
13621 tx_h,
13622 &modes,
13623 y,
13624 u,
13625 v,
13626 base_q_idx,
13627 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13628 fctx,
13629 )?;
13630 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
13631 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
13632 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
13633 // left column over its height. This arm wrote neither before lane-intrasplit
13634 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
13635 // context across the strip's footprint.
13636 for i in 0..bw / MI {
13637 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13638 *cell = tx_w as u8;
13639 }
13640 }
13641 for i in 0..bh / MI {
13642 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13643 *cell = tx_h as u8;
13644 }
13645 }
13646 // The strip's own palette state into the mi-granular neighbour bands, so
13647 // the next block's colour cache and `palette_y_mode` context are libaom's.
13648 record_strip_palette(
13649 neighbours,
13650 (mi_r, mi_c),
13651 bw,
13652 bh,
13653 palette_y.as_ref().map_or(0, |p| p.size),
13654 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
13655 palette_uv.as_ref().map_or(0, |p| p.size),
13656 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
13657 );
13658 let class = match bw.max(bh) {
13659 64 => 0,
13660 32 => 1,
13661 _ => 2,
13662 };
13663 hit_do! {
13664 INTRA_RECT_IN_INTER_HITS.with(|h| {
13665 let mut v = h.get();
13666 v[class] += 1;
13667 h.set(v);
13668 });
13669 }
13670 Ok(())
13671}
13672
13673/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
13674/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
13675///
13676/// libaom treats an intrabc block as INTER for everything except the mode-info
13677/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
13678/// (`blockd.h:373`), so
13679///
13680/// * `parse_decode_block` reads the transform size through the INTER var-tx
13681/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
13682/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
13683/// whose leaves publish their own resolved size back;
13684/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
13685/// frame's own pre-loop-filter reconstruction, at the coded block vector
13686/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
13687/// * `decode_token_recon_block`'s inter branch then reads one residual per
13688/// transform unit, through the INTER coefficient sets
13689/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
13690/// inheriting the colocated luma unit's coded `tx_type`.
13691///
13692/// Text order is libaom's: transform tree, prediction, luma residual, chroma
13693/// residual, bookkeeping. A skipped block codes no residual at all -- the
13694/// prediction is the reconstruction.
13695#[allow(clippy::too_many_arguments)]
13696fn decode_intrabc_rect(
13697 dec: &mut SymbolDecoder,
13698 cdfs: &mut Cdfs,
13699 neighbours: &mut Neighbours,
13700 (mi_r, mi_c): (usize, usize),
13701 (bw, bh): (usize, usize),
13702 skip: bool,
13703 (dv_row, dv_col): (i32, i32),
13704 y: &mut PlaneBuf<'static>,
13705 u: &mut PlaneBuf<'static>,
13706 v: &mut PlaneBuf<'static>,
13707 base_q_idx: u8,
13708 fctx: &crate::decode::FrameCtx,
13709) -> Result<()> {
13710 hit!(INTRABC_RECT_HITS);
13711 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
13712 let idx = usize::from(bh > bw);
13713 if skip {
13714 INTRABC_RECT_SKIPPED_HITS.with(|c| {
13715 let mut seen = c.get();
13716 seen[idx] += 1;
13717 c.set(seen);
13718 });
13719 } else {
13720 INTRABC_RECT_CODED_HITS.with(|c| {
13721 let mut seen = c.get();
13722 seen[idx] += 1;
13723 c.set(seen);
13724 });
13725 }
13726 let (px, py) = (mi_c * MI, mi_r * MI);
13727 // lane-whtshape: a LOSSLESS block's chroma plane block is
13728 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
13729 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
13730 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
13731 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
13732 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
13733 // walk below coded 2 units per plane where libaom codes 8.
13734 //
13735 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
13736 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
13737 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
13738 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
13739 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
13740 // the block at mi (92, 104) read all_zero=0 here against the oracle's
13741 // all_zero=1 -- the bit position forks there. Identical arithmetic at
13742 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
13743 // witness is the identity arm of this lane's gate.
13744 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13745 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
13746 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
13747 // shape this helper is called at, so the uv plane block is ONE unit --
13748 // the same call `decode_token_recon_block`'s own chroma loop makes.
13749 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13750 // lane-av1-intrabc r2: the square stride the proven INTER path uses
13751 // (`side`). The residual grids, the prediction windows AND
13752 // `TxParams::stride` are all laid out at it -- the block's own width
13753 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
13754 // exceeds the stride).
13755 let side = bw.max(bh);
13756 let cside = cw.max(ch);
13757 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
13758 // or bottom frame edge reads no transform-tree symbol for the units
13759 // outside it.
13760 let mi_cols = 2 * y.true_width.div_ceil(8);
13761 let mi_rows = 2 * y.true_height.div_ceil(8);
13762 let leaves = read_block_tx_size_rect(
13763 dec,
13764 cdfs,
13765 neighbours,
13766 (mi_r, mi_c),
13767 (bw, bh),
13768 (mi_cols, mi_rows),
13769 skip,
13770 fctx,
13771 )?;
13772 if leaves.is_some() {
13773 hit!(INTRABC_RECT_VARTX_HITS);
13774 }
13775 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
13776 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
13777 }
13778 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
13779 if crate::envflags::env_flag!("EC_IBCBLOCK") {
13780 eprintln!(
13781 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
13782 cw={cw} ch={ch} cside={cside} skip={skip}"
13783 );
13784 }
13785 // The whole-block prediction: `predict_inter_block` runs once, before any
13786 // coefficient is read. `flush_recon` first -- the source is this frame's
13787 // own reconstruction, including the writes this superblock has queued.
13788 flush_recon(fctx, y, u, v);
13789 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
13790 // reads it at the square stride, so re-lay it -- the same step the inter
13791 // path takes for its own square prediction buffer.
13792 let mut pred_y_dense = vec![0u16; bw * bh];
13793 mc::predict_with_filter(
13794 &y.data,
13795 y.width,
13796 y.true_width,
13797 y.true_height,
13798 mv_to_q4(px, dv_col, 0),
13799 mv_to_q4(py, dv_row, 0),
13800 bw,
13801 bh,
13802 mc::InterpFilterKind::Bilinear,
13803 &mut pred_y_dense,
13804 fctx,
13805 );
13806 let mut pred_y = vec![0u16; side * side];
13807 for row in 0..bh {
13808 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13809 }
13810 let mut pred_u_dense = vec![0u16; cw * ch];
13811 mc::predict_with_filter(
13812 &u.data,
13813 u.width,
13814 u.true_width,
13815 u.true_height,
13816 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13817 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13818 cw,
13819 ch,
13820 mc::InterpFilterKind::Bilinear,
13821 &mut pred_u_dense,
13822 fctx,
13823 );
13824 let mut pred_u = vec![0u16; cside * cside];
13825 for row in 0..ch {
13826 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13827 }
13828 let mut pred_v_dense = vec![0u16; cw * ch];
13829 mc::predict_with_filter(
13830 &v.data,
13831 v.width,
13832 v.true_width,
13833 v.true_height,
13834 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13835 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13836 cw,
13837 ch,
13838 mc::InterpFilterKind::Bilinear,
13839 &mut pred_v_dense,
13840 fctx,
13841 );
13842 let mut pred_v = vec![0u16; cside * cside];
13843 for row in 0..ch {
13844 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13845 }
13846 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13847 let luma_tx_type: TxType;
13848 let (luma_grid, u_grid, v_grid);
13849 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
13850 // kept so their per-4x4 slices can be re-stamped over the whole-block
13851 // record in the tail. `None` on every other arm.
13852 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
13853 if skip {
13854 // No residual syntax at all: the prediction IS the block.
13855 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
13856 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
13857 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
13858 push_mc_rect(
13859 0,
13860 px,
13861 py,
13862 side,
13863 bw,
13864 bh,
13865 Pred::Inline(&pred_y, side),
13866 &ZERO_RESIDUAL[..side * side],
13867 fctx,
13868 );
13869 push_mc_rect(
13870 1,
13871 cpx,
13872 cpy,
13873 cside,
13874 cw,
13875 ch,
13876 Pred::Inline(&pred_u, cside),
13877 &ZERO_RESIDUAL[..cside * cside],
13878 fctx,
13879 );
13880 push_mc_rect(
13881 2,
13882 cpx,
13883 cpy,
13884 cside,
13885 cw,
13886 ch,
13887 Pred::Inline(&pred_v, cside),
13888 &ZERO_RESIDUAL[..cside * cside],
13889 fctx,
13890 );
13891 if let Some(ls) = leaves.as_ref() {
13892 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
13893 // skip arm performs -- libaom `av1_reset_entropy_context`
13894 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
13895 // SKIPPED block zeroes its whole entropy-band footprint. This
13896 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
13897 // so a skipped lossless strip whose `leaves` resolved (every
13898 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13899 // returns the 4x4 grid before it looks at `skip`) left the
13900 // PREVIOUS occupant's luma bands standing and the NEXT block's
13901 // partition parse diverged from libaom's: the 320x242 lossless
13902 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
13903 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
13904 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13905 for &(row, col, tw, th) in ls {
13906 neighbours.record_mi_luma_rect(
13907 (mi_r + row, mi_c + col),
13908 tw,
13909 th,
13910 &ZERO_RESIDUAL[..tw * th],
13911 );
13912 }
13913 }
13914 luma_tx_type = TxType::DctDct;
13915 luma_grid = Grid::Zero(side * side);
13916 u_grid = Grid::Zero(cside * cside);
13917 v_grid = Grid::Zero(cside * cside);
13918 } else {
13919 match leaves.as_ref() {
13920 None => {
13921 // One whole-block rectangular transform unit.
13922 // lane-av1422mi24: at ss (1,0) the chroma above span is
13923 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
13924 // the per-mi gather counts every chroma column's whole-unit
13925 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
13926 // strip's U dc_sign read ctx 1 where the oracle's cell sum
13927 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
13928 // chroma planes take
13929 // [`Neighbours::around_mi_422_chroma`]'s every-second
13930 // above-cell sampling, like every other 4:2:2 chroma gather.
13931 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13932 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13933 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13934 around[1] = c[1];
13935 around[2] = c[2];
13936 }
13937 let (grid, tx_type) = read_inter_plane_rect(
13938 dec,
13939 cdfs,
13940 rect_inter_luma_set(bw, bh, fctx)?,
13941 (bw, bh),
13942 side,
13943 0,
13944 around[0],
13945 0,
13946 y,
13947 px,
13948 py,
13949 Pred::Inline(&pred_y, side),
13950 None,
13951 None,
13952 fctx,
13953 )?;
13954 luma_tx_type = tx_type;
13955 luma_grid = embed_grid_stride(&grid, bw, bh, side);
13956 let (ug, _) = read_inter_plane_rect(
13957 dec,
13958 cdfs,
13959 rect_inter_chroma_set(cw, ch)?,
13960 (cw, ch),
13961 cside,
13962 1,
13963 around[1],
13964 0,
13965 u,
13966 cpx,
13967 cpy,
13968 Pred::Inline(&pred_u, cside),
13969 Some(luma_tx_type),
13970 None,
13971 fctx,
13972 )?;
13973 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13974 let (vg, _) = read_inter_plane_rect(
13975 dec,
13976 cdfs,
13977 rect_inter_chroma_set(cw, ch)?,
13978 (cw, ch),
13979 cside,
13980 2,
13981 around[2],
13982 0,
13983 v,
13984 cpx,
13985 cpy,
13986 Pred::Inline(&pred_v, cside),
13987 Some(luma_tx_type),
13988 None,
13989 fctx,
13990 )?;
13991 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13992 }
13993 Some(leaves) => {
13994 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
13995 // the split override to LUMA only, per leaf -- the step the
13996 // proven inter var-tx path applies right after its own residual
13997 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
13998 // leaf's own transform edges are never filtered.
13999 for &(row, col, tw, th) in leaves.iter() {
14000 neighbours.fill_lf_grid_leaf_luma(
14001 (mi_r + row, mi_c + col),
14002 tw / MI,
14003 th / MI,
14004 tw as u8,
14005 th as u8,
14006 );
14007 }
14008 // One residual per transform unit, in the order the tree coded
14009 // them; each unit reads its own neighbour-magnitude context off
14010 // the units already decoded before it, and every unit adds onto
14011 // its own window of the block's single prediction.
14012 let mut first_tx_type = TxType::DctDct;
14013 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
14014 let tu_mi = (mi_r + row, mi_c + col);
14015 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14016 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14017 let (tu_grid, tu_tx_type) = if tw == th {
14018 let scan = default_scan(tw.min(32));
14019 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14020 read_inter_plane(
14021 dec,
14022 cdfs,
14023 inter_txbset_for(tw, reduced),
14024 scan,
14025 0,
14026 neighbours.around_mi(tu_mi, tw)[0],
14027 0,
14028 y,
14029 tu_px,
14030 tu_py,
14031 tw,
14032 base_q_idx,
14033 tu_pred,
14034 None,
14035 Some(tu_skip_ctx),
14036 fctx,
14037 )?
14038 } else {
14039 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
14040 read_inter_plane_rect(
14041 dec,
14042 cdfs,
14043 rect_inter_luma_set(tw, th, fctx)?,
14044 (tw, th),
14045 side,
14046 0,
14047 neighbours.around_mi_rect(tu_mi, tw, th)[0],
14048 0,
14049 y,
14050 tu_px,
14051 tu_py,
14052 tu_pred,
14053 None,
14054 Some(tu_skip_ctx),
14055 fctx,
14056 )?
14057 };
14058 if idx == 0 {
14059 first_tx_type = tu_tx_type;
14060 }
14061 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14062 }
14063 // `av1_get_tx_type`'s chroma lookup lands on the colocated
14064 // LUMA unit, which for a split block is the top-left one.
14065 luma_tx_type = first_tx_type;
14066 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
14067 // `None` arm above -- the per-mi rect gather double-counts
14068 // each chroma column's whole-unit dc sign at ss (1,0).
14069 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14070 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14071 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14072 around[1] = c[1];
14073 around[2] = c[2];
14074 }
14075 if lossless(fctx) {
14076 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
14077 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
14078 // lossless block before it looks at a tree, `read_tx_mode`
14079 // already forced `ONLY_4X4` for the frame, and
14080 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
14081 // -- so this block's chroma plane block is a
14082 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
14083 // (`decode_token_recon_block`: every U unit, then every V
14084 // unit), not the single rect unit the two
14085 // `read_inter_plane_rect` calls below read. That single
14086 // 8x4 unit is what reached the lossless WHT with the wrong
14087 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
14088 // replaced). Same helper, same walk, as the inter 8x8 and
14089 // 128 paths.
14090 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
14091 let mut uo = vec![0i32; cside * cside];
14092 let mut vo = vec![0i32; cside * cside];
14093 read_inter_chroma_lossless(
14094 dec,
14095 cdfs,
14096 neighbours,
14097 u,
14098 v,
14099 Pred::Inline(&pred_u, cside),
14100 Pred::Inline(&pred_v, cside),
14101 (mi_r, mi_c),
14102 (cpx, cpy),
14103 (0, 0),
14104 (cw, ch),
14105 (cw, ch),
14106 cside,
14107 0,
14108 base_q_idx,
14109 &mut uo,
14110 &mut vo,
14111 fctx,
14112 )?;
14113 // The per-unit walk stamped every unit's own coefficient
14114 // context, but the whole-block `record_split_luma_rect_mi`
14115 // in the tail rewrites every chroma cell with ONE composed
14116 // state, which drops the per-unit DC signs and levels (class
14117 // `override-slot-on-one-arm` -- the same one
14118 // `decode_rect_split`'s `ll_chroma_units` replay exists
14119 // for). The grids are kept here and replayed AFTER that
14120 // record, from the same 4x4 slices, so the same states.
14121 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
14122 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
14123 ll_chroma = Some((uo, vo));
14124 luma_grid = Grid::Zero(side * side);
14125 } else {
14126 let (ug, _) = read_inter_plane_rect(
14127 dec,
14128 cdfs,
14129 rect_inter_chroma_set(cw, ch)?,
14130 (cw, ch),
14131 cside,
14132 1,
14133 around[1],
14134 0,
14135 u,
14136 cpx,
14137 cpy,
14138 Pred::Inline(&pred_u, cside),
14139 Some(luma_tx_type),
14140 None,
14141 fctx,
14142 )?;
14143 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14144 let (vg, _) = read_inter_plane_rect(
14145 dec,
14146 cdfs,
14147 rect_inter_chroma_set(cw, ch)?,
14148 (cw, ch),
14149 cside,
14150 2,
14151 around[2],
14152 0,
14153 v,
14154 cpx,
14155 cpy,
14156 Pred::Inline(&pred_v, cside),
14157 Some(luma_tx_type),
14158 None,
14159 fctx,
14160 )?;
14161 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14162 luma_grid = Grid::Zero(side * side);
14163 }
14164 }
14165 }
14166 }
14167 let _ = luma_tx_type;
14168 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
14169 // next block reads a neighbour mode, its own block size in both `TXFM`
14170 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
14171 // state (a stale entry would feed the next block's colour cache), and its
14172 // DV into the intrabc mi grid the next block's DV predictor reads.
14173 if leaves.is_some() {
14174 neighbours.record_split_luma_rect_mi(
14175 (mi_r, mi_c),
14176 bw,
14177 bh,
14178 DC_PRED,
14179 DC_PRED,
14180 [&u_grid, &v_grid],
14181 );
14182 } else {
14183 neighbours.record_rect_mi(
14184 (mi_r, mi_c),
14185 bw,
14186 bh,
14187 DC_PRED,
14188 DC_PRED,
14189 &[&luma_grid, &u_grid, &v_grid],
14190 );
14191 }
14192 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
14193 // the whole-block record above, so the NEXT block reads the per-unit DC
14194 // signs and levels libaom's plane-major walk left behind instead of one
14195 // composed state for the whole plane block.
14196 if let Some((uo, vo)) = ll_chroma {
14197 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
14198 for ur in 0..ch / 4 {
14199 for uc in 0..cw / 4 {
14200 let mut unit = Vec::with_capacity(16);
14201 for r in 0..4 {
14202 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
14203 }
14204 neighbours.record_mi_chroma(
14205 // lane-av1lm444loss-corr: the MI STEP between chroma
14206 // units is that same footprint expressed in luma mi
14207 // cells, `(4 << ss) / MI` -- which is exactly what
14208 // `decode_inter_block`'s reference `mu_chroma_units`
14209 // construction writes (decode.rs:43688,
14210 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
14211 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
14212 // this replaces is 4:2:0-only arithmetic that happens
14213 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
14214 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
14215 // SAME value, so 4:2:0 is unchanged by construction.
14216 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
14217 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
14218 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
14219 // The step therefore lands every replayed unit at 4x
14220 // its own mi row/column on a 4:4:4 lossless frame, and
14221 // the whole block's per-unit states are stamped over
14222 // cells that belong to other blocks (or to nothing).
14223 (
14224 mi_r + ur * ((4 << ss_y(fctx)) / MI),
14225 mi_c + uc * ((4 << ss_x(fctx)) / MI),
14226 ),
14227 4 << ss_x(fctx),
14228 4 << ss_y(fctx),
14229 plane_idx,
14230 &Grid::Own(unit),
14231 );
14232 }
14233 }
14234 }
14235 }
14236 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14237 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14238 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14239 neighbours.fill_lf_grid_rect(
14240 (mi_r, mi_c),
14241 bw / MI,
14242 bh / MI,
14243 bw.min(64) as u8,
14244 bh.min(64) as u8,
14245 0,
14246 fctx,
14247 );
14248 record_intrabc_mi_rect(
14249 mi_r,
14250 mi_c,
14251 bw / MI,
14252 bh / MI,
14253 Some((dv_row, dv_col)),
14254 neighbours,
14255 fctx,
14256 );
14257 Ok(())
14258}
14259
14260/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
14261/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
14262/// `decode_block_128rect` refused by name before this port. libaom decodes
14263/// such a block through the INTER machinery (an intrabc block
14264/// `is_inter_block`): `predict_inter_block` copies the whole block from this
14265/// frame's own reconstruction at the integer block vector once, then
14266/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
14267/// per chunk every plane, luma units at the block's own resolved transform
14268/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
14269/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
14270/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
14271/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
14272/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14273/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14274#[allow(clippy::too_many_arguments)]
14275fn decode_intrabc_128rect(
14276 dec: &mut SymbolDecoder,
14277 cdfs: &mut Cdfs,
14278 neighbours: &mut Neighbours,
14279 (mi_r, mi_c): (usize, usize),
14280 (bw, bh): (usize, usize),
14281 skip: bool,
14282 (dv_row, dv_col): (i32, i32),
14283 y: &mut PlaneBuf<'static>,
14284 u: &mut PlaneBuf<'static>,
14285 v: &mut PlaneBuf<'static>,
14286 base_q_idx: u8,
14287 fctx: &crate::decode::FrameCtx,
14288) -> Result<()> {
14289 hit!(INTRABC_128RECT_HITS);
14290 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14291 let (rng, _) = dec.debug_state();
14292 eprintln!(
14293 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14294 );
14295 }
14296 let (px, py) = (mi_c * MI, mi_r * MI);
14297 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14298 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14299 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14300 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14301 // `/2` origin and extent made the prediction window half as tall as
14302 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14303 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14304 // `bw / 2, bh / 2` line-for-line.
14305 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14306 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14307 // The square strides the proven INTER path lays its residual grids,
14308 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14309 // note): 128/64 here.
14310 let side = bw.max(bh);
14311 let cside = cw.max(ch);
14312 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14313 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14314 let mi_cols = 2 * y.true_width.div_ceil(8);
14315 let mi_rows = 2 * y.true_height.div_ceil(8);
14316 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14317 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14318 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14319 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14320 // arms (lane-sb128c r7).
14321 let leaves = read_block_tx_size_rect(
14322 dec,
14323 cdfs,
14324 neighbours,
14325 (mi_r, mi_c),
14326 (bw, bh),
14327 (mi_cols, mi_rows),
14328 skip,
14329 fctx,
14330 )?;
14331 // Whole-block prediction, once, before any coefficient is read
14332 // (`predict_inter_block`); the source is this frame's own
14333 // reconstruction, including the writes this superblock has queued.
14334 flush_recon(fctx, y, u, v);
14335 let mut pred_y_dense = vec![0u16; bw * bh];
14336 mc::predict_with_filter(
14337 &y.data,
14338 y.width,
14339 y.true_width,
14340 y.true_height,
14341 mv_to_q4(px, dv_col, 0),
14342 mv_to_q4(py, dv_row, 0),
14343 bw,
14344 bh,
14345 mc::InterpFilterKind::Bilinear,
14346 &mut pred_y_dense,
14347 fctx,
14348 );
14349 let mut pred_y = vec![0u16; side * side];
14350 for row in 0..bh {
14351 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14352 }
14353 let mut pred_u_dense = vec![0u16; cw * ch];
14354 mc::predict_with_filter(
14355 &u.data,
14356 u.width,
14357 u.true_width,
14358 u.true_height,
14359 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14360 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14361 cw,
14362 ch,
14363 mc::InterpFilterKind::Bilinear,
14364 &mut pred_u_dense,
14365 fctx,
14366 );
14367 let mut pred_u = vec![0u16; cside * cside];
14368 for row in 0..ch {
14369 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14370 }
14371 let mut pred_v_dense = vec![0u16; cw * ch];
14372 mc::predict_with_filter(
14373 &v.data,
14374 v.width,
14375 v.true_width,
14376 v.true_height,
14377 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14378 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14379 cw,
14380 ch,
14381 mc::InterpFilterKind::Bilinear,
14382 &mut pred_v_dense,
14383 fctx,
14384 );
14385 let mut pred_v = vec![0u16; cside * cside];
14386 for row in 0..ch {
14387 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14388 }
14389 let (luma_grid, u_grid, v_grid);
14390 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
14391 // contexts per transform unit -- the replay after this fn's end-of-block
14392 // record restores them (the record itself re-stamps both planes with ONE
14393 // composed state, class `override-slot-on-one-arm`).
14394 let mut mu_chroma = false;
14395 if skip {
14396 // No residual syntax at all: the prediction IS the block. Strides are
14397 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
14398 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
14399 push_mc_rect(
14400 0,
14401 px,
14402 py,
14403 side,
14404 bw,
14405 bh,
14406 Pred::Inline(&pred_y, side),
14407 &ZERO_RESIDUAL[..side * side],
14408 fctx,
14409 );
14410 push_mc_rect(
14411 1,
14412 cpx,
14413 cpy,
14414 cside,
14415 cw,
14416 ch,
14417 Pred::Inline(&pred_u, cside),
14418 &ZERO_RESIDUAL[..cside * cside],
14419 fctx,
14420 );
14421 push_mc_rect(
14422 2,
14423 cpx,
14424 cpy,
14425 cside,
14426 cw,
14427 ch,
14428 Pred::Inline(&pred_v, cside),
14429 &ZERO_RESIDUAL[..cside * cside],
14430 fctx,
14431 );
14432 if let Some(ls) = leaves.as_ref() {
14433 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
14434 // grid before it looks at `skip`; the skipped block still zeroes
14435 // its entropy-band footprint over every unit (libaom
14436 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
14437 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
14438 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14439 for &(row, col, tw, th) in ls {
14440 neighbours.record_mi_luma_rect(
14441 (mi_r + row, mi_c + col),
14442 tw,
14443 th,
14444 &ZERO_RESIDUAL[..tw * th],
14445 );
14446 }
14447 }
14448 luma_grid = Grid::Zero(side * side);
14449 u_grid = Grid::Zero(cside * cside);
14450 v_grid = Grid::Zero(cside * cside);
14451 } else {
14452 let leaves = leaves
14453 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
14454 // libaom `get_transform_size`'s split override applies to LUMA only,
14455 // per leaf -- each unit's own transform edges get filtered
14456 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
14457 for &(row, col, tw, th) in leaves.iter() {
14458 neighbours.fill_lf_grid_leaf_luma(
14459 (mi_r + row, mi_c + col),
14460 tw / MI,
14461 th / MI,
14462 tw as u8,
14463 th as u8,
14464 );
14465 }
14466 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14467 let mut u_units: Vec<i32> = Vec::new();
14468 let mut v_units: Vec<i32> = Vec::new();
14469 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
14470 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
14471 // top-left sample is outside the frame codes nothing.
14472 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
14473 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
14474 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
14475 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
14476 for (pos, &idx) in order.iter().enumerate() {
14477 let (row, col, tw, th) = leaves[idx];
14478 debug_assert_eq!(
14479 tw, th,
14480 "a square TX_64X64 tree root only yields square leaves"
14481 );
14482 let tu_mi = (mi_r + row, mi_c + col);
14483 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14484 if tu_px >= y.true_width || tu_py >= y.true_height {
14485 continue;
14486 }
14487 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14488 let scan = default_scan(tw.min(32));
14489 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14490 let (tu_grid, tu_tx_type) = read_inter_plane(
14491 dec,
14492 cdfs,
14493 inter_txbset_for(tw, reduced),
14494 &scan,
14495 0,
14496 neighbours.around_mi(tu_mi, tw)[0],
14497 0,
14498 y,
14499 tu_px,
14500 tu_py,
14501 tw,
14502 base_q_idx,
14503 tu_pred,
14504 None,
14505 Some(tu_skip_ctx),
14506 fctx,
14507 )?;
14508 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
14509 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14510 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
14511 // mu chunk before the next one starts: once this chunk's leaves
14512 // are done, its chroma is read immediately (the inter 128 path's
14513 // interleave).
14514 let chunk = (row / 16, col / 16);
14515 let done = pos + 1 == order.len()
14516 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
14517 if done {
14518 let (cr, cc) = chunk;
14519 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
14520 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
14521 // within the chunk, plane-major inside the chunk.
14522 let cu_tx = 32usize;
14523 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
14524 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
14525 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
14526 // plane block is 32x64 there), four at 4:4:4. The old
14527 // `chunk_chroma = cside * 64 / side` walked a
14528 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
14529 // axes: at 4:2:2 it read HALF the chroma units of a chunk
14530 // (one 32x32 at the chunk's top-left instead of two), left
14531 // the chunk's lower 32 chroma rows with no residual at all,
14532 // and stamped every unit's entropy context over a 16x16-mi
14533 // luma span instead of 16x8. The same defect and the same
14534 // per-axis repair as `decode_inter_block`'s
14535 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
14536 // witnessed on `422_sb128_3f.obu`).
14537 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14538 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14539 // The unit's own footprint on the LUMA mi grid, per axis:
14540 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
14541 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
14542 // `record_mi_chroma` stamp exactly the unit's own cells.
14543 let unit_luma_w = cu_tx << ss_x(fctx);
14544 let unit_luma_h = cu_tx << ss_y(fctx);
14545 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
14546 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
14547 });
14548 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
14549 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
14550 let units_x = chunk_w_mi / (unit_luma_w / MI);
14551 let units_y = chunk_h_mi / (unit_luma_h / MI);
14552 if lossless(fctx) {
14553 // TX_4X4 chroma units over this chunk (lane-lossless2's
14554 // walk, shared with the inter 128 path).
14555 read_inter_chroma_lossless(
14556 dec,
14557 cdfs,
14558 neighbours,
14559 u,
14560 v,
14561 Pred::Inline(&pred_u, cside),
14562 Pred::Inline(&pred_v, cside),
14563 (mi_r, mi_c),
14564 (cpx, cpy),
14565 (cc * chunk_chroma_w, cr * chunk_chroma_h),
14566 (chunk_chroma_w, chunk_chroma_h),
14567 (cw, ch),
14568 cside,
14569 0,
14570 base_q_idx,
14571 &mut u_units,
14572 &mut v_units,
14573 fctx,
14574 )?;
14575 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
14576 // every TX_4X4 unit's own context (`record_mi_chroma`
14577 // inside the walk) -- the end-of-block record below must
14578 // not overwrite them with the composed grid (the inter
14579 // 128 path sets the same flag on this arm).
14580 mu_chroma = true;
14581 continue;
14582 }
14583 let cu_scan = default_scan(cu_tx);
14584 for plane_idx in 1..3 {
14585 let (src, buf) = if plane_idx == 1 {
14586 (Pred::Inline(&pred_u, cside), &mut *u)
14587 } else {
14588 (Pred::Inline(&pred_v, cside), &mut *v)
14589 };
14590 for ur in 0..units_y {
14591 for uc in 0..units_x {
14592 let unit_mi = (
14593 mi_r + cr * 16 + ur * (unit_luma_h / MI),
14594 mi_c + cc * 16 + uc * (unit_luma_w / MI),
14595 );
14596 // Per unit, AFTER the earlier units' stamps: this
14597 // unit's coefficient context must see them.
14598 let cu_around =
14599 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
14600 if crate::envflags::env_flag!("EC_ECDUMP") {
14601 for p in 1..3 {
14602 let ab: Vec<String> = (0..unit_luma_w / MI)
14603 .map(|k| {
14604 format!(
14605 "{:?}/{}",
14606 neighbours.above[unit_mi.1 + k][p].dc,
14607 neighbours.above[unit_mi.1 + k][p].level
14608 )
14609 })
14610 .collect();
14611 let lf: Vec<String> = (0..unit_luma_h / MI)
14612 .map(|k| {
14613 format!(
14614 "{:?}/{}",
14615 neighbours.left[unit_mi.0 + k][p].dc,
14616 neighbours.left[unit_mi.0 + k][p].level
14617 )
14618 })
14619 .collect();
14620 eprintln!(
14621 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
14622 cu_around[p].0,
14623 cu_around[p].1,
14624 cu_around[p].2,
14625 ab.join(","),
14626 lf.join(",")
14627 );
14628 }
14629 }
14630 let (cu_x, cu_y) = (
14631 cpx + cc * chunk_chroma_w + uc * cu_tx,
14632 cpy + cr * chunk_chroma_h + ur * cu_tx,
14633 );
14634 // `av1_get_tx_type` (blockd.h:1291): an inter
14635 // block's chroma unit never codes a tx_type; it
14636 // inherits the coded type of the luma leaf
14637 // covering its own quadrant (all of this chunk's
14638 // leaves are read by now).
14639 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
14640 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
14641 // The prediction window is the block's own square
14642 // `cside` buffer with the unit's true per-axis
14643 // position inside it.
14644 let cu_pred = src.offset(
14645 (cr * chunk_chroma_h + ur * cu_tx) * cside
14646 + cc * chunk_chroma_w
14647 + uc * cu_tx,
14648 );
14649 let cu_grid = read_inter_plane(
14650 dec,
14651 cdfs,
14652 TxbSet::Chroma32,
14653 &cu_scan,
14654 plane_idx,
14655 cu_around[plane_idx],
14656 0,
14657 buf,
14658 cu_x,
14659 cu_y,
14660 cu_tx,
14661 base_q_idx,
14662 cu_pred,
14663 Some(covering.unwrap_or(TxType::DctDct)),
14664 Some(3),
14665 fctx,
14666 )?
14667 .0;
14668 // Immediately, so the NEXT unit reads this one's
14669 // coefficient context.
14670 neighbours.record_mi_chroma(
14671 unit_mi,
14672 unit_luma_w,
14673 unit_luma_h,
14674 plane_idx,
14675 &cu_grid,
14676 );
14677 if crate::envflags::env_flag!("EC_ECDUMP") {
14678 let st = crate::decode::neighbour_state(&cu_grid);
14679 eprintln!(
14680 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
14681 st.dc, st.level
14682 );
14683 }
14684 hit!(CHROMA_SPLIT_TX_HITS);
14685 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
14686 // lane-av1-ibcrect: per-unit chroma context -- the
14687 // end-of-block record's composed-grid re-stamp
14688 // must not stand (replayed below).
14689 mu_chroma = true;
14690 let dst = mu_units(
14691 if plane_idx == 1 {
14692 &mut u_units
14693 } else {
14694 &mut v_units
14695 },
14696 cside * cside,
14697 );
14698 for rr in 0..cu_tx {
14699 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
14700 + cc * chunk_chroma_w
14701 + uc * cu_tx;
14702 dst[start..start + cu_tx]
14703 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
14704 }
14705 }
14706 }
14707 }
14708 }
14709 }
14710 // The block-level luma bands were recorded per leaf above; the
14711 // composed chroma grids carry every unit in place.
14712 luma_grid = Grid::Zero(side * side);
14713 u_grid = if u_units.is_empty() {
14714 Grid::Zero(cside * cside)
14715 } else {
14716 Grid::Own(std::mem::take(&mut u_units))
14717 };
14718 v_grid = if v_units.is_empty() {
14719 Grid::Zero(cside * cside)
14720 } else {
14721 Grid::Own(std::mem::take(&mut v_units))
14722 };
14723 }
14724 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
14725 // neighbour reads a mode, zeroed palette state, the skip grid, the
14726 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
14727 // and the DV into the intrabc mi grid.
14728 if skip {
14729 neighbours.record_rect_mi(
14730 (mi_r, mi_c),
14731 bw,
14732 bh,
14733 DC_PRED,
14734 DC_PRED,
14735 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
14736 );
14737 } else {
14738 neighbours.record_split_luma_rect_mi(
14739 (mi_r, mi_c),
14740 bw,
14741 bh,
14742 DC_PRED,
14743 DC_PRED,
14744 [&u_grid[..], &v_grid[..]],
14745 );
14746 }
14747 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
14748 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
14749 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
14750 // both planes with ONE `neighbour_state(composed_grid)` over the whole
14751 // span -- level = the SUM of every unit's levels and dc = the top-left
14752 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
14753 // inter block: the next block read a stale `dc_sign_ctx` one row low).
14754 // Measured on this shape: the 128x64 block at mi(64,32) of the
14755 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
14756 // into chunk-0's cells and the block below read `txb_skip` off the sum.
14757 // Replay every coded unit's own state after the record, in mu-chunk order
14758 // so a later unit still wins over an earlier one on the shared seam cells
14759 // (the composed construction `mu_chroma_units` uses, transcribed here).
14760 if mu_chroma {
14761 let cu = if lossless(fctx) { 4usize } else { 32usize };
14762 // The unit's own footprint on the LUMA mi grid (the chroma context
14763 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
14764 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
14765 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
14766 let unit_luma_w = cu << ss_x(fctx);
14767 let unit_luma_h = cu << ss_y(fctx);
14768 // A 64x64 mu chunk's chroma plane block is PER-AXIS
14769 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
14770 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
14771 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
14772 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14773 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14774 if lossless(fctx) {
14775 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
14776 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
14777 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
14778 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
14779 // enumerate it, and this arm re-stamps only the 4x4 at each
14780 // chunk's top-left with a 2x2-mi span. The twin
14781 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
14782 // instead raster-walks the WHOLE plane block at `cu` steps, and
14783 // that is the correct shape here too. It is left as-is on purpose:
14784 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
14785 // it would change 4:2:0 LOSSLESS output -- which this lane's
14786 // byte-identity requirement forbids doing on an unverified
14787 // reconstruction. Measured unreachability: this arm is entered
14788 // 0 times by the whole `lossless` and `intrabc` gate battery
14789 // (temporary env-gated counter in the arm). Unblock: one
14790 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
14791 // intrabc strip (`--lossless=1 --sb-size=128
14792 // --min-partition-size=64 --enable-rect-partitions=1
14793 // --enable-intrabc=1` over near-match screen content).
14794 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14795 for cr in 0..rows {
14796 for cc in 0..cols {
14797 let unit_mi = (
14798 mi_r + cr * (unit_luma_h / MI),
14799 mi_c + cc * (unit_luma_w / MI),
14800 );
14801 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14802 let mut unit = Vec::with_capacity(cu * cu);
14803 for rr in 0..cu {
14804 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
14805 unit.extend_from_slice(&grid[start..start + cu]);
14806 }
14807 neighbours.record_mi_chroma(
14808 unit_mi,
14809 unit_luma_w,
14810 unit_luma_h,
14811 plane_idx,
14812 &unit,
14813 );
14814 }
14815 }
14816 }
14817 } else {
14818 // The chunk count on each axis, then EVERY unit inside each
14819 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
14820 // span, and its own quadrant of the composed plane grid -- the
14821 // twin's loop (decode_inter_block's `mu_chroma_units`,
14822 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
14823 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
14824 // the grid PER UNIT, which only agrees when a chunk holds exactly
14825 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
14826 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
14827 // 2 or 4, so the old body reached only the first of the stacked
14828 // units and the rest of the chunk kept the composed-grid smearing
14829 // this replay exists to undo. A unit the frame edge clipped codes
14830 // nothing and carries no composed samples beyond the clip, so it
14831 // replays as the zero state exactly like libaom's uncoded unit.
14832 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
14833 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14834 for cr in 0..rows {
14835 for cc in 0..cols {
14836 for kr in 0..ur {
14837 for kc in 0..uc {
14838 let unit_mi = (
14839 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
14840 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
14841 );
14842 let (cy, cx) =
14843 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
14844 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14845 let mut unit = Vec::with_capacity(cu * cu);
14846 for rr in 0..cu {
14847 let start = (cy + rr) * cside + cx;
14848 unit.extend_from_slice(&grid[start..start + cu]);
14849 }
14850 neighbours.record_mi_chroma(
14851 unit_mi,
14852 unit_luma_w,
14853 unit_luma_h,
14854 plane_idx,
14855 &unit,
14856 );
14857 }
14858 }
14859 }
14860 }
14861 }
14862 }
14863 }
14864 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14865 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14866 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14867 neighbours.fill_lf_grid_rect(
14868 (mi_r, mi_c),
14869 bw / MI,
14870 bh / MI,
14871 bw.min(64) as u8,
14872 bh.min(64) as u8,
14873 0,
14874 fctx,
14875 );
14876 record_intrabc_mi_rect(
14877 mi_r,
14878 mi_c,
14879 bw / MI,
14880 bh / MI,
14881 Some((dv_row, dv_col)),
14882 neighbours,
14883 fctx,
14884 );
14885 Ok(())
14886}
14887
14888/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
14889/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
14890/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
14891/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
14892/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
14893/// has no rectangular-transform coefficient reader, and a chroma plane here
14894/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
14895/// with no depth-based square-tiling escape the way luma's own resolved
14896/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
14897/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
14898#[allow(clippy::too_many_arguments)]
14899fn decode_block_rect(
14900 dec: &mut SymbolDecoder,
14901 cdfs: &mut Cdfs,
14902 neighbours: &mut Neighbours,
14903 at: (usize, usize),
14904 bw: usize,
14905 bh: usize,
14906 y: &mut PlaneBuf<'static>,
14907 u: &mut PlaneBuf<'static>,
14908 v: &mut PlaneBuf<'static>,
14909 enable_filter_intra: bool,
14910 allow_screen_content_tools: bool,
14911 base_q_idx: u8,
14912 tx_select: bool,
14913 reduced_tx_set: bool,
14914 fctx: &crate::decode::FrameCtx,
14915) -> Result<()> {
14916 let (r, c) = at;
14917 let (px, py) = (c * SUB, r * SUB);
14918 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14919 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14920 let palette_uv_cache = neighbours.palette_uv_cache(at);
14921 let (
14922 skip,
14923 mode,
14924 angle_delta_y,
14925 uv_mode,
14926 angle_delta_uv,
14927 alpha,
14928 filter_intra,
14929 palette_y,
14930 palette_uv,
14931 intrabc,
14932 ) = read_intra_mode_rect(
14933 dec,
14934 cdfs,
14935 nb_above_mode,
14936 nb_left_mode,
14937 true,
14938 true,
14939 bw,
14940 bh,
14941 enable_filter_intra,
14942 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14943 allow_screen_content_tools,
14944 Some((palette_ctx, &palette_cache)),
14945 &palette_uv_cache,
14946 r * (SUB / MI),
14947 c * (SUB / MI),
14948 fctx,
14949 )?;
14950
14951 if let Some((dv_row, dv_col)) = intrabc {
14952 return decode_intrabc_rect(
14953 dec,
14954 cdfs,
14955 neighbours,
14956 (r * (SUB / MI), c * (SUB / MI)),
14957 (bw, bh),
14958 skip,
14959 (dv_row, dv_col),
14960 y,
14961 u,
14962 v,
14963 base_q_idx,
14964 fctx,
14965 );
14966 }
14967 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14968 if smooth_neighbor {
14969 hit!(SMOOTH_LUMA_HITS);
14970 }
14971 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
14972 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
14973 // `uv_mode`, not the luma one.
14974 let smooth_neighbor_uv =
14975 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14976 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
14977 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
14978 // rectangle just as happily), so a `use_filter_intra` strip at this level
14979 // predicts instead of refusing. The below-16x16 leaf arm
14980 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
14981 if filter_intra.is_some() {
14982 hit!(FILTER_INTRA_RECT_HITS);
14983 }
14984 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14985 DC_PRED
14986 } else {
14987 uv_mode
14988 };
14989 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14990 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
14991 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
14992 // one did not, so with `--enable-tx-size-search=0` -- which several gate
14993 // recipes use -- the decoder consumed a symbol the encoder never wrote and
14994 // desynced the tile from that point on. That is why both strips of the
14995 // pinned HORZ quadrant were wrong from their very first pixel, and why our
14996 // range after the read equalled the oracle's range for the whole block.
14997 // lane-av1mixloss: the lossless-segment early return
14998 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
14999 // rect block codes no depth symbol here either (class sweep of the sub8
15000 // leaf's fix).
15001 let depth = if tx_select && !lossless(fctx) {
15002 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15003 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15004 // intra-only frame publishes them from every block too
15005 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15006 // 1920x792 128-superblock stream,
15007 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15008 // `tx_size_cat2` row 1 where libaom reads row 2.
15009 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15010 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
15011 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15012 eprintln!(
15013 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
15014 dec.debug_state().0
15015 );
15016 }
15017 d
15018 } else {
15019 0
15020 };
15021 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
15022 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15023 publish_txfm_bands_if_in_inter(
15024 neighbours,
15025 (mi_r, mi_c),
15026 depth_to_tx_wh(bw, bh, depth, fctx),
15027 (bw, bh),
15028 fctx,
15029 );
15030 if depth != 0 || lossless(fctx) {
15031 hit!(TX_DEPTH_HITS);
15032 // lane-rectsplit r1: a split transform is predicted and reconstructed
15033 // per transform unit, each unit taking its edges from the previous
15034 // unit's reconstruction inside this same strip (spec 5.11.36) --
15035 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
15036 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15037 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15038 eprintln!(
15039 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
15040 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
15041 angle_y={angle_delta_y}"
15042 );
15043 }
15044 let modes = RectStripModes {
15045 skip,
15046 mode,
15047 angle_delta_y,
15048 uv_predict_mode,
15049 angle_delta_uv,
15050 alpha,
15051 filter_intra,
15052 smooth_neighbor,
15053 smooth_neighbor_uv,
15054 palette_y: palette_y
15055 .as_ref()
15056 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
15057 palette_uv: palette_uv.as_ref().map(|p| {
15058 (
15059 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15060 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15061 )
15062 }),
15063 };
15064 if palette_y.is_some() || palette_uv.is_some() {
15065 hit!(PALETTE_SPLIT_TX_HITS);
15066 }
15067 decode_rect_split(
15068 dec,
15069 cdfs,
15070 neighbours,
15071 (mi_r, mi_c),
15072 bw,
15073 bh,
15074 tx_w,
15075 tx_h,
15076 &modes,
15077 y,
15078 u,
15079 v,
15080 base_q_idx,
15081 reduced_tx_set,
15082 fctx,
15083 )?;
15084 // This early return skips this fn's own tail, so the palette
15085 // neighbour state has to be stamped HERE too: without it a split-tx
15086 // strip left the above/left palette arrays holding a DEAD block's
15087 // colours, and the next block's colour cache
15088 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
15089 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
15090 // and only those pixels were wrong (lane-palette2 r10).
15091 let (py_size, py_colors) = palette_y
15092 .as_ref()
15093 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15094 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15095 let (puv_size, puv_colors) = palette_uv
15096 .as_ref()
15097 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15098 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15099 hit!(RECT_PARTITION_HITS);
15100 return Ok(());
15101 }
15102 let (tx_w, tx_h) = (bw, bh);
15103 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15104 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15105 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15106 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15107 let (rng, _) = dec.debug_state();
15108 eprintln!(
15109 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
15110 skip={} tx={depth} rng={rng}",
15111 skip as i32
15112 );
15113 }
15114 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
15115 // block's prediction is the reconstructed colour-index map, set fresh
15116 // right before each `reconstruct_rect` call below (lane-palette2 r4).
15117 if let Some(ref pyv) = palette_y {
15118 let buf: Vec<u16> = pyv
15119 .map
15120 .iter()
15121 .map(|&idx| pyv.colors[idx as usize])
15122 .collect();
15123 set_palette_pred(buf, fctx);
15124 }
15125 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15126 (
15127 puv.map
15128 .iter()
15129 .map(|&idx| puv.u_colors[idx as usize])
15130 .collect(),
15131 puv.map
15132 .iter()
15133 .map(|&idx| puv.v_colors[idx as usize])
15134 .collect(),
15135 )
15136 });
15137 if skip {
15138 push_intra_rect(
15139 0,
15140 px,
15141 py,
15142 bw,
15143 bh,
15144 mode,
15145 angle_delta_y,
15146 reach,
15147 &ZERO_RESIDUAL[..bw * bh],
15148 None,
15149 filter_intra,
15150 smooth_neighbor,
15151 fctx,
15152 );
15153 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15154 if let Some((ub, _)) = &palette_uv_bufs {
15155 set_palette_pred(ub.clone(), fctx);
15156 }
15157 push_intra_rect(
15158 1,
15159 cpx,
15160 cpy,
15161 chroma_w,
15162 chroma_h,
15163 uv_predict_mode,
15164 angle_delta_uv,
15165 reach,
15166 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15167 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15168 None,
15169 smooth_neighbor_uv,
15170 fctx,
15171 );
15172 if let Some((_, vb)) = &palette_uv_bufs {
15173 set_palette_pred(vb.clone(), fctx);
15174 }
15175 push_intra_rect(
15176 2,
15177 cpx,
15178 cpy,
15179 chroma_w,
15180 chroma_h,
15181 uv_predict_mode,
15182 angle_delta_uv,
15183 reach,
15184 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15185 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15186 None,
15187 smooth_neighbor_uv,
15188 fctx,
15189 );
15190 neighbours.record_rect(
15191 at,
15192 bw,
15193 bh,
15194 mode,
15195 uv_predict_mode,
15196 &[
15197 &ZERO_RESIDUAL[..bw * bh],
15198 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15199 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15200 ],
15201 );
15202 } else {
15203 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
15204 // reduces both size pairs to their square-up CDF sets
15205 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
15206 // doc comments); the scan order and 2D context tables are the real
15207 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
15208 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
15209 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
15210 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
15211 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
15212 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15213 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15214 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15215 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
15216 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
15217 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
15218 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
15219 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
15220 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
15221 // default follows the >=32 rule below -- the same pairing the
15222 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
15223 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
15224 // is reachable there.
15225 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
15226 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15227 _ => {
15228 return Err(unsupported(
15229 "a rectangular chroma transform whose size has no coefficient table",
15230 ));
15231 }
15232 };
15233 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
15234 TxType::DctDct
15235 } else {
15236 default_intra_tx_type(uv_predict_mode as u8)
15237 };
15238 // lane-rectwire r3: real coefficients desync a pixel-exact gate
15239 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
15240 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
15241 // pixel (not a subtle context-table off-by-one), while the sibling
15242 // non-rect quadrants of the same frame match. Range-ladder bisection
15243 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
15244 // but the intra key-frame path has no traced symbol between the
15245 // partition read and the first coefficient block (mode/skip/tx_depth
15246 // reads are all untraced in libaom's decodeframe.c intra path, unlike
15247 // the inter EC_TRACE_MODE this round added), so a same-length range
15248 // comparison wasn't reachable within budget -- see
15249 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
15250 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
15251 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
15252 // libaom and match). lane-rectwire r4: range-ladder against the
15253 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
15254 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
15255 // both confirmed in sync -- rng=58692 on both sides right after
15256 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
15257 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
15258 // immediately after: ours moves rng 58692 -> 43570, which cannot be
15259 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
15260 // its own tx_size read) unless oracle's tx symbol is a near-certainty
15261 // CDF that barely narrows the range -- i.e. this decoder's
15262 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
15263 // a 32x16/16x32 strip is the first diverging symbol, not the
15264 // coefficient-context math r3 already cleared. Not confirmed byte-
15265 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
15266 // `read_tx_size`'s own rng, not attempted this round -- budget), so
15267 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
15268 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
15269 // it unconditionally where both square paths gate on `tx_select`. With
15270 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
15271 // decoder consumed one that was never there.
15272 {
15273 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15274 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15275 // strip's chroma is a square (side/2, side) block whose above cells
15276 // spread over `side` LUMA mi columns, so the per-mi rect gather
15277 // double-counts every chroma column's whole-unit dc sign. Measured on
15278 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15279 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15280 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15281 // 45260 whose pre-state, bit position and symbol all match and only
15282 // the CDF row differs, and the first divergence in the EC_SYMR
15283 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15284 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15285 let mut around = neighbours.around_rect(at, bw, bh);
15286 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15287 let c2 =
15288 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15289 around[1] = c2[1];
15290 around[2] = c2[2];
15291 }
15292 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15293 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15294 dec,
15295 &mut luma_coding,
15296 luma_scan,
15297 bw,
15298 bh,
15299 0,
15300 dc_sign_ctx(around[0].2),
15301 TxType::DctDct,
15302 0,
15303 )?;
15304 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15305 let (rng, _) = dec.debug_state();
15306 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15307 }
15308 let luma_residual = dequant_and_inverse_typed_wh(
15309 &luma_levels,
15310 bw,
15311 bh,
15312 crate::decode::bit_depth(fctx),
15313 block_q_idx(fctx),
15314 plane_q_delta(0, fctx).0,
15315 plane_q_delta(0, fctx).1,
15316 luma_tx_type,
15317 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15318 );
15319 push_intra_rect(
15320 0,
15321 px,
15322 py,
15323 bw,
15324 bh,
15325 mode,
15326 angle_delta_y,
15327 reach,
15328 &luma_residual,
15329 None,
15330 filter_intra,
15331 smooth_neighbor,
15332 fctx,
15333 );
15334 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15335 if let Some((ub, _)) = &palette_uv_bufs {
15336 set_palette_pred(ub.clone(), fctx);
15337 }
15338 let u_default_tx = chroma_default_tx;
15339 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15340 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15341 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15342 dec,
15343 &mut u_coding,
15344 chroma_scan,
15345 chroma_w,
15346 chroma_h,
15347 u_skip_ctx,
15348 dc_sign_ctx(around[1].2),
15349 u_default_tx,
15350 fctx,
15351 1,
15352 )?;
15353 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15354 let (rng, _) = dec.debug_state();
15355 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15356 }
15357 let u_residual = dequant_and_inverse_typed_wh(
15358 &u_levels,
15359 chroma_w,
15360 chroma_h,
15361 crate::decode::bit_depth(fctx),
15362 block_q_idx(fctx),
15363 plane_q_delta(1, fctx).0,
15364 plane_q_delta(1, fctx).1,
15365 u_tx_type,
15366 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15367 );
15368 push_intra_rect(
15369 1,
15370 cpx,
15371 cpy,
15372 chroma_w,
15373 chroma_h,
15374 uv_predict_mode,
15375 angle_delta_uv,
15376 reach,
15377 &u_residual,
15378 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15379 None,
15380 smooth_neighbor_uv,
15381 fctx,
15382 );
15383 if let Some((_, vb)) = &palette_uv_bufs {
15384 set_palette_pred(vb.clone(), fctx);
15385 }
15386 let v_default_tx = chroma_default_tx;
15387 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15388 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
15389 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
15390 dec,
15391 &mut v_coding,
15392 chroma_scan,
15393 chroma_w,
15394 chroma_h,
15395 v_skip_ctx,
15396 dc_sign_ctx(around[2].2),
15397 v_default_tx,
15398 fctx,
15399 2,
15400 )?;
15401 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15402 let (rng, _) = dec.debug_state();
15403 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15404 }
15405 let v_residual = dequant_and_inverse_typed_wh(
15406 &v_levels,
15407 chroma_w,
15408 chroma_h,
15409 crate::decode::bit_depth(fctx),
15410 block_q_idx(fctx),
15411 plane_q_delta(2, fctx).0,
15412 plane_q_delta(2, fctx).1,
15413 v_tx_type,
15414 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15415 );
15416 push_intra_rect(
15417 2,
15418 cpx,
15419 cpy,
15420 chroma_w,
15421 chroma_h,
15422 uv_predict_mode,
15423 angle_delta_uv,
15424 reach,
15425 &v_residual,
15426 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15427 None,
15428 smooth_neighbor_uv,
15429 fctx,
15430 );
15431 neighbours.record_rect(
15432 at,
15433 bw,
15434 bh,
15435 mode,
15436 uv_predict_mode,
15437 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15438 );
15439 hit!(RECT_COEFF_HITS);
15440 }
15441 }
15442 let (py_size, py_colors) = palette_y
15443 .as_ref()
15444 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15445 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15446 let (puv_size, puv_colors) = palette_uv
15447 .as_ref()
15448 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15449 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15450 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15451 neighbours.fill_lf_grid_rect(
15452 (mi_r, mi_c),
15453 bw / MI,
15454 bh / MI,
15455 tx_w as u8,
15456 tx_h as u8,
15457 0,
15458 fctx,
15459 );
15460 hit!(RECT_PARTITION_HITS);
15461 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15462 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
15463 }
15464 Ok(())
15465}
15466
15467/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
15468/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
15469/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
15470/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
15471/// the second strip of a HORZ/VERT split sits offset by half the 16x16
15472/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
15473/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
15474/// previous strip is directly above (same column, `mi_h` rows up) or
15475/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
15476/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
15477/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
15478/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
15479/// this strip's real position, never the coarse `record_rect` (which the
15480/// caller uses once, after both strips, exactly like the `VERT_B` arm next
15481/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
15482/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
15483/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
15484/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
15485/// half-width, unhalved height), the two size classes one level
15486/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
15487#[allow(clippy::too_many_arguments)]
15488fn decode_leaf_rect(
15489 dec: &mut SymbolDecoder,
15490 cdfs: &mut Cdfs,
15491 neighbours: &mut Neighbours,
15492 outer_at: (usize, usize),
15493 leaf_mi: (usize, usize),
15494 bw: usize,
15495 bh: usize,
15496 prev_leaf: Option<((usize, usize), usize)>,
15497 y: &mut PlaneBuf<'static>,
15498 u: &mut PlaneBuf<'static>,
15499 v: &mut PlaneBuf<'static>,
15500 enable_filter_intra: bool,
15501 allow_screen_content_tools: bool,
15502 base_q_idx: u8,
15503 tx_select: bool,
15504 reduced_tx_set: bool,
15505 fctx: &crate::decode::FrameCtx,
15506) -> Result<usize> {
15507 let _ = base_q_idx;
15508 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15509 eprintln!(
15510 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
15511 dec.debug_state().0
15512 );
15513 }
15514 let (r, c) = outer_at;
15515 let mut above_mode = neighbours.above_mode[c];
15516 let mut left_mode = neighbours.left_mode[r];
15517 let (mi_w, mi_h) = (bw / MI, bh / MI);
15518 if let Some(((pr, pc), pmode)) = prev_leaf {
15519 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
15520 above_mode = pmode;
15521 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
15522 left_mode = pmode;
15523 }
15524 }
15525 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
15526 // cannot hold the modes a split (or a pair of strips) leaves behind, so
15527 // when the map holds the block at exactly this strip's above/left mi it
15528 // is the neighbour libaom's `above_mi`/`left_mi` reads.
15529 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
15530 // availability-correct -- four 16x8 strips share one coarse 16x16
15531 // `left_mode` cell too, so the fallback must not stand in for an absent
15532 // tile-edge neighbour.
15533 let (above_mode, left_mode) =
15534 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15535 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15536 if smooth_neighbor {
15537 hit!(SMOOTH_LUMA_HITS);
15538 }
15539 // The palette-Y mode CDF row is picked by the neighbours' palette use
15540 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
15541 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
15542 // a palette narrows the wrong interval and desyncs the tile even when the
15543 // decoded bit is the same. The cell is the 16px-SUB cell containing the
15544 // leaf (the palette neighbour arrays have no finer granularity).
15545 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
15546 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
15547 // exclusion and the neighbour palette lookup itself are mi-granular
15548 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
15549 let pal_at = leaf_mi;
15550 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15551 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15552 let (
15553 skip,
15554 mode,
15555 angle_delta_y,
15556 uv_mode,
15557 angle_delta_uv,
15558 alpha,
15559 filter_intra,
15560 palette_y,
15561 palette_uv,
15562 intrabc,
15563 ) = read_intra_mode_rect(
15564 dec,
15565 cdfs,
15566 above_mode,
15567 left_mode,
15568 true,
15569 true,
15570 bw,
15571 bh,
15572 enable_filter_intra,
15573 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15574 allow_screen_content_tools,
15575 Some((palette_ctx, &palette_cache)),
15576 &palette_uv_cache,
15577 leaf_mi.0,
15578 leaf_mi.1,
15579 fctx,
15580 )?;
15581
15582 if let Some((dv_row, dv_col)) = intrabc {
15583 decode_intrabc_rect(
15584 dec,
15585 cdfs,
15586 neighbours,
15587 leaf_mi,
15588 (bw, bh),
15589 skip,
15590 (dv_row, dv_col),
15591 y,
15592 u,
15593 v,
15594 base_q_idx,
15595 fctx,
15596 )?;
15597 return Ok(DC_PRED);
15598 }
15599 // lane-kf900 r4: palette prediction on this shape, the same colour-index
15600 // map -> base colours buffer [`decode_block_rect`] hands each
15601 // `reconstruct_rect` through [`set_palette_pred`].
15602 if palette_y.is_some() || palette_uv.is_some() {
15603 hit!(RECT4_PALETTE_HITS);
15604 }
15605 let palette_y_buf: Option<Vec<u16>> = palette_y
15606 .as_ref()
15607 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15608 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15609 (
15610 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15611 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15612 )
15613 });
15614 let (pal_y_size, pal_y_colors) = palette_y
15615 .as_ref()
15616 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15617 let (pal_uv_size, pal_uv_colors) = palette_uv
15618 .as_ref()
15619 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15620 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15621 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
15622 }
15623 if filter_intra.is_some() {
15624 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
15625 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
15626 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
15627 // below already makes; this refusal was square-only prose.
15628 hit!(FILTER_INTRA_RECT_HITS);
15629 hit!(FILTER_INTRA_RECT_SUB16_HITS);
15630 }
15631 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15632 DC_PRED
15633 } else {
15634 uv_mode
15635 };
15636 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
15637 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
15638 // a constant `false`.
15639 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
15640 let depth = if tx_select && !lossless(fctx) {
15641 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
15642 // every other rect reader now does -- a no-op on a key frame.
15643 // lane-av1mixloss: libaom `read_tx_size`'s first line
15644 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
15645 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
15646 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
15647 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
15648 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
15649 // read was the leaf's own txb_skip.
15650 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
15651 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
15652 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
15653 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
15654 // count (3), different CDF row: a wrong-table read of a real symbol,
15655 // the class that cost lane-rectsplit r1 its 64x32 depth.
15656 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
15657 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
15658 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
15659 // function also decodes) sit at depth 2, so they read
15660 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
15661 // while `tx_size_cat2` belongs to the 32-level shapes
15662 // ([`decode_block_rect`]). Both tables carry three symbols, so the
15663 // wrong one decodes a plausible depth from the wrong probabilities:
15664 // the range diverges silently at the first such leaf and every later
15665 // symbol in the tile is read from the wrong place (class
15666 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
15667 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
15668 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15669 eprintln!(
15670 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
15671 leaf_mi.0,
15672 leaf_mi.1,
15673 dec.debug_state().0
15674 );
15675 }
15676 d
15677 } else {
15678 0
15679 };
15680 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
15681 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15682 publish_txfm_bands_if_in_inter(
15683 neighbours,
15684 leaf_mi,
15685 depth_to_tx_wh(bw, bh, depth, fctx),
15686 (bw, bh),
15687 fctx,
15688 );
15689 if depth != 0 || lossless(fctx) {
15690 // The same per-transform-unit walk the bigger strips take
15691 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
15692 // depth 2), addressed at this leaf's own mi position.
15693 hit!(TX_DEPTH_HITS);
15694 hit!(SUB16_SPLIT_HITS);
15695 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15696 let modes = RectStripModes {
15697 skip,
15698 mode,
15699 angle_delta_y,
15700 uv_predict_mode,
15701 angle_delta_uv,
15702 alpha,
15703 filter_intra,
15704 smooth_neighbor,
15705 // lane-rectsplitx r3: the split arm hard-coded `false` here while
15706 // the unsplit arm below passes the real neighbour answer -- chroma
15707 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
15708 smooth_neighbor_uv,
15709 palette_y: palette_y_buf.clone(),
15710 palette_uv: palette_uv_bufs.clone(),
15711 };
15712 if palette_y.is_some() || palette_uv.is_some() {
15713 hit!(PALETTE_SPLIT_TX_HITS);
15714 }
15715 decode_rect_split(
15716 dec,
15717 cdfs,
15718 neighbours,
15719 leaf_mi,
15720 bw,
15721 bh,
15722 tx_w,
15723 tx_h,
15724 &modes,
15725 y,
15726 u,
15727 v,
15728 base_q_idx,
15729 reduced_tx_set,
15730 fctx,
15731 )?;
15732 record_strip_palette(
15733 neighbours,
15734 pal_at,
15735 bw,
15736 bh,
15737 pal_y_size,
15738 pal_y_colors,
15739 pal_uv_size,
15740 pal_uv_colors,
15741 );
15742 return Ok(mode);
15743 }
15744 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15745 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15746 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15747 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15748 let (luma_levels, u_levels, v_levels);
15749 if skip {
15750 luma_levels = Grid::Zero(bw * bh);
15751 u_levels = Grid::Zero(chroma_w * chroma_h);
15752 v_levels = Grid::Zero(chroma_w * chroma_h);
15753 if let Some(b) = &palette_y_buf {
15754 set_palette_pred(b.clone(), fctx);
15755 }
15756 push_intra_rect(
15757 0,
15758 px,
15759 py,
15760 bw,
15761 bh,
15762 mode,
15763 angle_delta_y,
15764 reach,
15765 &luma_levels,
15766 None,
15767 filter_intra,
15768 smooth_neighbor,
15769 fctx,
15770 );
15771 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15772 if let Some((ub, _)) = &palette_uv_bufs {
15773 set_palette_pred(ub.clone(), fctx);
15774 }
15775 push_intra_rect(
15776 1,
15777 cpx,
15778 cpy,
15779 chroma_w,
15780 chroma_h,
15781 uv_predict_mode,
15782 angle_delta_uv,
15783 reach,
15784 &u_levels,
15785 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15786 None,
15787 smooth_neighbor_uv,
15788 fctx,
15789 );
15790 if let Some((_, vb)) = &palette_uv_bufs {
15791 set_palette_pred(vb.clone(), fctx);
15792 }
15793 push_intra_rect(
15794 2,
15795 cpx,
15796 cpy,
15797 chroma_w,
15798 chroma_h,
15799 uv_predict_mode,
15800 angle_delta_uv,
15801 reach,
15802 &v_levels,
15803 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15804 None,
15805 smooth_neighbor_uv,
15806 fctx,
15807 );
15808 } else {
15809 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
15810 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
15811 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
15812 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
15813 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
15814 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
15815 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
15816 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
15817 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
15818 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
15819 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
15820 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
15821 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
15822 if bw == 16 {
15823 (&SCAN_16X8, &SCAN_16X8)
15824 } else {
15825 (&SCAN_8X16, &SCAN_8X16)
15826 }
15827 } else if chroma_422 {
15828 if bw == 16 {
15829 (&SCAN_16X8, default_scan(8))
15830 } else {
15831 (&SCAN_8X16, default_scan(8))
15832 }
15833 } else if bw == 16 {
15834 (&SCAN_16X8, &SCAN_8X4)
15835 } else {
15836 (&SCAN_8X16, &SCAN_4X8)
15837 };
15838 let chroma_rect_set = if ss_x(fctx) == 0 {
15839 TxbSet::ChromaRect16x8
15840 } else if chroma_422 {
15841 TxbSet::Chroma8
15842 } else {
15843 TxbSet::ChromaRect8x4
15844 };
15845 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
15846 // (side/2, side) block, so `side` chroma 4-px cells above it spread
15847 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
15848 // mi cells, and both carry the covering unit's whole-unit dc sign.
15849 // The per-mi rect gather therefore double-counts every chroma
15850 // column's sign. `around_mi_422_chroma`'s every-second above-cell
15851 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
15852 // gather in this file already routes through it (see the gate at this
15853 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
15854 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
15855 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
15856 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
15857 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
15858 // divergence in the frame (the bit offset is a clean constant through
15859 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
15860 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15861 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
15862 if chroma_422 {
15863 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
15864 around[1] = c[1];
15865 around[2] = c[2];
15866 }
15867 let luma_set = if reduced_tx_set {
15868 TxbSet::LumaRect16x8
15869 } else {
15870 TxbSet::LumaRect16x8Set1
15871 };
15872 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
15873 let (l_levels, luma_tx_type) = read_coeffs_rect(
15874 dec,
15875 &mut luma_coding,
15876 luma_scan,
15877 bw,
15878 bh,
15879 0,
15880 dc_sign_ctx(around[0].2),
15881 TxType::DctDct,
15882 0,
15883 )?;
15884 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15885 let nz: Vec<(usize, i32)> = l_levels
15886 .iter()
15887 .copied()
15888 .enumerate()
15889 .filter(|(_, v)| *v != 0)
15890 .collect();
15891 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
15892 }
15893 luma_levels = l_levels;
15894 let luma_residual = dequant_and_inverse_typed_wh(
15895 &luma_levels,
15896 bw,
15897 bh,
15898 crate::decode::bit_depth(fctx),
15899 block_q_idx(fctx),
15900 plane_q_delta(0, fctx).0,
15901 plane_q_delta(0, fctx).1,
15902 luma_tx_type,
15903 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15904 );
15905 if let Some(b) = &palette_y_buf {
15906 set_palette_pred(b.clone(), fctx);
15907 }
15908 push_intra_rect(
15909 0,
15910 px,
15911 py,
15912 bw,
15913 bh,
15914 mode,
15915 angle_delta_y,
15916 reach,
15917 &luma_residual,
15918 None,
15919 filter_intra,
15920 smooth_neighbor,
15921 fctx,
15922 );
15923 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15924 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15925 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15926 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15927 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
15928 dec,
15929 &mut u_coding,
15930 chroma_scan,
15931 chroma_w,
15932 chroma_h,
15933 u_skip_ctx,
15934 dc_sign_ctx(around[1].2),
15935 u_default_tx,
15936 fctx,
15937 1,
15938 )?;
15939 u_levels = u_l;
15940 let u_residual = dequant_and_inverse_typed_wh(
15941 &u_levels,
15942 chroma_w,
15943 chroma_h,
15944 crate::decode::bit_depth(fctx),
15945 block_q_idx(fctx),
15946 plane_q_delta(1, fctx).0,
15947 plane_q_delta(1, fctx).1,
15948 u_tx_type,
15949 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15950 );
15951 if let Some((ub, _)) = &palette_uv_bufs {
15952 set_palette_pred(ub.clone(), fctx);
15953 }
15954 push_intra_rect(
15955 1,
15956 cpx,
15957 cpy,
15958 chroma_w,
15959 chroma_h,
15960 uv_predict_mode,
15961 angle_delta_uv,
15962 reach,
15963 &u_residual,
15964 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15965 None,
15966 smooth_neighbor_uv,
15967 fctx,
15968 );
15969 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15970 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15971 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15972 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
15973 dec,
15974 &mut v_coding,
15975 chroma_scan,
15976 chroma_w,
15977 chroma_h,
15978 v_skip_ctx,
15979 dc_sign_ctx(around[2].2),
15980 v_default_tx,
15981 fctx,
15982 2,
15983 )?;
15984 v_levels = v_l;
15985 let v_residual = dequant_and_inverse_typed_wh(
15986 &v_levels,
15987 chroma_w,
15988 chroma_h,
15989 crate::decode::bit_depth(fctx),
15990 block_q_idx(fctx),
15991 plane_q_delta(2, fctx).0,
15992 plane_q_delta(2, fctx).1,
15993 v_tx_type,
15994 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15995 );
15996 if let Some((_, vb)) = &palette_uv_bufs {
15997 set_palette_pred(vb.clone(), fctx);
15998 }
15999 push_intra_rect(
16000 2,
16001 cpx,
16002 cpy,
16003 chroma_w,
16004 chroma_h,
16005 uv_predict_mode,
16006 angle_delta_uv,
16007 reach,
16008 &v_residual,
16009 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16010 None,
16011 smooth_neighbor_uv,
16012 fctx,
16013 );
16014 hit!(RECT_LEAF_COEFF_HITS);
16015 }
16016 neighbours.record_mi_rect(
16017 leaf_mi,
16018 bw,
16019 bh,
16020 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16021 );
16022 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
16023 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16024 // The leaf's own palette state (`0` clears, as this site always did
16025 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
16026 // AXIS only until the pair's closing leaf: the coarse cell holds one
16027 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
16028 // real left neighbour leaf 1 reads (lane-kf900 r4).
16029 record_strip_palette(
16030 neighbours,
16031 pal_at,
16032 bw,
16033 bh,
16034 pal_y_size,
16035 pal_y_colors,
16036 pal_uv_size,
16037 pal_uv_colors,
16038 );
16039 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
16040 // rows -- record the whole span, not one cell.
16041 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
16042 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
16043 Ok(mode)
16044}
16045
16046/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
16047/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
16048/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
16049/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
16050/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
16051/// strip's mode so this one's mode context sees its true above/left
16052/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
16053///
16054/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
16055/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
16056/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
16057/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
16058/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
16059/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
16060/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
16061///
16062/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
16063/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
16064/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
16065/// unexamined.
16066#[allow(clippy::too_many_arguments)]
16067fn decode_block_rect4(
16068 dec: &mut SymbolDecoder,
16069 cdfs: &mut Cdfs,
16070 neighbours: &mut Neighbours,
16071 strip_mi: (usize, usize),
16072 bw: usize,
16073 bh: usize,
16074 prev_strip: Option<((usize, usize), usize)>,
16075 y: &mut PlaneBuf<'static>,
16076 u: &mut PlaneBuf<'static>,
16077 v: &mut PlaneBuf<'static>,
16078 enable_filter_intra: bool,
16079 allow_screen_content_tools: bool,
16080 base_q_idx: u8,
16081 tx_select: bool,
16082 fctx: &crate::decode::FrameCtx,
16083) -> Result<(usize, usize)> {
16084 let _ = base_q_idx;
16085 let (mi_r, mi_c) = strip_mi;
16086 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
16087 let (mi_w, mi_h) = (bw / MI, bh / MI);
16088 let mut above_mode = neighbours.above_mode[c];
16089 let mut left_mode = neighbours.left_mode[r];
16090 if let Some(((pr, pc), pmode)) = prev_strip {
16091 if pc == mi_c && mi_r == pr + mi_h {
16092 above_mode = pmode;
16093 } else if pr == mi_r && mi_c == pc + mi_w {
16094 left_mode = pmode;
16095 }
16096 }
16097 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
16098 // availability-correct neighbour modes (see
16099 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
16100 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
16101 let (above_mode, left_mode) =
16102 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
16103 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
16104 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
16105 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
16106 // wrong interval, so a screen-content tile desynced at the first strip
16107 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
16108 let pal_at = (mi_r, mi_c);
16109 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
16110 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
16111 let (
16112 skip,
16113 mode,
16114 angle_delta_y,
16115 uv_mode,
16116 angle_delta_uv,
16117 alpha,
16118 filter_intra,
16119 palette_y,
16120 palette_uv,
16121 intrabc,
16122 ) = read_intra_mode_rect(
16123 dec,
16124 cdfs,
16125 above_mode,
16126 left_mode,
16127 true,
16128 true,
16129 bw,
16130 bh,
16131 enable_filter_intra,
16132 neighbours.skip_txfm_ctx(mi_r, mi_c),
16133 allow_screen_content_tools,
16134 Some((palette_ctx, &palette_cache)),
16135 &palette_uv_cache,
16136 mi_r,
16137 mi_c,
16138 fctx,
16139 )?;
16140 if let Some((dv_row, dv_col)) = intrabc {
16141 decode_intrabc_rect(
16142 dec,
16143 cdfs,
16144 neighbours,
16145 strip_mi,
16146 (bw, bh),
16147 skip,
16148 (dv_row, dv_col),
16149 y,
16150 u,
16151 v,
16152 base_q_idx,
16153 fctx,
16154 )?;
16155 return Ok((DC_PRED, DC_PRED));
16156 }
16157 // lane-kf900 r4: palette prediction on this shape, exactly as
16158 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
16159 // mapped through the base colours IS the prediction (it reads no edge
16160 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
16161 if palette_y.is_some() || palette_uv.is_some() {
16162 hit!(RECT4_PALETTE_HITS);
16163 }
16164 let palette_y_buf: Option<Vec<u16>> = palette_y
16165 .as_ref()
16166 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16167 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16168 (
16169 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16170 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16171 )
16172 });
16173 let (pal_y_size, pal_y_colors) = palette_y
16174 .as_ref()
16175 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16176 let (pal_uv_size, pal_uv_colors) = palette_uv
16177 .as_ref()
16178 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16179 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16180 if smooth_neighbor {
16181 hit!(SMOOTH_LUMA_HITS);
16182 }
16183 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
16184 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
16185 // `r * (SUB / MI)` names a different mi column and the chroma
16186 // edge-filter strength was read from the wrong neighbour (measured:
16187 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
16188 // with luma bit-exact).
16189 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
16190 if filter_intra.is_some() {
16191 hit!(FILTER_INTRA_RECT_HITS);
16192 if bw > bh {
16193 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
16194 } else {
16195 hit!(FILTER_INTRA_RECT4_VERT_HITS);
16196 }
16197 }
16198 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16199 DC_PRED
16200 } else {
16201 uv_mode
16202 };
16203 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
16204 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
16205 // depth symbol here either (class sweep of the sub8 leaf's fix).
16206 let depth = if tx_select && !lossless(fctx) {
16207 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
16208 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
16209 // intra-only frame publishes them from every block too
16210 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
16211 // 1920x792 128-superblock stream,
16212 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
16213 // `tx_size_cat2` row 1 where libaom reads row 2.
16214 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
16215 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
16216 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16217 eprintln!(
16218 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
16219 dec.debug_state().0
16220 );
16221 }
16222 d
16223 } else {
16224 0
16225 };
16226 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
16227 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
16228 publish_txfm_bands_if_in_inter(
16229 neighbours,
16230 (mi_r, mi_c),
16231 depth_to_tx_wh(bw, bh, depth, fctx),
16232 (bw, bh),
16233 fctx,
16234 );
16235 if depth != 0 || lossless(fctx) {
16236 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
16237 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
16238 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
16239 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
16240 // both interleave in every real stream.
16241 hit!(TX_DEPTH_HITS);
16242 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16243 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
16244 // predicted -- depth 1 fires FIRST in every attempt that splits at
16245 // all, so a depth-2-only lift could never be gated. The r1 mismatch
16246 // was never the rect unit: it was the neighbour MODE the strip reads
16247 // (see `modes_above_left_mi`).
16248 let which = if depth == 1 {
16249 &RECT4_SPLIT_DEPTH1_HITS
16250 } else {
16251 &RECT4_SPLIT_DEPTH2_HITS
16252 };
16253 hit_do! { which.with(|c| c.set(c.get() + 1)); }
16254 let modes = RectStripModes {
16255 skip,
16256 mode,
16257 angle_delta_y,
16258 uv_predict_mode,
16259 angle_delta_uv,
16260 alpha,
16261 filter_intra,
16262 smooth_neighbor,
16263 smooth_neighbor_uv,
16264 palette_y: palette_y_buf.clone(),
16265 palette_uv: palette_uv_bufs.clone(),
16266 };
16267 if palette_y.is_some() || palette_uv.is_some() {
16268 hit!(PALETTE_SPLIT_TX_HITS);
16269 }
16270 decode_rect_split(
16271 dec,
16272 cdfs,
16273 neighbours,
16274 (mi_r, mi_c),
16275 bw,
16276 bh,
16277 tx_w,
16278 tx_h,
16279 &modes,
16280 y,
16281 u,
16282 v,
16283 base_q_idx,
16284 false,
16285 fctx,
16286 )?;
16287 record_strip_palette(
16288 neighbours,
16289 pal_at,
16290 bw,
16291 bh,
16292 pal_y_size,
16293 pal_y_colors,
16294 pal_uv_size,
16295 pal_uv_colors,
16296 );
16297 if bw > bh {
16298 hit!(RECT4_32_HORZ_HITS);
16299 } else {
16300 hit!(RECT4_32_VERT_HITS);
16301 }
16302 if !skip {
16303 hit!(RECT4_COEFF_HITS);
16304 }
16305 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16306 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16307 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16308 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16309 // transform size in both TXFM_CONTEXT bands. Without it the next block
16310 // reads the row's stale value.
16311 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16312 return Ok((mode, uv_predict_mode));
16313 }
16314 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16315 // that is 8 px tall, so each strip stamps every cell it touches and the
16316 // LAST strip wins -- which is the right answer for the block below/right
16317 // of the 32x32, the only reader outside it. Written after this strip's
16318 // own context read above, never before.
16319 for cell in 0..bw.div_ceil(SUB) {
16320 neighbours.above_mode[c + cell] = mode;
16321 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16322 neighbours.above_side[c + cell] = bw;
16323 }
16324 for cell in 0..bh.div_ceil(SUB) {
16325 neighbours.left_mode[r + cell] = mode;
16326 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16327 neighbours.left_side[r + cell] = bh;
16328 }
16329 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16330 // [`decode_leaf_rect`] does (the split arm above records these through
16331 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16332 // `sub8_mode_row` holding the previous block, and the next 32x32's
16333 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16334 // fixture).
16335 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16336 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16337 let (px, py) = (mi_c * MI, mi_r * MI);
16338 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16339 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16340 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16341 // lane-av1-444: the strip's chroma shape follows the subsampling.
16342 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16343 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16344 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16345 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16346 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16347 // and 1/1 only -- so the table is exhaustive.
16348 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16349 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16350 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16351 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16352 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16353 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16354 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
16355 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
16356 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
16357 // [`decode_rect_split`]'s chroma table use.
16358 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
16359 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
16360 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
16361 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
16362 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
16363 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
16364 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
16365 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
16366 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
16367 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
16368 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
16369 // instead of refusing; no coefficient-table row is added, because
16370 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
16371 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
16372 // 4:2:2-only.
16373 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
16374 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
16375 // lane-av1-422p: the units' own set/scan -- the whole-rect read
16376 // below never sees this row, the `chroma422_rect32` arm chunks
16377 // first. Anything else is still a named-lane gap.
16378 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
16379 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
16380 };
16381 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
16382 let (luma_levels, u_levels, v_levels) = if skip {
16383 (
16384 vec![0i32; bw * bh],
16385 vec![0i32; chroma_w * chroma_h],
16386 vec![0i32; chroma_w * chroma_h],
16387 )
16388 } else if chroma422_rect32 {
16389 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
16390 // plane-major (every U unit, then every V) -- the walk the pinned
16391 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
16392 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
16393 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
16394 // Luma is the same single TX_8X32 rect the general arm reads.
16395 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16396 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16397 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16398 dec,
16399 &mut luma_coding,
16400 luma_scan,
16401 bw,
16402 bh,
16403 0,
16404 dc_sign_ctx(around[0].2),
16405 TxType::DctDct,
16406 0,
16407 )?;
16408 hit!(RECT4_COEFF_HITS);
16409 let luma_residual = dequant_and_inverse_typed_wh(
16410 &luma_levels,
16411 bw,
16412 bh,
16413 crate::decode::bit_depth(fctx),
16414 block_q_idx(fctx),
16415 plane_q_delta(0, fctx).0,
16416 plane_q_delta(0, fctx).1,
16417 luma_tx_type,
16418 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16419 );
16420 if let Some(b) = &palette_y_buf {
16421 set_palette_pred(b.clone(), fctx);
16422 }
16423 push_intra_rect(
16424 0,
16425 px,
16426 py,
16427 bw,
16428 bh,
16429 mode,
16430 angle_delta_y,
16431 reach,
16432 &luma_residual,
16433 None,
16434 filter_intra,
16435 smooth_neighbor,
16436 fctx,
16437 );
16438 // CfL parameters are computed ONCE per block over the strip's luma
16439 // (`are_parameters_computed`) and shared by all four units, as in
16440 // every other chunk arm.
16441 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16442 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
16443 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16444 for unit_row in 0..4usize {
16445 let unit_mi = (mi_r + unit_row * 2, mi_c);
16446 let unit_reach = tu_reach_rect(
16447 bw,
16448 bh,
16449 0,
16450 unit_row * 8,
16451 8,
16452 8,
16453 reach,
16454 px,
16455 py,
16456 y.width,
16457 y.height,
16458 fctx,
16459 );
16460 if let Some((ub, vb)) = &palette_uv_bufs {
16461 let pbuf = if plane == 1 { ub } else { vb };
16462 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16463 }
16464 // Each unit is read and recorded IMMEDIATELY: unit row 0's
16465 // `txb_skip_ctx` still sees the real above/left neighbour
16466 // states, a lower unit sees this block's own upper unit's
16467 // (libaom's per-unit `set_entropy_context`), and the lower
16468 // unit predicts off the upper one's reconstructed samples.
16469 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
16470 let unit_grid = read_rect_chroma_unit(
16471 dec,
16472 cdfs,
16473 TxbSet::ChromaRect8x4,
16474 &SCAN_4X8,
16475 4,
16476 8,
16477 plane,
16478 chroma_around[plane],
16479 uv_predict_mode,
16480 angle_delta_uv,
16481 unit_reach,
16482 buf,
16483 cpx,
16484 cpy + unit_row * 8,
16485 base_q_idx,
16486 // `get_txb_ctx_general`'s chroma branch
16487 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
16488 // here, `num_pels_log2_lookup[255]` = 255 (the +255
16489 // byte of the decodetxb copy at 0xc0de70,
16490 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
16491 // ctx_offset is 10 -- the port's offset-7-first
16492 // `txb_skip_chroma_8` stores the offset-10 rows at
16493 // rows 3..6, hence +3.
16494 Some(3),
16495 alpha
16496 .zip(ac)
16497 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16498 smooth_neighbor_uv,
16499 fctx,
16500 )?;
16501 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
16502 unit_grids.push((unit_mi, plane, unit_grid));
16503 }
16504 }
16505 // The whole-block stamp rewrites the chroma cells ONE state wide,
16506 // which would erase the unit boundary the next block reads (class
16507 // `override-slot-on-one-arm`), so it carries zero chroma grids and
16508 // the per-unit writes replay after it. Its luma cells and side
16509 // spans are this arm's own bookkeeping.
16510 let zero_chroma = vec![0i32; chroma_w * chroma_h];
16511 neighbours.record_mi_rect(
16512 (mi_r, mi_c),
16513 bw,
16514 bh,
16515 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
16516 );
16517 for (unit_mi, plane, grid) in &unit_grids {
16518 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
16519 }
16520 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16521 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16522 record_strip_palette(
16523 neighbours,
16524 pal_at,
16525 bw,
16526 bh,
16527 pal_y_size,
16528 pal_y_colors,
16529 pal_uv_size,
16530 pal_uv_colors,
16531 );
16532 if bw > bh {
16533 hit!(RECT4_32_HORZ_HITS);
16534 } else {
16535 hit!(RECT4_32_VERT_HITS);
16536 }
16537 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16538 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16539 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16540 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16541 // transform size in both TXFM_CONTEXT bands. Without it the next block
16542 // reads the row's stale value.
16543 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16544 return Ok((mode, uv_predict_mode));
16545 } else {
16546 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16547 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16548 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16549 dec,
16550 &mut luma_coding,
16551 luma_scan,
16552 bw,
16553 bh,
16554 0,
16555 dc_sign_ctx(around[0].2),
16556 TxType::DctDct,
16557 0,
16558 )?;
16559 let mut planes = Vec::with_capacity(2);
16560 for plane in 1..3 {
16561 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
16562 // stands only while it is a member of this tx size's set; a
16563 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
16564 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
16565 // to DCT_DCT there, and ADST is undefined at widths above 16.
16566 let default_tx = if chroma_w.max(chroma_h) >= 32 {
16567 TxType::DctDct
16568 } else {
16569 default_intra_tx_type(uv_predict_mode as u8)
16570 };
16571 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
16572 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
16573 let (levels, tx_type) = read_chroma_coeffs_rect(
16574 dec,
16575 &mut coding,
16576 chroma_scan,
16577 chroma_w,
16578 chroma_h,
16579 skip_ctx,
16580 dc_sign_ctx(around[plane].2),
16581 default_tx,
16582 fctx,
16583 plane,
16584 )?;
16585 planes.push((levels, tx_type));
16586 }
16587 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
16588 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
16589 hit!(RECT4_COEFF_HITS);
16590 let luma_residual = dequant_and_inverse_typed_wh(
16591 &luma_levels,
16592 bw,
16593 bh,
16594 crate::decode::bit_depth(fctx),
16595 block_q_idx(fctx),
16596 plane_q_delta(0, fctx).0,
16597 plane_q_delta(0, fctx).1,
16598 luma_tx_type,
16599 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16600 );
16601 if let Some(b) = &palette_y_buf {
16602 set_palette_pred(b.clone(), fctx);
16603 }
16604 push_intra_rect(
16605 0,
16606 px,
16607 py,
16608 bw,
16609 bh,
16610 mode,
16611 angle_delta_y,
16612 reach,
16613 &luma_residual,
16614 None,
16615 filter_intra,
16616 smooth_neighbor,
16617 fctx,
16618 );
16619 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16620 for (plane, _buf, levels, tx_type) in [
16621 (1usize, &mut *u, &u_levels, u_tx_type),
16622 (2, &mut *v, &v_levels, v_tx_type),
16623 ] {
16624 let residual = dequant_and_inverse_typed_wh(
16625 levels,
16626 chroma_w,
16627 chroma_h,
16628 crate::decode::bit_depth(fctx),
16629 block_q_idx(fctx),
16630 plane_q_delta(plane, fctx).0,
16631 plane_q_delta(plane, fctx).1,
16632 tx_type,
16633 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
16634 );
16635 if let Some((ub, vb)) = &palette_uv_bufs {
16636 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
16637 }
16638 push_intra_rect(
16639 plane,
16640 cpx,
16641 cpy,
16642 chroma_w,
16643 chroma_h,
16644 uv_predict_mode,
16645 angle_delta_uv,
16646 reach,
16647 &residual,
16648 alpha
16649 .zip(ac)
16650 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16651 None,
16652 smooth_neighbor_uv,
16653 fctx,
16654 );
16655 }
16656 neighbours.record_mi_rect(
16657 (mi_r, mi_c),
16658 bw,
16659 bh,
16660 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16661 );
16662 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16663 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16664 record_strip_palette(
16665 neighbours,
16666 pal_at,
16667 bw,
16668 bh,
16669 pal_y_size,
16670 pal_y_colors,
16671 pal_uv_size,
16672 pal_uv_colors,
16673 );
16674 if bw > bh {
16675 hit!(RECT4_32_HORZ_HITS);
16676 } else {
16677 hit!(RECT4_32_VERT_HITS);
16678 }
16679 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16680 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16681 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16682 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16683 // transform size in both TXFM_CONTEXT bands. Without it the next block
16684 // reads the row's stale value.
16685 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16686 return Ok((mode, uv_predict_mode));
16687 };
16688 if let Some(b) = &palette_y_buf {
16689 set_palette_pred(b.clone(), fctx);
16690 }
16691 push_intra_rect(
16692 0,
16693 px,
16694 py,
16695 bw,
16696 bh,
16697 mode,
16698 angle_delta_y,
16699 reach,
16700 &luma_levels,
16701 None,
16702 filter_intra,
16703 smooth_neighbor,
16704 fctx,
16705 );
16706 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16707 if chroma422_rect32 {
16708 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
16709 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
16710 // arm walks the same four TX_4X8 units per plane -- the lower unit
16711 // predicts off the upper one's predicted samples. No coefficients
16712 // are coded; the tail's whole-block zero stamp below is the state
16713 // libaom's `set_entropy_context` leaves.
16714 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16715 for unit_row in 0..4usize {
16716 let unit_reach = tu_reach_rect(
16717 bw,
16718 bh,
16719 0,
16720 unit_row * 8,
16721 8,
16722 8,
16723 reach,
16724 px,
16725 py,
16726 y.width,
16727 y.height,
16728 fctx,
16729 );
16730 if let Some((ub, vb)) = &palette_uv_bufs {
16731 let pbuf = if plane == 1 { ub } else { vb };
16732 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16733 }
16734 push_intra_rect(
16735 plane,
16736 cpx,
16737 cpy + unit_row * 8,
16738 4,
16739 8,
16740 uv_predict_mode,
16741 angle_delta_uv,
16742 unit_reach,
16743 &ZERO_RESIDUAL[..4 * 8],
16744 alpha
16745 .zip(ac)
16746 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16747 None,
16748 smooth_neighbor_uv,
16749 fctx,
16750 );
16751 }
16752 }
16753 } else {
16754 if let Some((ub, _)) = &palette_uv_bufs {
16755 set_palette_pred(ub.clone(), fctx);
16756 }
16757 push_intra_rect(
16758 1,
16759 cpx,
16760 cpy,
16761 chroma_w,
16762 chroma_h,
16763 uv_predict_mode,
16764 angle_delta_uv,
16765 reach,
16766 &u_levels,
16767 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16768 None,
16769 smooth_neighbor_uv,
16770 fctx,
16771 );
16772 if let Some((_, vb)) = &palette_uv_bufs {
16773 set_palette_pred(vb.clone(), fctx);
16774 }
16775 push_intra_rect(
16776 2,
16777 cpx,
16778 cpy,
16779 chroma_w,
16780 chroma_h,
16781 uv_predict_mode,
16782 angle_delta_uv,
16783 reach,
16784 &v_levels,
16785 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16786 None,
16787 smooth_neighbor_uv,
16788 fctx,
16789 );
16790 }
16791 neighbours.record_mi_rect(
16792 (mi_r, mi_c),
16793 bw,
16794 bh,
16795 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16796 );
16797 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16798 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16799 record_strip_palette(
16800 neighbours,
16801 pal_at,
16802 bw,
16803 bh,
16804 pal_y_size,
16805 pal_y_colors,
16806 pal_uv_size,
16807 pal_uv_colors,
16808 );
16809 if bw > bh {
16810 hit!(RECT4_32_HORZ_HITS);
16811 } else {
16812 hit!(RECT4_32_VERT_HITS);
16813 }
16814 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16815 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16816 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16817 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16818 // transform size in both TXFM_CONTEXT bands. Without it the next block
16819 // reads the row's stale value.
16820 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16821 Ok((mode, uv_predict_mode))
16822}
16823
16824/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
16825/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
16826/// down, and the first shape here whose luma block is a single mi row (or
16827/// column).
16828///
16829/// What is new at this size is CHROMA. `is_chroma_reference`
16830/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
16831/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
16832/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
16833/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
16834/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
16835/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
16836/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
16837///
16838/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
16839/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
16840/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
16841/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
16842/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
16843/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
16844/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
16845/// shape's own CDF row.
16846///
16847/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
16848/// refuses by name rather than guess-decode.
16849#[allow(clippy::too_many_arguments)]
16850fn decode_rect4_16(
16851 dec: &mut SymbolDecoder,
16852 cdfs: &mut Cdfs,
16853 neighbours: &mut Neighbours,
16854 at16: (usize, usize),
16855 horz: bool,
16856 y: &mut PlaneBuf<'static>,
16857 u: &mut PlaneBuf<'static>,
16858 v: &mut PlaneBuf<'static>,
16859 enable_filter_intra: bool,
16860 allow_screen_content_tools: bool,
16861 base_q_idx: u8,
16862 tx_select: bool,
16863 reduced_tx_set: bool,
16864 fctx: &crate::decode::FrameCtx,
16865) -> Result<()> {
16866 let (r, c) = at16;
16867 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
16868 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
16869 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
16870 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
16871 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
16872 let mut prev: Option<((usize, usize), usize)> = None;
16873 let mut last_mode = DC_PRED;
16874 let mut last_uv_mode = DC_PRED;
16875 for i in 0..4usize {
16876 let lmi = if horz {
16877 (mi_row0 + i, mi_col0)
16878 } else {
16879 (mi_row0, mi_col0 + i)
16880 };
16881 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
16882 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
16883 // already >= 4x4) -- there is no 4:2:0 pair to close.
16884 // lane-av1-422o: the parity rule is per axis, straight out of
16885 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
16886 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
16887 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
16888 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
16889 // every ss_x == 1 format -- the ODD strip closes the pair and reads
16890 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
16891 // even mi_col, so `i % 2 == 1` is that clause.)
16892 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
16893 let (mode, uv, _tx) = decode_rect4_16_strip(
16894 dec,
16895 cdfs,
16896 neighbours,
16897 lmi,
16898 horz,
16899 has_chroma,
16900 prev,
16901 y,
16902 u,
16903 v,
16904 enable_filter_intra,
16905 allow_screen_content_tools,
16906 base_q_idx,
16907 tx_select,
16908 reduced_tx_set,
16909 fctx,
16910 )?;
16911 if let Some(m) = uv {
16912 last_uv_mode = m;
16913 }
16914 last_mode = mode;
16915 prev = Some((lmi, mode));
16916 }
16917 // The coarse 16-px cell holds one entry for the whole 16x16: the last
16918 // strip is what a block below (right) sees through it, the mi-exact maps
16919 // above answering everything finer.
16920 neighbours.above_mode[c] = last_mode;
16921 neighbours.left_mode[r] = last_mode;
16922 neighbours.above_uv_mode[c] = last_uv_mode;
16923 neighbours.left_uv_mode[r] = last_uv_mode;
16924 neighbours.above_side[c] = bw;
16925 neighbours.left_side[r] = bh;
16926 Ok(())
16927}
16928
16929/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
16930/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
16931/// block path can decode a SINGLE intra strip of a partition whose other
16932/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
16933/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
16934/// every strip publishes its own mi-exact mode). Returns
16935/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
16936/// Intrabc reconstruction for a rect strip that OWNS its chroma
16937/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
16938/// pair goes through [`decode_rect4_16_intrabc`].
16939///
16940/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
16941/// (predict once, then one residual per transform unit on the INTER sets,
16942/// chroma inherits luma's `tx_type`), written against the helpers that exist
16943/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
16944/// merge with lane-av1-intrabc should keep one of the two bodies; the call
16945/// shape is the same.
16946#[allow(clippy::too_many_arguments)]
16947fn decode_intrabc_owned_rect(
16948 dec: &mut SymbolDecoder,
16949 cdfs: &mut Cdfs,
16950 neighbours: &mut Neighbours,
16951 (mi_r, mi_c): (usize, usize),
16952 (bw, bh): (usize, usize),
16953 skip: bool,
16954 (dv_row, dv_col): (i32, i32),
16955 y: &mut PlaneBuf<'static>,
16956 u: &mut PlaneBuf<'static>,
16957 v: &mut PlaneBuf<'static>,
16958 base_q_idx: u8,
16959 tx_select: bool,
16960 reduced_tx_set: bool,
16961 fctx: &crate::decode::FrameCtx,
16962) -> Result<()> {
16963 let _ = base_q_idx;
16964 let (px, py) = (mi_c * MI, mi_r * MI);
16965 // lane-av1chromarect: libaom does NOT halve a 128-root intra-BC strip's
16966 // chroma plane block. `av1_get_max_uv_txsize` (blockd.h:1372) is
16967 // `max_txsize_rect_lookup[get_plane_block_size(bsize, ss_x, ss_y)]` run
16968 // through `av1_get_adjusted_tx_size`, and `get_plane_block_size` is
16969 // `ss_size_lookup[bsize]` -- at 4:4:4 the chroma plane block is the block's
16970 // OWN footprint, so the extent below and the eight chroma MV origin pairs
16971 // that follow must be `>> ss_x` / `>> ss_y`, not `/ 2`. At 4:2:0
16972 // (`ss_x == ss_y == 1`) the two forms are the same arithmetic.
16973 // MEASURED on the 4:4:4 LOSSY witness `fixtures/r512.obu` (6948 B, 3
16974 // frames, 5 strips through this function): with the halving, frame 0
16975 // diverges from the aomdec oracle in 166229 Y / 155383 U / 153498 V
16976 // samples and both later frames keep luma byte-exact while 74708 U +
16977 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
16978 // what makes this a chroma-sizing defect and not a block-geometry one.
16979 // Re-measured by this lane; see lanes/av1chromarect.report.md.
16980 if crate::envflags::env_flag!("EC_HALVSWEEP") {
16981 eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
16982 }
16983 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16984 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16985 let side = bw.max(bh);
16986 let cside = cw.max(ch);
16987 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
16988 hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS);
16989 }
16990 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16991 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
16992 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16993 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
16994 // false; the real bit is the caller's `tx_select`. Restored before return.
16995 fctx.tx_select_inter.with(|c| c.set(tx_select));
16996 let restore = ReducedTxRestore {
16997 fctx,
16998 saved_reduced,
16999 saved_tx,
17000 };
17001
17002 flush_recon(fctx, y, u, v);
17003 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
17004 let pred_u = predict_intrabc_window(u, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17005 let pred_v = predict_intrabc_window(v, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17006
17007 let mi_cols = 2 * y.true_width.div_ceil(8);
17008 let mi_rows = 2 * y.true_height.div_ceil(8);
17009 let leaves = read_block_tx_size_rect(
17010 dec,
17011 cdfs,
17012 neighbours,
17013 (mi_r, mi_c),
17014 (bw, bh),
17015 (mi_cols, mi_rows),
17016 skip,
17017 fctx,
17018 )?;
17019 let mut luma_tx_type = TxType::DctDct;
17020 let luma_grid;
17021 let u_grid;
17022 let v_grid;
17023 if skip {
17024 // `reconstruct_mc_rect` indexes the residual at the square stride.
17025 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
17026 push_mc_rect(
17027 0,
17028 px,
17029 py,
17030 side,
17031 bw,
17032 bh,
17033 Pred::Inline(&pred_y, side),
17034 &ZERO_RESIDUAL[..side * bh],
17035 fctx,
17036 );
17037 push_mc_rect(
17038 1,
17039 cpx,
17040 cpy,
17041 cside,
17042 cw,
17043 ch,
17044 Pred::Inline(&pred_u, cside),
17045 &ZERO_RESIDUAL[..cside * ch],
17046 fctx,
17047 );
17048 push_mc_rect(
17049 2,
17050 cpx,
17051 cpy,
17052 cside,
17053 cw,
17054 ch,
17055 Pred::Inline(&pred_v, cside),
17056 &ZERO_RESIDUAL[..cside * ch],
17057 fctx,
17058 );
17059 if let Some(ls) = leaves.as_ref() {
17060 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
17061 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
17062 // whole entropy-band footprint. The non-skip arm below writes
17063 // those bands per transform unit and the tail's
17064 // `record_split_luma_rect_mi` writes chroma only, so without
17065 // this walk a skipped strip whose `leaves` resolved (every
17066 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
17067 // returns the 4x4 grid before it looks at `skip`) leaked the
17068 // PREVIOUS occupant's luma bands into the next block's
17069 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
17070 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
17071 // stream left a stale 7 in left[48] and mi(48,68)'s first
17072 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
17073 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
17074 for &(row, col, tw, th) in ls {
17075 neighbours.record_mi_luma_rect(
17076 (mi_r + row, mi_c + col),
17077 tw,
17078 th,
17079 &ZERO_RESIDUAL[..tw * th],
17080 );
17081 }
17082 }
17083 luma_grid = Grid::Zero(side * side);
17084 u_grid = Grid::Zero(cside * cside);
17085 v_grid = Grid::Zero(cside * cside);
17086 } else if let Some(ls) = leaves.as_ref() {
17087 let mut leaf_types: Vec<(usize, usize, usize, usize, TxType)> =
17088 Vec::with_capacity(ls.len());
17089 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17090 let tu_mi = (mi_r + row, mi_c + col);
17091 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17092 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17093 let (g, tt) = if tw == th {
17094 read_inter_plane(
17095 dec,
17096 cdfs,
17097 inter_txbset_for(tw, reduced_tx_set),
17098 &default_scan(tw.min(32)),
17099 0,
17100 neighbours.around_mi(tu_mi, tw)[0],
17101 0,
17102 y,
17103 tu_px,
17104 tu_py,
17105 tw,
17106 base_q_idx,
17107 tu_pred,
17108 None,
17109 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17110 fctx,
17111 )?
17112 } else {
17113 read_inter_plane_rect(
17114 dec,
17115 cdfs,
17116 rect_inter_luma_set(tw, th, fctx)?,
17117 (tw, th),
17118 side,
17119 0,
17120 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17121 0,
17122 y,
17123 tu_px,
17124 tu_py,
17125 tu_pred,
17126 None,
17127 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17128 fctx,
17129 )?
17130 };
17131 leaf_types.push((row, col, tw, th, tt));
17132 if idx == 0 {
17133 luma_tx_type = tt;
17134 }
17135 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17136 if tw != th {
17137 neighbours.fill_lf_grid_leaf_luma(
17138 (tu_mi.0, tu_mi.1),
17139 tw / MI,
17140 th / MI,
17141 tw as u8,
17142 th as u8,
17143 );
17144 }
17145 }
17146 luma_grid = Grid::Zero(side * side);
17147 if cw.min(32) != cw || ch.min(32) != ch {
17148 // lane-av1chromarect: more than one chroma transform unit (the
17149 // 4:4:4 32x64/64x32 plane block). See the helper.
17150 let (ug, vg) = read_intrabc_rect_chroma_split(
17151 dec,
17152 cdfs,
17153 neighbours,
17154 (mi_r, mi_c),
17155 (cpx, cpy),
17156 (cw, ch),
17157 cside,
17158 &pred_u,
17159 &pred_v,
17160 &leaf_types,
17161 luma_tx_type,
17162 u,
17163 v,
17164 fctx,
17165 )?;
17166 u_grid = ug;
17167 v_grid = vg;
17168 } else {
17169 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17170 let (ug, _) = read_inter_plane_rect(
17171 dec,
17172 cdfs,
17173 rect_inter_chroma_set(cw, ch)?,
17174 (cw, ch),
17175 cside,
17176 1,
17177 around[1],
17178 0,
17179 u,
17180 cpx,
17181 cpy,
17182 Pred::Inline(&pred_u, cside),
17183 Some(luma_tx_type),
17184 None,
17185 fctx,
17186 )?;
17187 let (vg, _) = read_inter_plane_rect(
17188 dec,
17189 cdfs,
17190 rect_inter_chroma_set(cw, ch)?,
17191 (cw, ch),
17192 cside,
17193 2,
17194 around[2],
17195 0,
17196 v,
17197 cpx,
17198 cpy,
17199 Pred::Inline(&pred_v, cside),
17200 Some(luma_tx_type),
17201 None,
17202 fctx,
17203 )?;
17204 u_grid = ug;
17205 v_grid = vg;
17206 }
17207 } else {
17208 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17209 let (g, tt) = read_inter_plane_rect(
17210 dec,
17211 cdfs,
17212 rect_inter_luma_set(bw, bh, fctx)?,
17213 (bw, bh),
17214 side,
17215 0,
17216 around[0],
17217 0,
17218 y,
17219 px,
17220 py,
17221 Pred::Inline(&pred_y, side),
17222 None,
17223 None,
17224 fctx,
17225 )?;
17226 luma_tx_type = tt;
17227 luma_grid = g;
17228 if cw.min(32) != cw || ch.min(32) != ch {
17229 // lane-av1chromarect: more than one chroma transform unit (the
17230 // 4:4:4 32x64/64x32 plane block). See the helper.
17231 let (ug, vg) = read_intrabc_rect_chroma_split(
17232 dec,
17233 cdfs,
17234 neighbours,
17235 (mi_r, mi_c),
17236 (cpx, cpy),
17237 (cw, ch),
17238 cside,
17239 &pred_u,
17240 &pred_v,
17241 &[],
17242 luma_tx_type,
17243 u,
17244 v,
17245 fctx,
17246 )?;
17247 u_grid = ug;
17248 v_grid = vg;
17249 } else {
17250 let (ug, _) = read_inter_plane_rect(
17251 dec,
17252 cdfs,
17253 rect_inter_chroma_set(cw, ch)?,
17254 (cw, ch),
17255 cside,
17256 1,
17257 around[1],
17258 0,
17259 u,
17260 cpx,
17261 cpy,
17262 Pred::Inline(&pred_u, cside),
17263 Some(luma_tx_type),
17264 None,
17265 fctx,
17266 )?;
17267 let (vg, _) = read_inter_plane_rect(
17268 dec,
17269 cdfs,
17270 rect_inter_chroma_set(cw, ch)?,
17271 (cw, ch),
17272 cside,
17273 2,
17274 around[2],
17275 0,
17276 v,
17277 cpx,
17278 cpy,
17279 Pred::Inline(&pred_v, cside),
17280 Some(luma_tx_type),
17281 None,
17282 fctx,
17283 )?;
17284 u_grid = ug;
17285 v_grid = vg;
17286 }
17287 }
17288 drop(restore);
17289 // lane-av1chromarect: when the chroma plane block was walked as SEVERAL
17290 // transform units, each unit stamped its own span through
17291 // `record_mi_chroma` and the whole-block stamp below would overwrite them
17292 // with one state (class `override-slot-on-one-arm`). libaom keeps the
17293 // per-unit above/left contexts distinct; the next block's first unit
17294 // reads them.
17295 // `!skip` matters: a SKIPPED strip reads no chroma unit at all (its whole
17296 // chroma plane block is one `push_mc_rect` of `ZERO_RESIDUAL`), so no
17297 // per-unit `record_mi_chroma` ran and the whole-block chroma stamp below
17298 // is still the only one that happens.
17299 let chroma_split_units = !skip && (cw.min(32) != cw || ch.min(32) != ch);
17300 if leaves.is_some() {
17301 if chroma_split_units {
17302 neighbours.record_split_luma_rect_mi_modes((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED);
17303 } else {
17304 neighbours.record_split_luma_rect_mi(
17305 (mi_r, mi_c),
17306 bw,
17307 bh,
17308 DC_PRED,
17309 DC_PRED,
17310 [&u_grid, &v_grid],
17311 );
17312 }
17313 } else if chroma_split_units {
17314 neighbours.record_rect_mi_luma_only((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &luma_grid);
17315 } else {
17316 neighbours.record_rect_mi(
17317 (mi_r, mi_c),
17318 bw,
17319 bh,
17320 DC_PRED,
17321 DC_PRED,
17322 &[&luma_grid, &u_grid, &v_grid],
17323 );
17324 }
17325 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17326 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17327 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17328 neighbours.fill_lf_grid_rect(
17329 (mi_r, mi_c),
17330 bw / MI,
17331 bh / MI,
17332 bw.min(64) as u8,
17333 bh.min(64) as u8,
17334 0,
17335 fctx,
17336 );
17337 record_intrabc_mi_rect(
17338 mi_r,
17339 mi_c,
17340 bw / MI,
17341 bh / MI,
17342 Some((dv_row, dv_col)),
17343 neighbours,
17344 fctx,
17345 );
17346 let _ = luma_tx_type;
17347 Ok(())
17348}
17349
17350/// The chroma plane block of a 128-root intra-BC HORZ/VERT strip when that
17351/// plane block needs MORE THAN ONE transform unit -- the 4:4:4 cell, and the
17352/// 4:2:0 cell of a strip with a 128-px axis.
17353///
17354/// libaom never forms a 64-point CHROMA transform. `get_vartx_max_txsize`
17355/// (blockd.h:1447) returns `av1_get_adjusted_tx_size(max_txsize_rect_lookup
17356/// [plane_bsize])` and `av1_get_adjusted_tx_size` maps `TX_32X64`/`TX_64X32`
17357/// to `TX_32X32`; `decode_token_recon_block` (decodeframe.c:994-1004) then
17358/// steps the plane block by that size's mi units, and
17359/// `decode_reconstruct_tx`'s `tx_size == plane_tx_size || plane` arm never
17360/// recurses for chroma -- the same statement from the other side. So a 4:4:4
17361/// 32x64 chroma plane block is TWO stacked `TX_32X32` units, each with its
17362/// own eob, its own scan and its own coefficient context, NOT one 32x64 unit
17363/// whose coded corner happens to be 32x32: `av1_get_max_eob`'s 64-axis
17364/// truncation is a LUMA rule, and a chroma plane block is never 64 points
17365/// long to begin with.
17366///
17367/// That is exactly the tiling [`read_inter_rect_chroma`] implements
17368/// (`(write_chroma_w.min(32), write_chroma_h.min(32))` and the `nx * ny`
17369/// walk); this is the same walk for a caller that keeps its own grid
17370/// assembly and neighbour recording. The single-unit case is deliberately
17371/// NOT routed through here, so at 4:2:0 and at every 4:4:4 shape below 64
17372/// the caller keeps its own one-unit read verbatim.
17373#[allow(clippy::too_many_arguments)]
17374fn read_intrabc_rect_chroma_split(
17375 dec: &mut SymbolDecoder,
17376 cdfs: &mut Cdfs,
17377 neighbours: &mut Neighbours,
17378 (mi_r, mi_c): (usize, usize),
17379 (cpx, cpy): (usize, usize),
17380 (cw, ch): (usize, usize),
17381 cside: usize,
17382 pred_u: &[u16],
17383 pred_v: &[u16],
17384 leaf_tx_types: &[(usize, usize, usize, usize, TxType)],
17385 luma_tx_type: TxType,
17386 u: &mut PlaneBuf<'static>,
17387 v: &mut PlaneBuf<'static>,
17388 fctx: &crate::decode::FrameCtx,
17389) -> Result<(Grid, Grid)> {
17390 let (uw, uh) = (cw.min(32), ch.min(32));
17391 let (nx, ny) = (cw / uw, ch / uh);
17392 let set = rect_inter_chroma_set(uw, uh)?;
17393 let assembled_h = ch.max(cside);
17394 let mut assembled: [Vec<i32>; 2] = [
17395 vec![0i32; cside * assembled_h],
17396 vec![0i32; cside * assembled_h],
17397 ];
17398 for plane_idx in 1..=2 {
17399 let (src, buf) = if plane_idx == 1 {
17400 (pred_u, &mut *u)
17401 } else {
17402 (pred_v, &mut *v)
17403 };
17404 for cu_row in 0..ny {
17405 for cu_col in 0..nx {
17406 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
17407 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
17408 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
17409 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
17410 let cu_pred = Pred::Inline(src, cside).offset(cu_row * uh * cside + cu_col * uw);
17411 // libaom's `av1_get_tx_type` (blockd.h:1287) reads
17412 // `xd->tx_type_map` at the chroma unit's OWN position scaled
17413 // back to luma, so a unit sitting over a luma leaf that coded
17414 // nothing takes that leaf's stamp, not the block-level one.
17415 let rel_mi = (cu_mi.0 - mi_r, cu_mi.1 - mi_c);
17416 let inherit_tx_type =
17417 covering_leaf_tx_type(leaf_tx_types, rel_mi).or(Some(luma_tx_type));
17418 let cu_grid = read_inter_plane_rect(
17419 dec,
17420 cdfs,
17421 set,
17422 (uw, uh),
17423 cside,
17424 plane_idx,
17425 cu_around[plane_idx],
17426 0,
17427 buf,
17428 cu_x,
17429 cu_y,
17430 cu_pred,
17431 inherit_tx_type,
17432 // `get_txb_ctx`: plus 10 when the plane block is bigger
17433 // than the transform -- the same offset-3 convention
17434 // `read_inter_rect_chroma` passes on this arm.
17435 Some(3),
17436 fctx,
17437 )?
17438 .0;
17439 // Immediately, so the next unit of this block reads this one's
17440 // coefficient context (libaom updates the chroma above/left
17441 // contexts per unit).
17442 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
17443 let dst = &mut assembled[plane_idx - 1];
17444 for rr in 0..uh {
17445 let start = (cu_row * uh + rr) * cside + cu_col * uw;
17446 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
17447 }
17448 }
17449 }
17450 }
17451 let [ug, vg] = assembled;
17452 Ok((Grid::Own(ug), Grid::Own(vg)))
17453}
17454
17455fn predict_intrabc_window(
17456 plane: &PlaneBuf<'_>,
17457 px: usize,
17458 py: usize,
17459 w: usize,
17460 h: usize,
17461 dv_col: i32,
17462 dv_row: i32,
17463 luma: bool,
17464 stride: usize,
17465 fctx: &crate::decode::FrameCtx,
17466) -> Vec<u16> {
17467 let mut dense = vec![0u16; w * h];
17468 mc::predict_with_filter(
17469 &plane.data,
17470 plane.width,
17471 plane.true_width,
17472 plane.true_height,
17473 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
17474 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
17475 w,
17476 h,
17477 mc::InterpFilterKind::Bilinear,
17478 &mut dense,
17479 fctx,
17480 );
17481 let mut laid = vec![0u16; stride * stride];
17482 for row in 0..h {
17483 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
17484 }
17485 laid
17486}
17487
17488struct ReducedTxRestore<'a> {
17489 fctx: &'a crate::decode::FrameCtx,
17490 saved_reduced: bool,
17491 saved_tx: bool,
17492}
17493impl Drop for ReducedTxRestore<'_> {
17494 fn drop(&mut self) {
17495 self.fctx
17496 .reduced_tx_set_inter
17497 .with(|c| c.set(self.saved_reduced));
17498 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
17499 }
17500}
17501
17502/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
17503///
17504/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
17505/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
17506/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
17507/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
17508/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
17509/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
17510/// strip's own footprint, copied from this strip's DV. The block is
17511/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
17512/// the luma unit's coded `tx_type`.
17513///
17514/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
17515/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
17516/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
17517/// would code chroma on every strip.
17518#[allow(clippy::too_many_arguments)]
17519fn decode_rect4_16_intrabc(
17520 dec: &mut SymbolDecoder,
17521 cdfs: &mut Cdfs,
17522 neighbours: &mut Neighbours,
17523 lmi: (usize, usize),
17524 horz: bool,
17525 has_chroma: bool,
17526 skip: bool,
17527 (dv_row, dv_col): (i32, i32),
17528 y: &mut PlaneBuf<'static>,
17529 u: &mut PlaneBuf<'static>,
17530 v: &mut PlaneBuf<'static>,
17531 base_q_idx: u8,
17532 tx_select: bool,
17533 reduced_tx_set: bool,
17534 fctx: &crate::decode::FrameCtx,
17535) -> Result<(usize, Option<usize>, (usize, usize))> {
17536 let _ = base_q_idx;
17537 hit!(RECT4_16_INTRABC_HITS);
17538 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17539 let (mi_w, mi_h) = (bw / MI, bh / MI);
17540 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17541 let side = bw.max(bh);
17542 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
17543 // publishes `reduced_tx_set` into it; set it here too so a caller that
17544 // passed the bit explicitly cannot disagree with the set we read.
17545 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17546 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17547 let restored = scopeguard_reduced(fctx, saved_reduced);
17548
17549 flush_recon(fctx, y, u, v);
17550 let mut pred_y_dense = vec![0u16; bw * bh];
17551 mc::predict_with_filter(
17552 &y.data,
17553 y.width,
17554 y.true_width,
17555 y.true_height,
17556 mv_to_q4(px, dv_col, 0),
17557 mv_to_q4(py, dv_row, 0),
17558 bw,
17559 bh,
17560 mc::InterpFilterKind::Bilinear,
17561 &mut pred_y_dense,
17562 fctx,
17563 );
17564 let mut pred_y = vec![0u16; side * side];
17565 for row in 0..bh {
17566 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
17567 }
17568
17569 // lane-av1444rect r2 (the class this lane named, second instance): the
17570 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
17571 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
17572 // unconditionally true -- the strip is its own chroma reference, there is
17573 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
17574 // (VERT_4) at the strip's own origin, with its coefficient context read
17575 // over that same extent. The old constants instead predicted and coded an
17576 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
17577 //
17578 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
17579 // --enable-palette=1 --cq-level=60 --min-partition-size=4
17580 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
17581 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
17582 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
17583 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
17584 // twin of the same recipe is byte-exact.
17585 //
17586 // 4:2:0 and 4:2:2 keep every constant below verbatim -- the arm is gated on
17587 // the full ss (0,0), not on a per-axis shift, so `pw / 2` and the literal
17588 // halving are untouched for both.
17589 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
17590 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
17591 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
17592 }
17593 let (pw, ph) = if own444 {
17594 (bw, bh)
17595 } else if horz {
17596 (16usize, 8usize)
17597 } else {
17598 (8, 16)
17599 };
17600 let (cw, ch) = if own444 { (bw, bh) } else { (pw / 2, ph / 2) };
17601 let pair_mi = if has_chroma {
17602 if own444 {
17603 lmi
17604 } else if horz {
17605 (lmi.0 - 1, lmi.1)
17606 } else {
17607 (lmi.0, lmi.1 - 1)
17608 }
17609 } else {
17610 lmi
17611 };
17612 let (cpx, cpy) = if has_chroma {
17613 if own444 {
17614 (px, py)
17615 } else {
17616 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
17617 }
17618 } else {
17619 (0, 0)
17620 };
17621 let cside = cw.max(ch);
17622 let (pred_u, pred_v) = if has_chroma {
17623 let mut ud = vec![0u16; cw * ch];
17624 mc::predict_with_filter(
17625 &u.data,
17626 u.width,
17627 u.true_width,
17628 u.true_height,
17629 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17630 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17631 cw,
17632 ch,
17633 mc::InterpFilterKind::Bilinear,
17634 &mut ud,
17635 fctx,
17636 );
17637 let mut us = vec![0u16; cside * cside];
17638 for row in 0..ch {
17639 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
17640 }
17641 let mut vd = vec![0u16; cw * ch];
17642 mc::predict_with_filter(
17643 &v.data,
17644 v.width,
17645 v.true_width,
17646 v.true_height,
17647 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17648 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17649 cw,
17650 ch,
17651 mc::InterpFilterKind::Bilinear,
17652 &mut vd,
17653 fctx,
17654 );
17655 let mut vs = vec![0u16; cside * cside];
17656 for row in 0..ch {
17657 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
17658 }
17659 (us, vs)
17660 } else {
17661 (Vec::new(), Vec::new())
17662 };
17663
17664 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
17665 // false for a key frame, so `read_block_tx_size_rect` would skip the
17666 // symbol; read it here against the parameter the intra path already uses.
17667 // A skipped intrabc block predicts the whole footprint once and codes
17668 // no residual (`decode_token_recon_block`'s inter branch). Lossless
17669 // still forces TX_4X4 when the block is coded.
17670 let leaves = if skip || (!lossless(fctx) && !tx_select) {
17671 None
17672 } else if lossless(fctx) {
17673 let mut leaves = Vec::new();
17674 for row in 0..bh / MI {
17675 for col in 0..bw / MI {
17676 leaves.push((row, col, 4usize, 4usize));
17677 }
17678 }
17679 Some(leaves)
17680 } else {
17681 let ctx = txfm_partition_ctx_rect(
17682 neighbours.above_txfm[lmi.1],
17683 neighbours.left_txfm[lmi.0],
17684 side,
17685 bw,
17686 bh,
17687 );
17688 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17689 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17690 let (rng, _) = dec.debug_state();
17691 eprintln!(
17692 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17693 lmi.0,
17694 lmi.1,
17695 u8::from(split)
17696 );
17697 }
17698 if !split {
17699 None
17700 } else {
17701 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
17702 let mi_cols = 2 * y.true_width.div_ceil(8);
17703 let mi_rows = 2 * y.true_height.div_ceil(8);
17704 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
17705 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
17706 let mut out = Vec::new();
17707 for row in (0..bh / MI).step_by(sub_h / MI) {
17708 for col in (0..bw / MI).step_by(sub_w / MI) {
17709 read_var_tx_size(
17710 dec,
17711 cdfs,
17712 neighbours,
17713 lmi,
17714 side,
17715 (max_w_mi, max_h_mi),
17716 (sub_w, sub_h),
17717 1,
17718 row,
17719 col,
17720 &mut out,
17721 );
17722 }
17723 }
17724 Some(out)
17725 }
17726 };
17727 let (tx_w, tx_h) = leaves
17728 .as_ref()
17729 .and_then(|ls| ls.first())
17730 .map_or((bw, bh), |l| (l.2, l.3));
17731
17732 let mut luma_tx_type = TxType::DctDct;
17733 let luma_grid;
17734 let mut u_grid = Grid::Zero(cw * ch);
17735 let mut v_grid = Grid::Zero(cw * ch);
17736 let chroma_stamped_per_unit;
17737
17738 if skip {
17739 push_mc_rect(
17740 0,
17741 px,
17742 py,
17743 side,
17744 bw,
17745 bh,
17746 Pred::Inline(&pred_y, side),
17747 &ZERO_RESIDUAL[..side * bh],
17748 fctx,
17749 );
17750 luma_grid = Grid::Zero(bw * bh);
17751 if has_chroma {
17752 push_mc_rect(
17753 1,
17754 cpx,
17755 cpy,
17756 cside,
17757 cw,
17758 ch,
17759 Pred::Inline(&pred_u, cside),
17760 &ZERO_RESIDUAL[..cside * ch],
17761 fctx,
17762 );
17763 push_mc_rect(
17764 2,
17765 cpx,
17766 cpy,
17767 cside,
17768 cw,
17769 ch,
17770 Pred::Inline(&pred_v, cside),
17771 &ZERO_RESIDUAL[..cside * ch],
17772 fctx,
17773 );
17774 }
17775 chroma_stamped_per_unit = false;
17776 } else if let Some(ls) = leaves.as_ref() {
17777 if lossless(fctx) {
17778 for &(row, col, _tw, _th) in ls {
17779 let tu_mi = (lmi.0 + row, lmi.1 + col);
17780 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17781 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17782 let (g, _) = read_inter_plane(
17783 dec,
17784 cdfs,
17785 if reduced_tx_set {
17786 TxbSet::Luma4Inter
17787 } else {
17788 TxbSet::Luma4InterSet1
17789 },
17790 &default_scan(4),
17791 0,
17792 neighbours.around_mi(tu_mi, 4)[0],
17793 0,
17794 y,
17795 tu_px,
17796 tu_py,
17797 4,
17798 base_q_idx,
17799 tu_pred,
17800 None,
17801 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
17802 fctx,
17803 )?;
17804 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
17805 }
17806 } else {
17807 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17808 let tu_mi = (lmi.0 + row, lmi.1 + col);
17809 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17810 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17811 let (g, tt) = if tw == th {
17812 read_inter_plane(
17813 dec,
17814 cdfs,
17815 inter_txbset_for(tw, reduced_tx_set),
17816 &default_scan(tw.min(32)),
17817 0,
17818 neighbours.around_mi(tu_mi, tw)[0],
17819 0,
17820 y,
17821 tu_px,
17822 tu_py,
17823 tw,
17824 base_q_idx,
17825 tu_pred,
17826 None,
17827 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17828 fctx,
17829 )?
17830 } else {
17831 read_inter_plane_rect(
17832 dec,
17833 cdfs,
17834 rect_inter_luma_set(tw, th, fctx)?,
17835 (tw, th),
17836 side,
17837 0,
17838 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17839 0,
17840 y,
17841 tu_px,
17842 tu_py,
17843 tu_pred,
17844 None,
17845 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17846 fctx,
17847 )?
17848 };
17849 if idx == 0 {
17850 luma_tx_type = tt;
17851 }
17852 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17853 }
17854 }
17855 luma_grid = Grid::Zero(bw * bh);
17856 chroma_stamped_per_unit = has_chroma && lossless(fctx);
17857 if has_chroma && lossless(fctx) {
17858 let (mut uo, mut vo) = (Vec::new(), Vec::new());
17859 read_inter_chroma_lossless(
17860 dec,
17861 cdfs,
17862 neighbours,
17863 u,
17864 v,
17865 Pred::Inline(&pred_u, cside),
17866 Pred::Inline(&pred_v, cside),
17867 pair_mi,
17868 (cpx, cpy),
17869 (0, 0),
17870 (cw, ch),
17871 (cw, ch),
17872 cside,
17873 0,
17874 base_q_idx,
17875 &mut uo,
17876 &mut vo,
17877 fctx,
17878 )?;
17879 u_grid = if uo.is_empty() {
17880 Grid::Zero(cw * ch)
17881 } else {
17882 Grid::Own(uo)
17883 };
17884 v_grid = if vo.is_empty() {
17885 Grid::Zero(cw * ch)
17886 } else {
17887 Grid::Own(vo)
17888 };
17889 } else if has_chroma {
17890 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17891 let (ug, _) = read_inter_plane_rect(
17892 dec,
17893 cdfs,
17894 rect_inter_chroma_set(cw, ch)?,
17895 (cw, ch),
17896 cside,
17897 1,
17898 around[1],
17899 0,
17900 u,
17901 cpx,
17902 cpy,
17903 Pred::Inline(&pred_u, cside),
17904 Some(luma_tx_type),
17905 None,
17906 fctx,
17907 )?;
17908 u_grid = ug;
17909 let (vg, _) = read_inter_plane_rect(
17910 dec,
17911 cdfs,
17912 rect_inter_chroma_set(cw, ch)?,
17913 (cw, ch),
17914 cside,
17915 2,
17916 around[2],
17917 0,
17918 v,
17919 cpx,
17920 cpy,
17921 Pred::Inline(&pred_v, cside),
17922 Some(luma_tx_type),
17923 None,
17924 fctx,
17925 )?;
17926 v_grid = vg;
17927 }
17928 } else {
17929 let around = neighbours.around_mi_rect(lmi, bw, bh);
17930 let (g, tt) = read_inter_plane_rect(
17931 dec,
17932 cdfs,
17933 rect_inter_luma_set(bw, bh, fctx)?,
17934 (bw, bh),
17935 side,
17936 0,
17937 around[0],
17938 0,
17939 y,
17940 px,
17941 py,
17942 Pred::Inline(&pred_y, side),
17943 None,
17944 None,
17945 fctx,
17946 )?;
17947 luma_tx_type = tt;
17948 luma_grid = g;
17949 chroma_stamped_per_unit = false;
17950 if has_chroma {
17951 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17952 let (ug, _) = read_inter_plane_rect(
17953 dec,
17954 cdfs,
17955 rect_inter_chroma_set(cw, ch)?,
17956 (cw, ch),
17957 cside,
17958 1,
17959 around[1],
17960 0,
17961 u,
17962 cpx,
17963 cpy,
17964 Pred::Inline(&pred_u, cside),
17965 Some(luma_tx_type),
17966 None,
17967 fctx,
17968 )?;
17969 u_grid = ug;
17970 let (vg, _) = read_inter_plane_rect(
17971 dec,
17972 cdfs,
17973 rect_inter_chroma_set(cw, ch)?,
17974 (cw, ch),
17975 cside,
17976 2,
17977 around[2],
17978 0,
17979 v,
17980 cpx,
17981 cpy,
17982 Pred::Inline(&pred_v, cside),
17983 Some(luma_tx_type),
17984 None,
17985 fctx,
17986 )?;
17987 v_grid = vg;
17988 }
17989 }
17990 drop(restored);
17991
17992 if leaves.is_none() {
17993 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
17994 }
17995 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
17996 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17997 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17998 for cell in 0..mi_w {
17999 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18000 *slot = bw as u8;
18001 }
18002 }
18003 for cell in 0..mi_h {
18004 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18005 *slot = bh as u8;
18006 }
18007 }
18008 let mut last_uv = None;
18009 if has_chroma {
18010 hit!(RECT4_16_CHROMA_HITS);
18011 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
18012 if !chroma_stamped_per_unit {
18013 let u_state = neighbour_state(&u_grid);
18014 let v_state = neighbour_state(&v_grid);
18015 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18016 let bound_h = round_up_even(neighbours.mi_rows);
18017 let bound_w = round_up_even(neighbours.mi_cols);
18018 for cell in 0..(ph / MI) {
18019 if pair_mi.0 + cell < bound_h
18020 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18021 {
18022 slot[1] = u_state;
18023 slot[2] = v_state;
18024 }
18025 }
18026 for cell in 0..(pw / MI) {
18027 if pair_mi.1 + cell < bound_w
18028 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18029 {
18030 slot[1] = u_state;
18031 slot[2] = v_state;
18032 }
18033 }
18034 }
18035 last_uv = Some(DC_PRED);
18036 }
18037 if horz {
18038 hit!(RECT4_16_HORZ_HITS);
18039 } else {
18040 hit!(RECT4_16_VERT_HITS);
18041 }
18042 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
18043 if leaves.is_none() {
18044 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
18045 // with `skip && is_inter`, or the unsplit unit). A split tree already
18046 // published per leaf inside `read_var_tx_size`.
18047 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18048 }
18049 record_intrabc_mi_rect(
18050 lmi.0,
18051 lmi.1,
18052 mi_w,
18053 mi_h,
18054 Some((dv_row, dv_col)),
18055 neighbours,
18056 fctx,
18057 );
18058 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
18059}
18060
18061/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
18062/// including through `?`.
18063struct ReducedRestore<'a> {
18064 fctx: &'a crate::decode::FrameCtx,
18065 saved: bool,
18066}
18067impl Drop for ReducedRestore<'_> {
18068 fn drop(&mut self) {
18069 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
18070 }
18071}
18072fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
18073 ReducedRestore { fctx, saved }
18074}
18075
18076#[allow(clippy::too_many_arguments)]
18077fn decode_rect4_16_strip(
18078 dec: &mut SymbolDecoder,
18079 cdfs: &mut Cdfs,
18080 neighbours: &mut Neighbours,
18081 lmi: (usize, usize),
18082 horz: bool,
18083 has_chroma: bool,
18084 prev: Option<((usize, usize), usize)>,
18085 y: &mut PlaneBuf<'static>,
18086 u: &mut PlaneBuf<'static>,
18087 v: &mut PlaneBuf<'static>,
18088 enable_filter_intra: bool,
18089 allow_screen_content_tools: bool,
18090 base_q_idx: u8,
18091 tx_select: bool,
18092 reduced_tx_set: bool,
18093 fctx: &crate::decode::FrameCtx,
18094) -> Result<(usize, Option<usize>, (usize, usize))> {
18095 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
18096 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
18097 let (mi_w, mi_h) = (bw / MI, bh / MI);
18098 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
18099 let mut last_uv_mode: Option<usize> = None;
18100 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
18101 // aliases all four strips onto one entry, so the mi-exact map wins and
18102 // the previous strip stands in on the split axis.
18103 let mut above_mode = neighbours.above_mode[c];
18104 let mut left_mode = neighbours.left_mode[r];
18105 if let Some(((pr, pc), pmode)) = prev {
18106 if pc == lmi.1 && lmi.0 == pr + mi_h {
18107 above_mode = pmode;
18108 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
18109 left_mode = pmode;
18110 }
18111 }
18112 let (above_mode, left_mode) =
18113 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
18114 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
18115 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
18116 // off CDF row 0 and every cache hit off an empty cache.
18117 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
18118 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
18119 let (
18120 skip,
18121 mode,
18122 angle_delta_y,
18123 uv_mode,
18124 angle_delta_uv,
18125 alpha,
18126 filter_intra,
18127 palette_y,
18128 palette_uv,
18129 intrabc,
18130 ) = read_intra_mode_rect(
18131 dec,
18132 cdfs,
18133 above_mode,
18134 left_mode,
18135 true,
18136 has_chroma,
18137 bw,
18138 bh,
18139 enable_filter_intra,
18140 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
18141 allow_screen_content_tools,
18142 Some((palette_ctx, &palette_cache)),
18143 &palette_uv_cache,
18144 lmi.0,
18145 lmi.1,
18146 fctx,
18147 )?;
18148 if let Some(dv) = intrabc {
18149 return decode_rect4_16_intrabc(
18150 dec,
18151 cdfs,
18152 neighbours,
18153 lmi,
18154 horz,
18155 has_chroma,
18156 skip,
18157 dv,
18158 y,
18159 u,
18160 v,
18161 base_q_idx,
18162 tx_select,
18163 reduced_tx_set,
18164 fctx,
18165 );
18166 }
18167 if palette_y.is_some() || palette_uv.is_some() {
18168 hit!(RECT4_PALETTE_HITS);
18169 }
18170 // The colour-index map through the base colours IS the prediction.
18171 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
18172 // chroma transform this closing strip codes.
18173 let palette_y_buf: Option<Vec<u16>> = palette_y
18174 .as_ref()
18175 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
18176 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
18177 (
18178 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18179 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18180 )
18181 });
18182 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
18183 if smooth_neighbor {
18184 hit!(SMOOTH_LUMA_HITS);
18185 }
18186 if filter_intra.is_some() {
18187 hit!(FILTER_INTRA_RECT_HITS);
18188 }
18189 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
18190 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
18191 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
18192 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
18193 // lane-av1mixloss: the lossless-segment early return
18194 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
18195 // lossless-segment strip codes no depth symbol here either (class
18196 // sweep of the sub8 leaf's fix).
18197 let depth = if tx_select && !lossless(fctx) {
18198 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
18199 // (`get_tx_size_context`, libaom `pred_common.h:342`).
18200 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
18201 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
18202 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18203 eprintln!(
18204 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
18205 lmi.0,
18206 lmi.1,
18207 dec.debug_state().0
18208 );
18209 }
18210 d
18211 } else {
18212 0
18213 };
18214 if depth != 0 {
18215 hit!(TX_DEPTH_HITS);
18216 hit!(RECT4_16_SPLIT_HITS);
18217 }
18218 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18219 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18220 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18221 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
18222 if depth != 0 || lossless(fctx) {
18223 // [`decode_rect_split`]'s per-unit walk, inlined because the
18224 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
18225 // the strip (that function codes one chroma transform per block).
18226 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
18227 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
18228 // unit predicts off the units before it in raster order.
18229 let rect_unit = tx_w != tx_h;
18230 let zero_tu = vec![0i32; tx_w * tx_h];
18231 for tu_row in 0..bh / tx_h {
18232 for tu_col in 0..bw / tx_w {
18233 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
18234 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
18235 let tu_reach =
18236 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
18237 if let Some(b) = &palette_y_buf {
18238 let tu_buf: Vec<u16> = (0..tx_h)
18239 .flat_map(|i| {
18240 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
18241 b[base..base + tx_w].iter().copied()
18242 })
18243 .collect();
18244 set_palette_pred(tu_buf, fctx);
18245 }
18246 if skip {
18247 push_intra_rect(
18248 0,
18249 tu_px,
18250 tu_py,
18251 tx_w,
18252 tx_h,
18253 mode,
18254 angle_delta_y,
18255 tu_reach,
18256 &zero_tu,
18257 None,
18258 filter_intra,
18259 smooth_neighbor,
18260 fctx,
18261 );
18262 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
18263 } else if rect_unit {
18264 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
18265 // 32 coded positions and the `TX_4X4` `tx_type` row:
18266 // exactly [`TxbSet::LumaRect4x8`].
18267 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
18268 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
18269 let set = if reduced_tx_set {
18270 TxbSet::LumaRect4x8
18271 } else {
18272 TxbSet::LumaRect4x8Set1
18273 };
18274 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
18275 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18276 let (tu_grid, tu_tx_type) = read_coeffs_rect(
18277 dec,
18278 &mut coding,
18279 tu_scan,
18280 tx_w,
18281 tx_h,
18282 tu_skip_ctx,
18283 dc_sign_ctx(tu_around.2),
18284 TxType::DctDct,
18285 0,
18286 )?;
18287 let residual = dequant_and_inverse_typed_wh(
18288 &tu_grid,
18289 tx_w,
18290 tx_h,
18291 crate::decode::bit_depth(fctx),
18292 block_q_idx(fctx),
18293 plane_q_delta(0, fctx).0,
18294 plane_q_delta(0, fctx).1,
18295 tu_tx_type,
18296 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
18297 );
18298 push_intra_rect(
18299 0,
18300 tu_px,
18301 tu_py,
18302 tx_w,
18303 tx_h,
18304 mode,
18305 angle_delta_y,
18306 tu_reach,
18307 &residual,
18308 None,
18309 filter_intra,
18310 smooth_neighbor,
18311 fctx,
18312 );
18313 if tu_grid.iter().any(|&l| l != 0) {
18314 hit!(RECT4_16_COEFF_HITS);
18315 }
18316 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
18317 } else {
18318 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
18319 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
18320 let tu_grid = read_plane(
18321 dec,
18322 cdfs,
18323 txbset_for(tx_w, reduced_tx_set),
18324 default_scan(tx_w),
18325 0,
18326 tu_around,
18327 mode,
18328 mode,
18329 angle_delta_y,
18330 tu_reach,
18331 y,
18332 tu_px,
18333 tu_py,
18334 tx_w,
18335 tx_w,
18336 base_q_idx,
18337 None,
18338 filter_intra,
18339 Some(tu_skip_ctx),
18340 smooth_neighbor,
18341 fctx,
18342 )?;
18343 if tu_grid.iter().any(|&l| l != 0) {
18344 hit!(RECT4_16_COEFF_HITS);
18345 }
18346 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
18347 }
18348 }
18349 }
18350 } else {
18351 let levels = if skip {
18352 let zeros = Grid::Zero(bw * bh);
18353 if let Some(b) = &palette_y_buf {
18354 set_palette_pred(b.clone(), fctx);
18355 }
18356 push_intra_rect(
18357 0,
18358 px,
18359 py,
18360 bw,
18361 bh,
18362 mode,
18363 angle_delta_y,
18364 reach,
18365 &zeros,
18366 None,
18367 filter_intra,
18368 smooth_neighbor,
18369 fctx,
18370 );
18371 zeros
18372 } else {
18373 // The strip's luma TU *is* the strip (`plane_bsize ==
18374 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
18375 // `txb_skip_ctx` at 0.
18376 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
18377 let set = if reduced_tx_set {
18378 TxbSet::LumaRect16x4
18379 } else {
18380 TxbSet::LumaRect16x4Set1
18381 };
18382 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18383 let (levels, tx_type) = read_coeffs_rect(
18384 dec,
18385 &mut coding,
18386 scan,
18387 bw,
18388 bh,
18389 0,
18390 dc_sign_ctx(around.2),
18391 TxType::DctDct,
18392 0,
18393 )?;
18394 let residual = dequant_and_inverse_typed_wh(
18395 &levels,
18396 bw,
18397 bh,
18398 crate::decode::bit_depth(fctx),
18399 block_q_idx(fctx),
18400 plane_q_delta(0, fctx).0,
18401 plane_q_delta(0, fctx).1,
18402 tx_type,
18403 block_iqmatrix(fctx, 0, bw, bh, tx_type),
18404 );
18405 if let Some(b) = &palette_y_buf {
18406 set_palette_pred(b.clone(), fctx);
18407 }
18408 push_intra_rect(
18409 0,
18410 px,
18411 py,
18412 bw,
18413 bh,
18414 mode,
18415 angle_delta_y,
18416 reach,
18417 &residual,
18418 None,
18419 filter_intra,
18420 smooth_neighbor,
18421 fctx,
18422 );
18423 hit!(RECT4_16_COEFF_HITS);
18424 levels
18425 };
18426 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
18427 }
18428 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18429 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18430 // `update_partition_context` writes `partition_context_lookup[
18431 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
18432 // the left (mirrored under VERT_4).
18433 for cell in 0..mi_w {
18434 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18435 *slot = bw as u8;
18436 }
18437 }
18438 for cell in 0..mi_h {
18439 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18440 *slot = bh as u8;
18441 }
18442 }
18443 if has_chroma {
18444 hit!(RECT4_16_CHROMA_HITS);
18445 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
18446 // own chroma reference and codes its own 16x4 / 4x16 chroma
18447 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
18448 // ss 0/0, so the neighbour reads below anchor at the strip.)
18449 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
18450 (lmi, bw, bh)
18451 } else if ss_y(fctx) == 0 && horz {
18452 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
18453 // 16x4 strip is its own chroma reference (`is_chroma_reference`
18454 // at ss(1,0): bh == 1 mi, so the row clause reduces to
18455 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
18456 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
18457 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
18458 // the pair merge below -- its own chroma block
18459 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
18460 // walk proved such leaves exist, and libaom codes the pair's
18461 // chroma from the closing strip; the chunk lives in the
18462 // `chroma422_pair16` arm below.)
18463 (lmi, bw, bh)
18464 } else if horz {
18465 ((lmi.0 - 1, lmi.1), 16, 8)
18466 } else {
18467 ((lmi.0, lmi.1 - 1), 8, 16)
18468 };
18469 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
18470 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
18471 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
18472 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
18473 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
18474 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
18475 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
18476 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
18477 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
18478 // `decode_token_recon_block` walks unit_width =
18479 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
18480 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
18481 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
18482 // walks per unit: `predict_and_reconstruct_intra_block` predicts
18483 // every unit regardless of `skip_txfm`.
18484 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
18485 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18486 DC_PRED
18487 } else {
18488 uv_mode
18489 };
18490 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
18491 hit!(RECT4_16_CHROMA_DIR_HITS);
18492 }
18493 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
18494 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
18495 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
18496 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
18497 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
18498 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
18499 // the pair's top-left luma mi, never this leaf's odd row/column.
18500 // Reading `lmi` here named the leaf directly above (a non-chroma
18501 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
18502 // SMOOTH neighbour: filt_type 0 instead of 1 turned
18503 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
18504 // directional chroma strip, moving 4 samples by 1.
18505 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
18506 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
18507 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
18508 // counter's mirror of the snapping form, and the shipped read offsets
18509 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
18510 //
18511 // lane-av1leftwit: this mirror is NOT evidence about the left read's
18512 // `+ss_y` term, whatever a report once said. It reads the leaf's own
18513 // (odd) mi row, which no decode call site does -- every one of them
18514 // uses the snapping form, whose base row is even -- and its result
18515 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
18516 // and worth keeping (the pair's chroma-reference read against the
18517 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
18518 // so it stays; the decode path's own reach for the `+ss_y` term is
18519 // `uv_left_1mi_split_hits()`.
18520 if smooth_neighbor_uv
18521 != neighbours.smooth_uv_neighbour_unsnapped(
18522 lmi.0,
18523 lmi.1,
18524 r,
18525 c,
18526 ss_x(fctx),
18527 ss_y(fctx),
18528 false,
18529 )
18530 {
18531 hit!(RECT4_16_UV_PAIR_FILT_HITS);
18532 }
18533 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
18534 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
18535 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
18536 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
18537 // the rect here consumed one symbol block too few and desynced
18538 // the next strip's `skip` (measured: lossless sb128 320x240,
18539 // mi(1,20) uv_mode matched, the following skip did not).
18540 let lossless_pair = lossless(fctx);
18541 let (u_levels, v_levels) = if lossless_pair {
18542 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
18543 if skip {
18544 for plane in 1..3usize {
18545 for rr in 0..ch / 4 {
18546 for cc in 0..cw / 4 {
18547 let (ox, oy) = (cc * 4, rr * 4);
18548 // The unit's origin and extent in LUMA pixels: `<< ss`
18549 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
18550 // at 4:4:4 -- the same form as the block-walk sibling
18551 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
18552 // only right at ss (1,1): at 4:4:4 it claims a 4x4
18553 // chroma unit is 8x8 luma, so `of_tu`'s
18554 // `col_off + tx_w < bw` test answers against a
18555 // footprint twice the real one and every unit past
18556 // the block's midpoint wrongly reports
18557 // `above_right = false` -- a directional chroma
18558 // strip then predicts from a neighbour libaom
18559 // never reads (measured: key frame 0, 4:4:4 lossless
18560 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
18561 // entropy bit-identical over 351109 EC_SYMR reads).
18562 let cu_reach = tu_reach(
18563 pw,
18564 ph,
18565 ox << ss_x(fctx),
18566 oy << ss_y(fctx),
18567 4 << ss_x(fctx),
18568 pair_reach,
18569 ppx,
18570 ppy,
18571 y.width,
18572 y.height,
18573 fctx,
18574 );
18575 if let Some((ub, vb)) = &palette_uv_bufs {
18576 let buf = if plane == 1 { ub } else { vb };
18577 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18578 }
18579 push_intra(
18580 plane,
18581 cpx + ox,
18582 cpy + oy,
18583 4,
18584 uv_predict_mode,
18585 angle_delta_uv,
18586 cu_reach,
18587 &ZERO_RESIDUAL[..16],
18588 None,
18589 None,
18590 smooth_neighbor_uv,
18591 fctx,
18592 );
18593 let cu_mi = (
18594 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18595 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18596 );
18597 neighbours.record_mi_chroma(
18598 cu_mi,
18599 4 << ss_x(fctx),
18600 4 << ss_y(fctx),
18601 plane,
18602 &ZERO_RESIDUAL[..16],
18603 );
18604 }
18605 }
18606 }
18607 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18608 } else {
18609 let scan4 = default_scan(4);
18610 // `get_txb_ctx`: offset 10 (our tables store it at +3)
18611 // when the plane block is larger than the transform.
18612 let offset = Some(3usize);
18613 let mut uo = vec![0i32; cw * ch];
18614 let mut vo = vec![0i32; cw * ch];
18615 for plane in 1..3usize {
18616 for rr in 0..ch / 4 {
18617 for cc in 0..cw / 4 {
18618 let (ox, oy) = (cc * 4, rr * 4);
18619 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
18620 continue;
18621 }
18622 // The unit's stamp is its own span: aom
18623 // `av1_set_entropy_contexts` (blockd.c:29)
18624 // memsets exactly `tx_size_wide_unit` x
18625 // `tx_size_high_unit` cells at the unit's own
18626 // `(aoff, loff)` -- for TX_4X4 ONE above cell
18627 // and ONE left cell. `(oy / 2, ox / 2)` +
18628 // `(8, 8)` is the 4:2:0 subsampled form (one
18629 // chroma cell = 8 luma px = 2 mi cells); at
18630 // 4:4:4 a unit is ONE mi cell, and the 2x2
18631 // smear let a 4-wide strip's later units
18632 // overwrite the NEXT COLUMN's above cell with
18633 // their own state -- a column aom never sees
18634 // this block write -- so the following block's
18635 // `all_zero` read the wrong `txb_skip` row
18636 // (frame-0 read #452, the llkf named gap).
18637 let cu_mi = (
18638 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18639 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18640 );
18641 // One luma-mi cell: the chroma entropy arrays
18642 // are subsampled, and our bands replicate that
18643 // one entry over the unit's two cells
18644 // (`read_intra_chroma_lossless`).
18645 let cu_around = neighbours.around_mi(cu_mi, MI);
18646 // Same ss-aware luma footprint as the skip arm
18647 // above -- `ox * 2 / 8` is the 4:2:0-only form and
18648 // mis-answers `of_tu` at 4:4:4 (see there).
18649 let cu_reach = tu_reach(
18650 pw,
18651 ph,
18652 ox << ss_x(fctx),
18653 oy << ss_y(fctx),
18654 4 << ss_x(fctx),
18655 pair_reach,
18656 ppx,
18657 ppy,
18658 y.width,
18659 y.height,
18660 fctx,
18661 );
18662 if let Some((ub, vb)) = &palette_uv_bufs {
18663 let buf = if plane == 1 { ub } else { vb };
18664 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18665 }
18666 let buf: &mut PlaneBuf<'static> =
18667 if plane == 1 { &mut *u } else { &mut *v };
18668 let cu_grid = read_plane(
18669 dec,
18670 cdfs,
18671 TxbSet::Chroma4,
18672 &scan4,
18673 plane,
18674 cu_around[plane],
18675 mode,
18676 uv_predict_mode,
18677 angle_delta_uv,
18678 cu_reach,
18679 buf,
18680 cpx + ox,
18681 cpy + oy,
18682 4,
18683 4,
18684 base_q_idx,
18685 None,
18686 None,
18687 offset,
18688 smooth_neighbor_uv,
18689 fctx,
18690 )?;
18691 neighbours.record_mi_chroma(
18692 cu_mi,
18693 4 << ss_x(fctx),
18694 4 << ss_y(fctx),
18695 plane,
18696 &cu_grid,
18697 );
18698 hit!(CHROMA_SPLIT_TX_HITS);
18699 let dst = if plane == 1 { &mut uo } else { &mut vo };
18700 for row in 0..4 {
18701 let start = (oy + row) * cw + ox;
18702 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
18703 }
18704 }
18705 }
18706 }
18707 (Grid::Own(uo), Grid::Own(vo))
18708 }
18709 } else if skip {
18710 let zeros = Grid::Zero(cw * ch);
18711 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
18712 // ~1000) predicts EVERY plane and only guards the residual on
18713 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
18714 // DC + alpha * luma-AC. Dropping the CfL term here left a
18715 // chroma-only bounded box on ReelC's key frames.
18716 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18717 if alpha.is_some() {
18718 hit!(CHROMA_SKIP_CFL_HITS);
18719 }
18720 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
18721 if chroma422_pair16 {
18722 // lane-av1-422o: two TX_4X8 units, each predicted on
18723 // its own edges (the lower one off the upper one's
18724 // samples); no coefficients are coded, and libaom's
18725 // `set_entropy_context` zeroed the block's own cells,
18726 // so the pair-wide zero stamp below stays correct.
18727 for unit_row in 0..2usize {
18728 let unit_reach = tu_reach_rect(
18729 pw,
18730 ph,
18731 0,
18732 unit_row * 8,
18733 8,
18734 8,
18735 pair_reach,
18736 ppx,
18737 ppy,
18738 y.width,
18739 y.height,
18740 fctx,
18741 );
18742 if let Some((ub, vb)) = &palette_uv_bufs {
18743 let pbuf = if plane == 1 { ub } else { vb };
18744 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18745 }
18746 push_intra_rect(
18747 plane,
18748 cpx,
18749 cpy + unit_row * 8,
18750 4,
18751 8,
18752 uv_predict_mode,
18753 angle_delta_uv,
18754 unit_reach,
18755 &ZERO_RESIDUAL[..4 * 8],
18756 alpha
18757 .zip(ac)
18758 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18759 None,
18760 smooth_neighbor_uv,
18761 fctx,
18762 );
18763 }
18764 } else {
18765 if let Some((ub, vb)) = &palette_uv_bufs {
18766 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18767 }
18768 push_intra_rect(
18769 plane,
18770 cpx,
18771 cpy,
18772 cw,
18773 ch,
18774 uv_predict_mode,
18775 angle_delta_uv,
18776 pair_reach,
18777 &zeros,
18778 alpha
18779 .zip(ac)
18780 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18781 None,
18782 smooth_neighbor_uv,
18783 fctx,
18784 );
18785 }
18786 }
18787 (zeros.clone(), zeros)
18788 } else if chroma422_pair16 {
18789 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
18790 // per plane, plane-major (every U unit, then every V). Each
18791 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
18792 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
18793 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
18794 // offset comes from `num_pels_log2_lookup[plane_bsize] >
18795 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
18796 // BLOCK_INVALID (255), and the byte at that table's +255 in
18797 // the pinned Release oracle is 255 (`cmpb` against the
18798 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
18799 // arm: +3 on the offset-7-first chroma tables. No tx_type
18800 // symbol (only y plane's is transmitted); the unit's type is
18801 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
18802 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
18803 // are computed ONCE per block (`are_parameters_computed`)
18804 // over the pair's luma, shared by both units. Each unit is
18805 // predicted and recorded immediately, so the lower unit
18806 // reads the upper one's coefficient context.
18807 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18808 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
18809 for unit_row in 0..2usize {
18810 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
18811 let unit_reach = tu_reach_rect(
18812 pw,
18813 ph,
18814 0,
18815 unit_row * 8,
18816 8,
18817 8,
18818 pair_reach,
18819 ppx,
18820 ppy,
18821 y.width,
18822 y.height,
18823 fctx,
18824 );
18825 if let Some((ub, vb)) = &palette_uv_bufs {
18826 let pbuf = if plane == 1 { ub } else { vb };
18827 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18828 }
18829 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
18830 let unit_grid = read_rect_chroma_unit(
18831 dec,
18832 cdfs,
18833 TxbSet::ChromaRect8x4,
18834 &SCAN_4X8,
18835 4,
18836 8,
18837 plane,
18838 chroma_around[plane],
18839 uv_predict_mode,
18840 angle_delta_uv,
18841 unit_reach,
18842 buf,
18843 cpx,
18844 cpy + unit_row * 8,
18845 base_q_idx,
18846 // lane-av1-422q: the offset-10 rows -- the same
18847 // measured rule as the 4x32 arm (plane_bsize
18848 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
18849 // num_pels_log2_lookup[255] = 0xff at the
18850 // 0xc0de70 copy -> +3 on the offset-7-first
18851 // chroma tables; see lanes/av1422q.report.md).
18852 Some(3),
18853 alpha
18854 .zip(ac)
18855 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18856 smooth_neighbor_uv,
18857 fctx,
18858 )?;
18859 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
18860 }
18861 }
18862 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18863 } else {
18864 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
18865 // every second luma-mi cell
18866 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
18867 // chroma 4-px column spans two luma mi columns, and the
18868 // plain per-mi gather counts each column's whole-unit dc
18869 // sign twice). The left extent is unsubsampled at ss_y 0,
18870 // so its per-mi cells already line up one-to-one.
18871 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
18872 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
18873 } else {
18874 neighbours.around_mi_rect(pair_mi, pw, ph)
18875 };
18876 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
18877 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
18878 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
18879 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
18880 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
18881 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
18882 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
18883 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
18884 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
18885 // (4,16) never reaches this row; `chroma422_pair16`
18886 // intercepts it above and chunks it into TX_4X8 units.)
18887 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
18888 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
18889 // pair's height: an 8x8 SQUARE chroma block, the same
18890 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
18891 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
18892 // row is unreachable there. It is also the witness arm:
18893 // a restored `/2 chroma height` lands on (8,4) and the
18894 // counter reads 0.
18895 (8, 8) => {
18896 hit!(CHROMA422_SQUARE_HITS);
18897 (TxbSet::Chroma8, default_scan(8))
18898 }
18899 // lane-av1-422o: with the `chroma422_pair16` arm above,
18900 // the (2,16) own-strip shape and the 4:4:4 shapes are the
18901 // only residents; anything else is a named-lane gap.
18902 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
18903 };
18904 let mut planes = Vec::with_capacity(2);
18905 for plane in 1..3 {
18906 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
18907 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
18908 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
18909 let (levels, tx_type) = read_chroma_coeffs_rect(
18910 dec,
18911 &mut coding,
18912 chroma_scan,
18913 cw,
18914 ch,
18915 skip_ctx,
18916 dc_sign_ctx(around[plane].2),
18917 default_tx,
18918 fctx,
18919 plane,
18920 )?;
18921 planes.push((levels, tx_type));
18922 }
18923 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
18924 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
18925 // CfL averages the luma of the WHOLE pair, the region this one
18926 // chroma transform covers.
18927 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18928 for (plane, _buf, levels, tx_type) in [
18929 (1usize, &mut *u, &u_levels, u_tx_type),
18930 (2, &mut *v, &v_levels, v_tx_type),
18931 ] {
18932 let residual = dequant_and_inverse_typed_wh(
18933 levels,
18934 cw,
18935 ch,
18936 crate::decode::bit_depth(fctx),
18937 block_q_idx(fctx),
18938 plane_q_delta(plane, fctx).0,
18939 plane_q_delta(plane, fctx).1,
18940 tx_type,
18941 block_iqmatrix(fctx, plane, cw, ch, tx_type),
18942 );
18943 if let Some((ub, vb)) = &palette_uv_bufs {
18944 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18945 }
18946 push_intra_rect(
18947 plane,
18948 cpx,
18949 cpy,
18950 cw,
18951 ch,
18952 uv_predict_mode,
18953 angle_delta_uv,
18954 pair_reach,
18955 &residual,
18956 alpha
18957 .zip(ac)
18958 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18959 None,
18960 smooth_neighbor_uv,
18961 fctx,
18962 );
18963 }
18964 (u_levels, v_levels)
18965 };
18966 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
18967 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
18968 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
18969 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
18970 // the arm above (libaom's coefficient contexts are per
18971 // 4x4-cell); a pair-wide state would erase the unit boundary the
18972 // next block reads.
18973 if !lossless_pair && !chroma422_pair16 {
18974 // The chroma planes' coefficient context, over the PAIR's mi span
18975 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
18976 // the luma one rounded up to its 4x4 unit).
18977 let u_state = neighbour_state(&u_levels);
18978 let v_state = neighbour_state(&v_levels);
18979 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18980 let bound_h = round_up_even(neighbours.mi_rows);
18981 let bound_w = round_up_even(neighbours.mi_cols);
18982 for cell in 0..(ph / MI) {
18983 if pair_mi.0 + cell < bound_h
18984 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18985 {
18986 slot[1] = u_state;
18987 slot[2] = v_state;
18988 }
18989 }
18990 for cell in 0..(pw / MI) {
18991 if pair_mi.1 + cell < bound_w
18992 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18993 {
18994 slot[1] = u_state;
18995 slot[2] = v_state;
18996 }
18997 }
18998 }
18999 last_uv_mode = Some(uv_predict_mode);
19000 }
19001 if horz {
19002 hit!(RECT4_16_HORZ_HITS);
19003 } else {
19004 hit!(RECT4_16_VERT_HITS);
19005 }
19006 let (pal_y_size, pal_y_colors) = palette_y
19007 .as_ref()
19008 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19009 let (pal_uv_size, pal_uv_colors) = palette_uv
19010 .as_ref()
19011 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19012 record_strip_palette(
19013 neighbours,
19014 lmi,
19015 bw,
19016 bh,
19017 pal_y_size,
19018 pal_y_colors,
19019 pal_uv_size,
19020 pal_uv_colors,
19021 );
19022 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19023 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19024 // frame): the above row records `tx_size_wide` over the block's width and
19025 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19026 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19027 // and it published neither band -- so the block after a 64x16 strip read
19028 // the row's init value 64 as its left transform height and took
19029 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19030 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19031 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19032 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
19033 Ok((mode, last_uv_mode, (tx_w, tx_h)))
19034}
19035
19036/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
19037/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
19038/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
19039/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
19040/// cap, so LUMA needs the same corner truncation [`decode_block`] already
19041/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
19042/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
19043/// this function's own charter/report), so both strips read a real 32x32
19044/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
19045/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
19046/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
19047/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
19048/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
19049/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
19050/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
19051/// that function, only the single-transform-unit (`tx_depth == 0`) case is
19052/// supported: a split transform refuses by name rather than guess-decode.
19053#[allow(clippy::too_many_arguments)]
19054fn decode_block_rect64(
19055 dec: &mut SymbolDecoder,
19056 cdfs: &mut Cdfs,
19057 neighbours: &mut Neighbours,
19058 at: (usize, usize),
19059 bw: usize,
19060 bh: usize,
19061 y: &mut PlaneBuf<'static>,
19062 u: &mut PlaneBuf<'static>,
19063 v: &mut PlaneBuf<'static>,
19064 enable_filter_intra: bool,
19065 allow_screen_content_tools: bool,
19066 base_q_idx: u8,
19067 tx_select: bool,
19068 reduced_tx_set: bool,
19069 fctx: &crate::decode::FrameCtx,
19070) -> Result<()> {
19071 let (r, c) = at;
19072 let (px, py) = (c * SUB, r * SUB);
19073 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
19074 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
19075 let palette_uv_cache = neighbours.palette_uv_cache(at);
19076 let (
19077 skip,
19078 mode,
19079 angle_delta_y,
19080 uv_mode,
19081 angle_delta_uv,
19082 alpha,
19083 filter_intra,
19084 palette_y,
19085 palette_uv,
19086 intrabc,
19087 ) = read_intra_mode_rect(
19088 dec,
19089 cdfs,
19090 nb_above_mode,
19091 nb_left_mode,
19092 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
19093 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
19094 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
19095 // correct), CFL must never be offered here -- passing `true`
19096 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
19097 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
19098 // from this block's very first symbol (lane-sbpart r3 bisect).
19099 false,
19100 true,
19101 bw,
19102 bh,
19103 enable_filter_intra,
19104 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
19105 allow_screen_content_tools,
19106 Some((palette_ctx, &palette_cache)),
19107 &palette_uv_cache,
19108 r * (SUB / MI),
19109 c * (SUB / MI),
19110 fctx,
19111 )?;
19112 if let Some((dv_row, dv_col)) = intrabc {
19113 return decode_intrabc_owned_rect(
19114 dec,
19115 cdfs,
19116 neighbours,
19117 (r * (SUB / MI), c * (SUB / MI)),
19118 (bw, bh),
19119 skip,
19120 (dv_row, dv_col),
19121 y,
19122 u,
19123 v,
19124 base_q_idx,
19125 tx_select,
19126 reduced_tx_set,
19127 fctx,
19128 );
19129 }
19130 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
19131 // lane-t900 r34: a non-skip palette block on a superblock-level strip
19132 // -- counted so its gate cannot go vacuous (this was a refusal until
19133 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
19134 // decodes_pixel_exact`).
19135 hit!(PALETTE_SB_STRIP_HITS);
19136 }
19137 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
19138 if smooth_neighbor {
19139 hit!(SMOOTH_LUMA_HITS);
19140 }
19141 let smooth_neighbor_uv =
19142 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
19143 if filter_intra.is_some() {
19144 // `filter_intra_size_class_rect` already returns `None` for both
19145 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
19146 // 32 on both axes), so this symbol is never read at this level --
19147 // kept only as the same defensive refusal [`decode_block_rect`] has.
19148 return Err(unsupported(
19149 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
19150 av1_filter_intra_allowed_bsize caps at 32x32)",
19151 ));
19152 }
19153 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
19154 DC_PRED
19155 } else {
19156 uv_mode
19157 };
19158 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
19159 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
19160 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
19161 // no depth symbol here either (class sweep of the sub8 leaf's fix).
19162 let depth = if tx_select && !lossless(fctx) {
19163 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
19164 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
19165 // intra-only frame publishes them from every block too
19166 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
19167 // 1920x792 128-superblock stream,
19168 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
19169 // `tx_size_cat2` row 1 where libaom reads row 2.
19170 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
19171 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
19172 // counts `sub_tx_size_map` steps from the block's own max rect
19173 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
19174 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
19175 // steps, so this level's category is 3 (the same one a 64x64 square
19176 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
19177 // here was a wrong-table read of a real symbol.
19178 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
19179 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19180 eprintln!(
19181 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
19182 dec.debug_state().0
19183 );
19184 }
19185 d
19186 } else {
19187 0
19188 };
19189 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
19190 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
19191 publish_txfm_bands_if_in_inter(
19192 neighbours,
19193 (mi_r, mi_c),
19194 depth_to_tx_wh(bw, bh, depth, fctx),
19195 (bw, bh),
19196 fctx,
19197 );
19198 if depth != 0 || lossless(fctx) {
19199 hit!(TX_DEPTH_HITS);
19200 // lane-rectsplit r1/r4: the superblock-level strip splits its
19201 // transform through the very same per-unit path as its 32x32-level
19202 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
19203 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
19204 // measured the old square formula mis-tiling exactly that strip).
19205 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
19206 if bw.max(bh) / bw.min(bh) == 4 {
19207 let which = if depth == 1 {
19208 &RECT4_SPLIT_DEPTH1_HITS
19209 } else {
19210 &RECT4_SPLIT_DEPTH2_HITS
19211 };
19212 hit_do! { which.with(|c| c.set(c.get() + 1)); }
19213 }
19214 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19215 eprintln!(
19216 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
19217 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
19218 angle_y={angle_delta_y}"
19219 );
19220 }
19221 let modes = RectStripModes {
19222 skip,
19223 mode,
19224 angle_delta_y,
19225 uv_predict_mode,
19226 angle_delta_uv,
19227 alpha,
19228 filter_intra,
19229 smooth_neighbor,
19230 smooth_neighbor_uv,
19231 palette_y: palette_y
19232 .as_ref()
19233 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
19234 palette_uv: palette_uv.as_ref().map(|p| {
19235 (
19236 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
19237 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
19238 )
19239 }),
19240 };
19241 if palette_y.is_some() || palette_uv.is_some() {
19242 hit!(PALETTE_SPLIT_TX_HITS);
19243 }
19244 decode_rect_split(
19245 dec,
19246 cdfs,
19247 neighbours,
19248 (mi_r, mi_c),
19249 bw,
19250 bh,
19251 tx_w,
19252 tx_h,
19253 &modes,
19254 y,
19255 u,
19256 v,
19257 base_q_idx,
19258 reduced_tx_set,
19259 fctx,
19260 )?;
19261 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
19262 // (lane-palette2 r10): this return skips the fn's own tail, so a
19263 // split-tx superblock strip would otherwise leave the above/left
19264 // palette arrays holding a dead block's colours.
19265 let (py_size, py_colors) = palette_y
19266 .as_ref()
19267 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19268 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19269 let (puv_size, puv_colors) = palette_uv
19270 .as_ref()
19271 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19272 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19273 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
19274 // return skips the fn's own tail, so a SPLIT superblock-level strip
19275 // published no TXFM_CONTEXT band and the next block read the row's init
19276 // value 64 as its left transform height. Measured on the 10-bit
19277 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
19278 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
19279 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
19280 // bands carry the SPLIT unit's size, not the block's.
19281 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19282 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
19283 hit!(RECT_PARTITION_HITS);
19284 return Ok(());
19285 }
19286 let (tx_w, tx_h) = (bw, bh);
19287 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
19288 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
19289 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19290 if let Some(ref pyv) = palette_y {
19291 let buf: Vec<u16> = pyv
19292 .map
19293 .iter()
19294 .map(|&idx| pyv.colors[idx as usize])
19295 .collect();
19296 set_palette_pred(buf, fctx);
19297 }
19298 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
19299 (
19300 puv.map
19301 .iter()
19302 .map(|&idx| puv.u_colors[idx as usize])
19303 .collect(),
19304 puv.map
19305 .iter()
19306 .map(|&idx| puv.v_colors[idx as usize])
19307 .collect(),
19308 )
19309 });
19310 if skip {
19311 push_intra_rect(
19312 0,
19313 px,
19314 py,
19315 bw,
19316 bh,
19317 mode,
19318 angle_delta_y,
19319 reach,
19320 &ZERO_RESIDUAL[..bw * bh],
19321 None,
19322 filter_intra,
19323 smooth_neighbor,
19324 fctx,
19325 );
19326 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19327 if let Some((ub, _)) = &palette_uv_bufs {
19328 set_palette_pred(ub.clone(), fctx);
19329 }
19330 push_intra_rect(
19331 1,
19332 cpx,
19333 cpy,
19334 chroma_w,
19335 chroma_h,
19336 uv_predict_mode,
19337 angle_delta_uv,
19338 reach,
19339 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19340 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
19341 None,
19342 smooth_neighbor_uv,
19343 fctx,
19344 );
19345 if let Some((_, vb)) = &palette_uv_bufs {
19346 set_palette_pred(vb.clone(), fctx);
19347 }
19348 push_intra_rect(
19349 2,
19350 cpx,
19351 cpy,
19352 chroma_w,
19353 chroma_h,
19354 uv_predict_mode,
19355 angle_delta_uv,
19356 reach,
19357 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19358 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
19359 None,
19360 smooth_neighbor_uv,
19361 fctx,
19362 );
19363 neighbours.record_rect(
19364 at,
19365 bw,
19366 bh,
19367 mode,
19368 uv_predict_mode,
19369 &[
19370 &ZERO_RESIDUAL[..bw * bh],
19371 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19372 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19373 ],
19374 );
19375 } else {
19376 let around = neighbours.around_rect(at, bw, bh);
19377 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
19378 // (see this function's own doc comment). A 64-length axis codes only
19379 // its low 32 coefficients, so the corner is `min(bw, 32)` x
19380 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
19381 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
19382 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
19383 let scan32 = default_scan(TX32);
19384 if coeff_trace_on() {
19385 let (rng, _) = dec.debug_state();
19386 eprintln!(
19387 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
19388 );
19389 }
19390 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
19391 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
19392 read_coeffs(
19393 dec,
19394 &mut luma_coding,
19395 &scan32,
19396 0,
19397 dc_sign_ctx(around[0].2),
19398 TxType::DctDct,
19399 Some((bw, bh)),
19400 )?
19401 } else {
19402 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
19403 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
19404 // (`scan.c`) gives both the very same `default_scan_32x16` /
19405 // `default_scan_16x32` the 2:1 sizes use ("Half of the
19406 // coefficients of tx64 at higher frequencies are set to zeros. So
19407 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
19408 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
19409 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
19410 // 512-position eob group) -- BOTH identical to TX_32X16, so the
19411 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
19412 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
19413 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
19414 // what `base_ctx_rect` computes at (32, 16).
19415 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
19416 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
19417 read_coeffs_rect(
19418 dec,
19419 &mut luma_coding,
19420 luma_scan,
19421 luma_cw,
19422 luma_ch,
19423 0,
19424 dc_sign_ctx(around[0].2),
19425 TxType::DctDct,
19426 0,
19427 )?
19428 };
19429 if coeff_trace_on() {
19430 let (rng, _) = dec.debug_state();
19431 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
19432 }
19433 let mut luma_levels = vec![0i32; bw * bh];
19434 for row in 0..luma_ch {
19435 luma_levels[row * bw..][..luma_cw]
19436 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
19437 }
19438 {
19439 let cur = block_q_idx(fctx);
19440 if cur != i32::from(base_q_idx) {
19441 hit!(RECT64_QIDX_DRIFT_HITS);
19442 }
19443 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19444 eprintln!(
19445 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
19446 );
19447 }
19448 }
19449 let luma_residual = dequant_and_inverse_typed_wh(
19450 &luma_levels,
19451 bw,
19452 bh,
19453 crate::decode::bit_depth(fctx),
19454 block_q_idx(fctx),
19455 plane_q_delta(0, fctx).0,
19456 plane_q_delta(0, fctx).1,
19457 luma_tx_type,
19458 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
19459 );
19460 push_intra_rect(
19461 0,
19462 px,
19463 py,
19464 bw,
19465 bh,
19466 mode,
19467 angle_delta_y,
19468 reach,
19469 &luma_residual,
19470 None,
19471 filter_intra,
19472 smooth_neighbor,
19473 fctx,
19474 );
19475 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19476 let leftcol: Vec<u16> = if px > 0 {
19477 (py..py + bh)
19478 .map(|row| y.data[row * y.width + px - 1])
19479 .collect()
19480 } else {
19481 vec![]
19482 };
19483 eprintln!(
19484 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
19485 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
19486 luma_corner.iter().any(|&v| v != 0),
19487 &y.data[py * y.width + px..][..bw],
19488 leftcol,
19489 );
19490 }
19491 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
19492 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
19493 // is larger than that, so it is tiled into 32-capped units.
19494 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19495 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
19496 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
19497 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
19498 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
19499 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
19500 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
19501 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
19502 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
19503 _ => {
19504 return Err(unsupported(
19505 "a 64-axis strip whose chroma unit has no coefficient table",
19506 ));
19507 }
19508 };
19509 let bigger = nw * nh > 1;
19510 let mut u_levels = vec![0i32; chroma_w * chroma_h];
19511 let mut v_levels = vec![0i32; chroma_w * chroma_h];
19512 // The tiled units below stamp their own coefficient context
19513 // immediately, then the whole-strip `record_rect` rewrite paints
19514 // every chroma cell with ONE whole-strip state and the per-unit DC
19515 // signs and levels are lost (class `override-slot-on-one-arm`, same
19516 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
19517 // here and replayed after that record, the c8 `mu_chroma_units` way.
19518 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
19519 for plane_idx in 1..=2 {
19520 for cu_row in 0..nh {
19521 for cu_col in 0..nw {
19522 let cu_around = if nw == 1 && nh == 1 {
19523 around
19524 } else {
19525 let lsx = uw << ss_x(fctx);
19526 let lsy = uh << ss_y(fctx);
19527 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
19528 neighbours.around_mi_rect(cu_mi, lsx, lsy)
19529 };
19530 let lsx = uw << ss_x(fctx);
19531 let lsy = uh << ss_y(fctx);
19532 let cfl = alpha.map(|(au, av)| {
19533 let a = if plane_idx == 1 { au } else { av };
19534 (
19535 a,
19536 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
19537 )
19538 });
19539 let levels = if uw == uh {
19540 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
19541 if let Some((ub, vb)) = &palette_uv_bufs {
19542 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19543 }
19544 read_plane(
19545 dec,
19546 cdfs,
19547 chroma_set,
19548 chroma_scan,
19549 plane_idx,
19550 cu_around[plane_idx],
19551 mode,
19552 uv_predict_mode,
19553 angle_delta_uv,
19554 reach,
19555 plane,
19556 cpx + cu_col * uw,
19557 cpy + cu_row * uh,
19558 uw,
19559 uw,
19560 base_q_idx,
19561 cfl,
19562 None,
19563 bigger.then_some(3),
19564 smooth_neighbor_uv,
19565 fctx,
19566 )?
19567 } else {
19568 let skip_ctx = usize::from(cu_around[plane_idx].0)
19569 + usize::from(cu_around[plane_idx].1)
19570 + usize::from(bigger) * 3;
19571 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19572 let (levels, tx_type) = read_chroma_coeffs_rect(
19573 dec,
19574 &mut coding,
19575 chroma_scan,
19576 uw,
19577 uh,
19578 skip_ctx,
19579 dc_sign_ctx(cu_around[plane_idx].2),
19580 TxType::DctDct,
19581 fctx,
19582 plane_idx,
19583 )?;
19584 let residual = dequant_and_inverse_typed_wh(
19585 &levels,
19586 uw,
19587 uh,
19588 crate::decode::bit_depth(fctx),
19589 block_q_idx(fctx),
19590 plane_q_delta(plane_idx, fctx).0,
19591 plane_q_delta(plane_idx, fctx).1,
19592 tx_type,
19593 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
19594 );
19595 if let Some((ub, vb)) = &palette_uv_bufs {
19596 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19597 }
19598 push_intra_rect(
19599 plane_idx,
19600 cpx + cu_col * uw,
19601 cpy + cu_row * uh,
19602 uw,
19603 uh,
19604 uv_predict_mode,
19605 angle_delta_uv,
19606 reach,
19607 &residual,
19608 cfl,
19609 None,
19610 smooth_neighbor_uv,
19611 fctx,
19612 );
19613 levels
19614 };
19615 let dst = if plane_idx == 1 {
19616 &mut u_levels
19617 } else {
19618 &mut v_levels
19619 };
19620 for row in 0..uh {
19621 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
19622 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
19623 }
19624 if bigger {
19625 neighbours.record_mi_chroma(
19626 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19627 lsx,
19628 lsy,
19629 plane_idx,
19630 &levels,
19631 );
19632 tiled_chroma_units.push((
19633 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19634 plane_idx,
19635 levels.clone(),
19636 lsx,
19637 lsy,
19638 ));
19639 }
19640 }
19641 }
19642 }
19643 neighbours.record_rect(
19644 at,
19645 bw,
19646 bh,
19647 mode,
19648 uv_predict_mode,
19649 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
19650 );
19651 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
19652 // chroma cells from the assembled grids' one whole-strip state,
19653 // overwriting exactly the stamps the tiled loop just made.
19654 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
19655 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
19656 }
19657 hit!(RECT_COEFF_HITS);
19658 }
19659 let (py_size, py_colors) = palette_y
19660 .as_ref()
19661 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19662 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19663 let (puv_size, puv_colors) = palette_uv
19664 .as_ref()
19665 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19666 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19667 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
19668 neighbours.fill_lf_grid_rect(
19669 (mi_r, mi_c),
19670 bw / MI,
19671 bh / MI,
19672 tx_w as u8,
19673 tx_h as u8,
19674 0,
19675 fctx,
19676 );
19677 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19678 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19679 // frame): the above row records `tx_size_wide` over the block's width and
19680 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19681 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19682 // and it published neither band -- so the block after a 64x16 strip read
19683 // the row's init value 64 as its left transform height and took
19684 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19685 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19686 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19687 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19688 hit!(SB_RECT_HITS);
19689 match (bw, bh) {
19690 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
19691 (16, 64) => hit!(SB_RECT4_VERT_HITS),
19692 _ => {}
19693 }
19694 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19695 let (rng, _) = dec.debug_state();
19696 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
19697 }
19698 Ok(())
19699}
19700
19701/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
19702/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
19703/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
19704/// it lands away from zero, for gate tests to prove a real stream fired one.
19705fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
19706 let symbol = dec.symbol(cdf);
19707 if symbol != ANGLE_DELTA_ZERO {
19708 hit!(ANGLE_DELTA_HITS);
19709 }
19710 symbol as i32 - ANGLE_DELTA_ZERO as i32
19711}
19712
19713#[allow(clippy::too_many_arguments)]
19714fn read_intra_mode(
19715 dec: &mut SymbolDecoder,
19716 cdfs: &mut Cdfs,
19717 above_mode: usize,
19718 left_mode: usize,
19719 cfl: bool,
19720 side: usize,
19721 enable_filter_intra: bool,
19722 skip_ctx: usize,
19723 allow_screen_content_tools: bool,
19724 allow_intrabc: bool,
19725 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
19726 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
19727 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
19728 // `None` at the excluded call sites (the 8x8-leaf path), which still read
19729 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
19730 // decoder reads either way -- but refuse by name the moment it fires,
19731 // exactly the old behaviour.
19732 palette: Option<(usize, &[u16])>,
19733 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
19734 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
19735 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
19736 // `use_palette_y`, not a neighbour lookup).
19737 palette_uv_cache: &[u16],
19738 mi_r: usize,
19739 mi_c: usize,
19740 fctx: &crate::decode::FrameCtx,
19741) -> Result<(
19742 bool,
19743 usize,
19744 i32,
19745 usize,
19746 i32,
19747 Option<(i32, i32)>,
19748 Option<usize>,
19749 Option<PaletteY>,
19750 Option<PaletteUv>,
19751)> {
19752 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
19753 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
19754 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
19755 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
19756 // line against the instrumented aomdec, not just `tell()`.
19757 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
19758 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
19759 if ec_istep {
19760 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
19761 // (decodemv.c:818), printed at the same point: before the first
19762 // mode-info symbol of the block, so a cross-decoder range ladder can
19763 // be keyed on the BLOCK, not just on the symbol sequence.
19764 eprintln!(
19765 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
19766 dec.debug_state().0
19767 );
19768 }
19769 macro_rules! istep {
19770 ($name:literal, $val:expr) => {
19771 if ec_istep {
19772 let (rng, _) = dec.debug_state();
19773 eprintln!(
19774 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
19775 $name, $val
19776 );
19777 }
19778 };
19779 }
19780 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
19781 // point every square caller routes through (see `read_intra_mode_rect`).
19782 let cfl = if cfl && side > 32 {
19783 hit!(NOCFL_UV_MODE_HITS);
19784 false
19785 } else {
19786 cfl
19787 };
19788 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
19789 // `skip` when `SegIdPreSkip`, and after it otherwise.
19790 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
19791 if seg_id_pre_skip(fctx) {
19792 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
19793 }
19794 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
19795 if trace {
19796 eprintln!(
19797 "TRACE skip value={} rng={}",
19798 skip as i32,
19799 dec.debug_state().0
19800 );
19801 }
19802 istep!("skip", skip as i32);
19803 if !seg_id_pre_skip(fctx) {
19804 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
19805 }
19806 // spec order (see the comment below on `read_intrabc_info`): `skip`,
19807 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
19808 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
19809 istep!("cdef", 0);
19810 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
19811 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
19812 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
19813 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
19814 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19815 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19816 istep!("dq", 0);
19817 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
19818 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
19819 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
19820 // intra frame whose header set `allow_intrabc`. Actual intra block copy
19821 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
19822 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
19823 // draws the line at consuming this one flag symbol and refusing by name
19824 // when it fires, so the arithmetic decoder still resyncs for a stream
19825 // that merely allows (but never uses) intrabc.
19826 if allow_intrabc {
19827 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
19828 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19829 eprintln!(
19830 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
19831 u8::from(use_intrabc),
19832 dec.debug_state().0
19833 );
19834 }
19835 if trace {
19836 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
19837 }
19838 if use_intrabc {
19839 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
19840 if trace {
19841 eprintln!("TRACE intrabc dv={dv:?}");
19842 }
19843 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
19844 hit!(INTRABC_HITS);
19845 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
19846 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
19847 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
19848 // `DC_PRED` (which is also what the neighbour mode contexts and
19849 // the loop filter then see).
19850 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
19851 }
19852 }
19853 let above_ctx = INTRA_MODE_CTX[above_mode];
19854 let left_ctx = INTRA_MODE_CTX[left_mode];
19855 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
19856 if trace {
19857 eprintln!(
19858 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
19859 dec.debug_state().0
19860 );
19861 }
19862 istep!("mode", mode as i32);
19863 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
19864 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
19865 if trace {
19866 eprintln!(
19867 "TRACE angle_delta value={}",
19868 delta + ANGLE_DELTA_ZERO as i32
19869 );
19870 }
19871 delta
19872 } else {
19873 0
19874 };
19875 istep!("angle_y", angle_delta_y);
19876 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
19877 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
19878 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
19879 // gates its chroma symbols on.
19880 let has_chroma = !mono(fctx);
19881 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
19882 let uv_mode = if !has_chroma {
19883 DC_PRED
19884 } else if cfl {
19885 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19886 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
19887 } else {
19888 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19889 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
19890 };
19891 if trace {
19892 eprintln!(
19893 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
19894 dec.debug_state().0
19895 );
19896 }
19897 istep!("uv_mode", uv_mode as i32);
19898 let alpha = if cfl && uv_mode == UV_CFL_PRED {
19899 Some(read_cfl_alphas(dec, cdfs))
19900 } else {
19901 None
19902 };
19903 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
19904 // from this lane's directional chroma: a corner block with neither
19905 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
19906 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
19907 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
19908 // bug in that fallback this lane's own scope does not cover. Keep it
19909 // refused here rather than ship a silently-wrong decode.
19910 if (9..=12).contains(&uv_mode) {
19911 hit!(SMOOTH_UV_HITS);
19912 }
19913 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
19914 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
19915 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
19916 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
19917 // the `else` branch below and never reads one either way.
19918 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
19919 hit!(DIRECTIONAL_UV_HITS);
19920 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
19921 } else {
19922 0
19923 };
19924 istep!("angle_uv", angle_delta_uv);
19925 if angle_delta_uv != 0 {
19926 hit!(UV_ANGLE_DELTA_HITS);
19927 }
19928 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
19929 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
19930 // gated by `av1_allow_palette` (blockd.h -- size bound only,
19931 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
19932 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
19933 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
19934 // read the same CDF row whenever every neighbour really is non-palette).
19935 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
19936 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
19937 // neighbour lookup at all), so it is exact even at the excluded call
19938 // sites once Y decodes real syntax there too.
19939 //
19940 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
19941 // inline from `read_palette_mode_info` -- it runs later, from
19942 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
19943 // after the WHOLE mode-info read for the block, including UV palette
19944 // mode_info (`read_palette_mode_info`'s own second half, right below)
19945 // and `read_filter_intra_mode_info`. So this branch now only reads
19946 // mode/size/colours for both planes (deferring the two colour-index-map
19947 // decodes to after `filter_intra`, below) -- r6's range trace pinned
19948 // this exact ordering bug (`compare-range-not-tell`: ranges matched
19949 // bit-for-bit through the Y colours, diverged only at the old inline
19950 // `decode_color_index_map` call).
19951 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
19952 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
19953 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
19954 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
19955 if mode == DC_PRED {
19956 if trace {
19957 let (rng, _) = dec.debug_state();
19958 eprintln!(
19959 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
19960 );
19961 }
19962 }
19963 let use_palette_y =
19964 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
19965 if mode == DC_PRED && trace {
19966 let (rng, _) = dec.debug_state();
19967 eprintln!(
19968 "TRACE palette_y_mode value={} rng={rng}",
19969 use_palette_y as i32
19970 );
19971 }
19972 if use_palette_y {
19973 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
19974 if trace {
19975 let (rng, _) = dec.debug_state();
19976 eprintln!("TRACE palette_y_size n={n} rng={rng}");
19977 }
19978 let colors = read_palette_colors_y(dec, n, cache, fctx);
19979 if trace {
19980 let (rng, _) = dec.debug_state();
19981 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
19982 }
19983 palette_y_pending = Some((n, colors));
19984 }
19985 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
19986 // unconditionally at this bit position whenever `uv_mode ==
19987 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
19988 // scope always reconstructs chroma alongside luma (`decode_block`
19989 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
19990 // is always true here and does not need threading in.
19991 //
19992 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
19993 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
19994 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
19995 // symbol even at this chroma-owning square block.
19996 let palette_uv_mode_ctx = usize::from(use_palette_y);
19997 if has_chroma
19998 && uv_mode == DC_PRED
19999 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
20000 {
20001 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
20002 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
20003 palette_uv_pending = Some((n, u_colors, v_colors));
20004 }
20005 }
20006 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
20007 // `use_filter_intra` symbol this decoder never read at all until
20008 // lane-av1real r10 -- silently skipping it left every bit past a
20009 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
20010 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
20011 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
20012 // symbol's bits were never consumed).
20013 let mut filter_intra = None;
20014 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
20015 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
20016 // `use_filter_intra` symbol for a Y-palette block, and reading one here
20017 // desynced every screen-content stream from the first palette block on
20018 // (it surfaced as a bogus "partition below 8x8" refusal further down the
20019 // tile).
20020 if mode == DC_PRED
20021 && enable_filter_intra
20022 && palette_y_pending.is_none()
20023 && let Some(class) = filter_intra_size_class(side)
20024 {
20025 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
20026 if trace {
20027 eprintln!(
20028 "TRACE use_filter_intra side={side} rng={} value={}",
20029 dec.debug_state().0,
20030 use_filter_intra as i32
20031 );
20032 }
20033 istep!("use_filter_intra", use_filter_intra as i32);
20034 if use_filter_intra {
20035 hit!(FILTER_INTRA_HITS);
20036 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
20037 if trace {
20038 eprintln!("TRACE filter_intra_mode value={fi_mode}");
20039 }
20040 istep!("filter_intra_mode", fi_mode as i32);
20041 filter_intra = Some(fi_mode);
20042 }
20043 }
20044 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
20045 // shared U/V map) -- the same order libaom's own loop visits them in.
20046 let palette_y = palette_y_pending.map(|(n, colors)| {
20047 let map = decode_color_index_map(
20048 dec,
20049 cdfs,
20050 n,
20051 side,
20052 palette_onscreen(mi_r, mi_c, side, side, fctx),
20053 false,
20054 );
20055 hit!(PALETTE_HITS);
20056 if trace {
20057 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
20058 }
20059 PaletteY {
20060 size: n,
20061 colors,
20062 map,
20063 }
20064 });
20065 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
20066 let on = palette_onscreen_uv(
20067 (side, side),
20068 palette_onscreen(mi_r, mi_c, side, side, fctx),
20069 (side >> ss_x(fctx), side >> ss_y(fctx)),
20070 (ss_x(fctx), ss_y(fctx)),
20071 );
20072 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
20073 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
20074 // square call's `(side >> ss_x)`-squared (4x4), which left a
20075 // 16-entry map for a 32-sample unit and panicked the reconstruct.
20076 let map = decode_color_index_map_wh(
20077 dec,
20078 cdfs,
20079 n,
20080 side >> ss_x(fctx),
20081 side >> ss_y(fctx),
20082 on,
20083 true,
20084 );
20085 hit!(PALETTE_UV_HITS);
20086 if trace {
20087 eprintln!(
20088 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
20089 &u_colors[..n],
20090 &v_colors[..n]
20091 );
20092 }
20093 PaletteUv {
20094 size: n,
20095 u_colors,
20096 v_colors,
20097 map,
20098 }
20099 });
20100 Ok((
20101 skip,
20102 mode,
20103 angle_delta_y,
20104 uv_mode,
20105 angle_delta_uv,
20106 alpha,
20107 filter_intra,
20108 palette_y,
20109 palette_uv,
20110 ))
20111}
20112
20113/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
20114/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
20115/// intra modes.
20116const UV_CFL_PRED: usize = 13;
20117
20118/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
20119/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
20120/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
20121/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
20122/// joint sign the same way. Returns each plane's final signed `alpha_q3`
20123/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
20124fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
20125 hit!(CFL_BLOCK_HITS);
20126 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
20127 let sign_u = ((joint_sign + 1) * 11) >> 5;
20128 let sign_v = (joint_sign + 1) - 3 * sign_u;
20129 let alpha_u = if sign_u == 0 {
20130 0
20131 } else {
20132 let ctx_u = (joint_sign + 1 - 3) as usize;
20133 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
20134 if sign_u == 2 { mag } else { -mag }
20135 };
20136 let alpha_v = if sign_v == 0 {
20137 0
20138 } else {
20139 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
20140 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
20141 if sign_v == 2 { mag } else { -mag }
20142 };
20143 (alpha_u, alpha_v)
20144}
20145
20146/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
20147/// the reconstructed luma samples under a `side`-square block, subsampled
20148/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
20149/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
20150/// to give the AC values [`cfl_scaled`] scales by alpha.
20151fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
20152 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
20153 i32::from(y.data[ly * y.width + lx])
20154 })
20155}
20156
20157/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
20158/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
20159/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
20160/// reconstruction through THIS function rather than a second transcription of
20161/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
20162/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
20163/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
20164fn cfl_ac_ss(
20165 y: &PlaneBuf<'_>,
20166 px: usize,
20167 py: usize,
20168 bw: usize,
20169 bh: usize,
20170 ss_x: usize,
20171 ss_y: usize,
20172) -> Vec<i32> {
20173 if ss_x == 0 && ss_y == 0 {
20174 hit!(CFL_AC_444_HITS);
20175 let mut ac = vec![0i32; bw * bh];
20176 let mut sum = 0i32;
20177 for row in 0..bh {
20178 for col in 0..bw {
20179 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
20180 ac[row * bw + col] = q3;
20181 sum += q3;
20182 }
20183 }
20184 let num_pel = (bw * bh) as i32;
20185 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20186 ac.iter_mut().for_each(|v| *v -= avg);
20187 ac
20188 } else if ss_x == 1 && ss_y == 0 {
20189 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
20190 // averages the HORIZONTAL luma pair above it, at full chroma height
20191 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
20192 // is square here, and the 4:2:0 rect/square helpers below would halve
20193 // the height it must keep.
20194 hit!(CFL_AC_422_HITS);
20195 let (cw, ch) = (bw >> 1, bh);
20196 let mut ac = vec![0i32; cw * ch];
20197 let mut sum = 0i32;
20198 for row in 0..ch {
20199 for col in 0..cw {
20200 let (lx, ly) = (px + col * 2, py + row);
20201 let q3 = (i32::from(y.data[ly * y.width + lx])
20202 + i32::from(y.data[ly * y.width + lx + 1]))
20203 << 2;
20204 ac[row * cw + col] = q3;
20205 sum += q3;
20206 }
20207 }
20208 let num_pel = (cw * ch) as i32;
20209 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20210 ac.iter_mut().for_each(|v| *v -= avg);
20211 ac
20212 } else if bw == bh {
20213 hit!(CFL_AC_420_SQ_HITS);
20214 cfl_ac_q3(y, px, py, bw)
20215 } else {
20216 hit!(CFL_AC_420_RECT_HITS);
20217 cfl_ac_q3_rect(y, px, py, bw, bh)
20218 }
20219}
20220
20221pub(crate) fn cfl_ac_q3_at(
20222 px: usize,
20223 py: usize,
20224 bw: usize,
20225 bh: usize,
20226 sample: impl Fn(usize, usize) -> i32,
20227) -> Vec<i32> {
20228 hit!(CFL_AC_Q3_AT_HITS);
20229 if crate::envflags::env_flag!("EC_HALVSWEEP") {
20230 eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
20231 }
20232 let (cw, ch) = (bw / 2, bh / 2);
20233 let mut ac = vec![0i32; cw * ch];
20234 let mut sum = 0i32;
20235 for cy in 0..ch {
20236 for cx in 0..cw {
20237 let (lx, ly) = (px + cx * 2, py + cy * 2);
20238 let q3 =
20239 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
20240 << 1;
20241 ac[cy * cw + cx] = q3;
20242 sum += q3;
20243 }
20244 }
20245 let num_pel = (cw * ch) as i32;
20246 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20247 ac.iter_mut().for_each(|v| *v -= avg);
20248 ac
20249}
20250
20251/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
20252/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
20253/// ties away from zero on the shifted-out sign).
20254pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
20255 let v = alpha_q3 * ac_q3;
20256 if v >= 0 {
20257 (v + 32) >> 6
20258 } else {
20259 -((-v + 32) >> 6)
20260 }
20261}
20262
20263/// One plane's reconstruction buffer, `width * height` samples, and the
20264/// prediction/residual reads and writes into it — the decode-side twin of
20265/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
20266/// (own-edge and reach clamps both), passing what it gathers straight to
20267/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
20268/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
20269/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
20270/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
20271/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
20272/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
20273/// lane-mc64 r1: the decode-order index the stage dumps below key their file
20274/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
20275/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
20276/// without this every frame overwrote `.f0` and a per-frame bisection silently
20277/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
20278#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
20279fn stage_dump_idx() -> usize {
20280 PREFILT_PICTURE_IDX
20281 .load(std::sync::atomic::Ordering::SeqCst)
20282 .saturating_sub(1)
20283}
20284
20285fn dump_stage16(
20286 var: &str,
20287 y: &PlaneBuf<'_>,
20288 u: &PlaneBuf<'_>,
20289 v: &PlaneBuf<'_>,
20290 fw: usize,
20291 fh: usize,
20292) {
20293 use std::io::Write;
20294 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
20295 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
20296 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
20297 // not be read out at all.
20298 if let Ok(path) = crate::envflags::var(var)
20299 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20300 {
20301 for (p, w, h) in [
20302 (y, fw, fh),
20303 (u, fw.div_ceil(2), fh.div_ceil(2)),
20304 (v, fw.div_ceil(2), fh.div_ceil(2)),
20305 ] {
20306 for row in 0..h {
20307 let mut bytes = Vec::with_capacity(w * 2);
20308 for &s in &p.data[row * p.width..][..w] {
20309 bytes.extend_from_slice(&s.to_le_bytes());
20310 }
20311 let _ = f.write_all(&bytes);
20312 }
20313 }
20314 }
20315}
20316
20317/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
20318/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
20319/// every frame overwrote the previous one and only the LAST frame survived,
20320/// which silently defeats any per-frame filter-stage bisection.
20321fn dump_stage_idx(var: &str) -> usize {
20322 use std::collections::HashMap;
20323 use std::sync::{Mutex, OnceLock};
20324 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
20325 let mut m = IDX
20326 .get_or_init(|| Mutex::new(HashMap::new()))
20327 .lock()
20328 .unwrap();
20329 let e = m.entry(var.to_string()).or_insert(0);
20330 let i = *e;
20331 *e += 1;
20332 i
20333}
20334
20335fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20336 use std::io::Write;
20337 if let Ok(path) = crate::envflags::var(var)
20338 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20339 {
20340 for p in [y, u, v] {
20341 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
20342 let _ = f.write_all(&narrow);
20343 }
20344 }
20345}
20346
20347/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
20348/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
20349/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
20350/// `uv_width`/`uv_height`), so the two can be diffed directly.
20351///
20352/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
20353/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
20354/// measurement traps, and the second one is why the first went unnoticed:
20355/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
20356/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
20357/// inter frame had no pre-filter rung to compare against and got attributed to
20358/// reconstruction when the oracle could not see it. The `static` also restarted
20359/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
20360/// per-frame bisection silently compared the LAST decoded frame. The counter
20361/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
20362/// the inter path (skipped when the filter pipeline is active, which has
20363/// already deblocked by the time the tile tail runs -- same condition
20364/// `capture_filter_replay` guards itself with).
20365fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20366 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
20367 return;
20368 };
20369 use std::io::Write;
20370 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
20371 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
20372 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
20373 for row in 0..plane.true_height {
20374 out.extend(
20375 plane.data[row * plane.width..][..plane.true_width]
20376 .iter()
20377 .map(|&s| s as u8),
20378 );
20379 }
20380 out
20381 };
20382 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
20383 let _ = f.write_all(&crop(y));
20384 let _ = f.write_all(&crop(u));
20385 let _ = f.write_all(&crop(v));
20386 }
20387}
20388
20389/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
20390/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
20391/// at most 4095), so a decode that hashes identically under the flag proves
20392/// the output does not depend on the plane buffer's initial content.
20393const PLANE_SENTINEL: u16 = 0xDEAD;
20394
20395/// A frame plane's own backing store, `n` samples, UNINITIALISED.
20396///
20397/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
20398/// by the tile walk's reconstruction before anything reads it, so the
20399/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
20400/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
20401/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
20402/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
20403/// ways (see the lane report) and the two agree, which is the proof that no
20404/// unwritten sample reaches the output.
20405fn fresh_plane(n: usize) -> Vec<u16> {
20406 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
20407 return vec![PLANE_SENTINEL; n];
20408 }
20409 let mut v: Vec<u16> = Vec::with_capacity(n);
20410 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
20411 // capacity was just reserved, so the vector owns `n` initialised-or-not
20412 // `u16` slots. Every one is written by reconstruction before it is read
20413 // (proven by the sentinel gate above).
20414 #[allow(unsafe_code)]
20415 unsafe {
20416 v.set_len(n);
20417 }
20418 v
20419}
20420
20421#[derive(Clone)]
20422struct PlaneBuf<'a> {
20423 data: std::borrow::Cow<'a, [u16]>,
20424 width: usize,
20425 height: usize,
20426 /// The frame's true, decodable extent in this plane's own units — past
20427 /// this, samples are the padded coding surface's invented tail, never a
20428 /// real decoder's edge or reach reads.
20429 true_width: usize,
20430 true_height: usize,
20431 /// This plane's own tile's top-left pixel origin (spec: intra prediction
20432 /// never reaches across a tile boundary even though an earlier-decoded
20433 /// tile's real pixels sit right there in the shared buffer) — set via
20434 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
20435 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
20436 /// is threaded (the two-tile column-split stage 1 fixture's tile always
20437 /// ends at the frame's own right/bottom edge); a non-last tile's own
20438 /// right/bottom reach bound is still open, tracked in the report.
20439 tile_x0: usize,
20440 tile_y0: usize,
20441 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
20442 /// (exclusive) -- a non-last tile column/row's own reach must stop at
20443 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
20444 /// full padded extent) for the single-tile/last-tile case, matching the
20445 /// old unclipped behaviour exactly.
20446 tile_x1: usize,
20447 tile_y1: usize,
20448}
20449
20450/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
20451/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
20452/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
20453/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
20454/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
20455/// `ALTREF2`/`ALTREF`).
20456// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
20457// prints one PIXWRITE line per reconstruction store landing on that sample,
20458// naming the store site, the value it replaces and the one it leaves. Re-anchored
20459// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
20460// now live in `reconstruct_mc_rect`).
20461static PIXPROBE_ON: std::sync::LazyLock<bool> =
20462 std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
20463
20464static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> = std::sync::LazyLock::new(|| {
20465 crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
20466 let (x, y) = v.split_once(',')?;
20467 Some((
20468 x.trim().parse::<usize>().ok()?,
20469 y.trim().parse::<usize>().ok()?,
20470 ))
20471 })
20472});
20473
20474#[inline]
20475fn pix_write(
20476 site: &str,
20477 bx: usize,
20478 by: usize,
20479 bside: usize,
20480 x: usize,
20481 y: usize,
20482 prev: u16,
20483 val: u16,
20484) {
20485 if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
20486 eprintln!(
20487 "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
20488 std::panic::Location::caller()
20489 );
20490 }
20491}
20492
20493impl PlaneBuf<'_> {
20494 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
20495 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
20496 /// are already in this plane's own units (luma pixels for `y`, chroma
20497 /// pixels — halved — for `u`/`v`).
20498 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
20499 self.tile_x0 = x0;
20500 self.tile_y0 = y0;
20501 self.tile_x1 = x1;
20502 self.tile_y1 = y1;
20503 }
20504
20505 fn edges(
20506 &self,
20507 x: usize,
20508 y: usize,
20509 side: usize,
20510 reach: Reach,
20511 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20512 let own_across = x + side.min(self.true_width.saturating_sub(x));
20513 let across = if reach.above_right {
20514 own_across + side.min(self.true_width.saturating_sub(own_across))
20515 } else {
20516 own_across
20517 }
20518 .min(self.width)
20519 .min(self.tile_x1);
20520 let own_down = y + side.min(self.true_height.saturating_sub(y));
20521 let down = if reach.below_left {
20522 own_down + side.min(self.true_height.saturating_sub(own_down))
20523 } else {
20524 own_down
20525 }
20526 .min(self.height)
20527 .min(self.tile_y1);
20528 let above = (y > self.tile_y0 && across > x)
20529 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20530 let left = (x > self.tile_x0 && down > y).then(|| {
20531 (y..down)
20532 .map(|row| self.data[row * self.width + x - 1])
20533 .collect::<Vec<_>>()
20534 });
20535 let corner =
20536 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20537 (above, left, corner)
20538 }
20539
20540 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
20541 /// the above/left reach each extend by their OWN axis (`bw` across,
20542 /// `bh` down), not one shared `side`.
20543 fn edges_rect(
20544 &self,
20545 x: usize,
20546 y: usize,
20547 bw: usize,
20548 bh: usize,
20549 reach: Reach,
20550 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20551 let own_across = x + bw.min(self.true_width.saturating_sub(x));
20552 let across = if reach.above_right {
20553 own_across + bw.min(self.true_width.saturating_sub(own_across))
20554 } else {
20555 own_across
20556 }
20557 .min(self.width)
20558 .min(self.tile_x1);
20559 let own_down = y + bh.min(self.true_height.saturating_sub(y));
20560 let down = if reach.below_left {
20561 own_down + bh.min(self.true_height.saturating_sub(own_down))
20562 } else {
20563 own_down
20564 }
20565 .min(self.height)
20566 .min(self.tile_y1);
20567 let above = (y > self.tile_y0 && across > x)
20568 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20569 let left = (x > self.tile_x0 && down > y).then(|| {
20570 (y..down)
20571 .map(|row| self.data[row * self.width + x - 1])
20572 .collect::<Vec<_>>()
20573 });
20574 let corner =
20575 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20576 if matches!((bw, bh), (16, 8) | (8, 16)) {
20577 hit!(RECT_STRIP_PRED_HITS);
20578 if across > own_across || down > own_down {
20579 hit!(RECT_STRIP_REACH_HITS);
20580 }
20581 }
20582 (above, left, corner)
20583 }
20584
20585 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
20586 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
20587 /// already-rect-capable `(bw, bh)` pair.
20588 #[allow(clippy::too_many_arguments)]
20589 #[track_caller]
20590 fn reconstruct_rect(
20591 &mut self,
20592 x: usize,
20593 y: usize,
20594 bw: usize,
20595 bh: usize,
20596 mode: usize,
20597 angle_delta: i32,
20598 reach: Reach,
20599 residual: &[i32],
20600 cfl: Option<(i32, &[i32])>,
20601 filter_intra: Option<usize>,
20602 smooth_neighbor: bool,
20603 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20604 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20605 // than by this replay.
20606 pred: Option<Vec<u16>>,
20607 fctx: &crate::decode::FrameCtx,
20608 ) {
20609 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
20610 // (lane-palette2 r4): a palette block's prediction is the
20611 // reconstructed colour-index map, needing no edge pixels at all.
20612 let prediction = if let Some(buf) = pred {
20613 buf
20614 } else {
20615 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
20616 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20617 eprintln!(
20618 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
20619 above.as_ref().map(|a| (a.len(), a[0])),
20620 left.as_ref().map(|l| l.len()),
20621 left.as_ref().map(|l| l[0]),
20622 self.tile_x0,
20623 self.tile_y0,
20624 self.true_width,
20625 self.true_height
20626 );
20627 }
20628 let mut prediction = vec![0u16; bw * bh];
20629 if let Some(fi_mode) = filter_intra {
20630 crate::intra::predict_filter_intra(
20631 fi_mode,
20632 above.as_deref(),
20633 left.as_deref(),
20634 corner,
20635 bw,
20636 bh,
20637 &mut prediction,
20638 fctx,
20639 );
20640 } else {
20641 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20642 predict(
20643 mode as u8,
20644 angle_delta,
20645 above.as_deref(),
20646 left.as_deref(),
20647 corner,
20648 bw,
20649 bh,
20650 enable_edge_filter,
20651 smooth_neighbor,
20652 &mut prediction,
20653 fctx,
20654 );
20655 }
20656 prediction
20657 };
20658 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20659 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20660 if crate::envflags::env_flag!("EC_PRED") {
20661 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20662 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20663 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
20664 eprintln!(
20665 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20666 std::panic::Location::caller(),
20667 recon_plane(),
20668 i32::from(smooth_neighbor)
20669 );
20670 }
20671 let residual = dense_residual(residual, bw * bh);
20672 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20673 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
20674 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20675 eprintln!(
20676 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
20677 );
20678 }
20679 for row in 0..bh {
20680 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
20681 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
20682 // whose padded width is not superblock aligned hangs past it.
20683 if y + row >= self.height {
20684 break;
20685 }
20686 for col in 0..bw {
20687 if x + col >= self.width {
20688 break;
20689 }
20690 let idx = row * bw + col;
20691 let mut base = i32::from(prediction[idx]);
20692 if let Some((alpha_q3, ac_q3)) = cfl {
20693 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20694 }
20695 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20696 pix_write(
20697 "reconstruct_rect",
20698 x,
20699 y,
20700 bw,
20701 x + col,
20702 y + row,
20703 self.data[(y + row) * self.width + x + col],
20704 sample,
20705 );
20706 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20707 }
20708 }
20709 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
20710 // -- a block whose prediction matches the oracle's but whose written
20711 // samples do not is either a residual defect or a later overwrite, and
20712 // only this print separates the two.
20713 if crate::envflags::env_flag!("EC_PRED") {
20714 let row0: Vec<u16> = (0..bw.min(8))
20715 .map(|c| self.data[y * self.width + x + c])
20716 .collect();
20717 let col0: Vec<u16> = (0..bh.min(8))
20718 .map(|r| self.data[(y + r) * self.width + x])
20719 .collect();
20720 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
20721 }
20722 }
20723
20724 /// Predicts under `mode` then adds `residual` (side*side, raster),
20725 /// writing the clamped reconstruction back into the plane at `(x, y)`.
20726 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
20727 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
20728 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
20729 /// order (cfl.c).
20730 #[track_caller]
20731 fn reconstruct(
20732 &mut self,
20733 x: usize,
20734 y: usize,
20735 side: usize,
20736 mode: usize,
20737 angle_delta: i32,
20738 reach: Reach,
20739 residual: &[i32],
20740 cfl: Option<(i32, &[i32])>,
20741 filter_intra: Option<usize>,
20742 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
20743 // libaom `get_filt_type`): true when the block's above OR left
20744 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
20745 // Callers pass their own plane's neighbour-mode check
20746 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
20747 // callers until a smooth/paeth `uv_mode` can reach this call at all
20748 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
20749 // keeps `false` exact for chroma without this fn needing to know why.
20750 smooth_neighbor: bool,
20751 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20752 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20753 // than by this replay.
20754 pred: Option<Vec<u16>>,
20755 fctx: &crate::decode::FrameCtx,
20756 ) {
20757 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
20758 // takes priority over `predict()`/`predict_filter_intra` entirely --
20759 // palette prediction needs no edge pixels at all.
20760 let prediction = if let Some(buf) = pred {
20761 buf
20762 } else {
20763 let (above, left, corner) = self.edges(x, y, side, reach);
20764 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20765 eprintln!(
20766 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
20767 above.as_deref(),
20768 left.as_deref(),
20769 );
20770 }
20771 let mut prediction = vec![0u16; side * side];
20772 if let Some(fi_mode) = filter_intra {
20773 crate::intra::predict_filter_intra(
20774 fi_mode,
20775 above.as_deref(),
20776 left.as_deref(),
20777 corner,
20778 side,
20779 side,
20780 &mut prediction,
20781 fctx,
20782 );
20783 } else {
20784 // `enable_intra_edge_filter` is the sequence header's own flag
20785 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
20786 // call, never per-block) -- threading it through every
20787 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
20788 // dozen sites for a value that never changes mid-decode, so it
20789 // rides a thread-local instead (this decoder is single-threaded
20790 // per stream).
20791 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20792 predict(
20793 mode as u8,
20794 angle_delta,
20795 above.as_deref(),
20796 left.as_deref(),
20797 corner,
20798 side,
20799 side,
20800 enable_edge_filter,
20801 smooth_neighbor,
20802 &mut prediction,
20803 fctx,
20804 );
20805 }
20806 prediction
20807 };
20808 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20809 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20810 if crate::envflags::env_flag!("EC_PRED") {
20811 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20812 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
20813 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
20814 eprintln!(
20815 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20816 std::panic::Location::caller(),
20817 recon_plane(),
20818 i32::from(smooth_neighbor)
20819 );
20820 }
20821 let residual = dense_residual(residual, side * side);
20822 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20823 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
20824 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
20825 eprintln!(
20826 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
20827 cfl.is_some()
20828 );
20829 }
20830 for row in 0..side {
20831 // lane-sb128c r8: libaom's frame buffer is superblock
20832 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
20833 // transform unit of a 128x64 block at the BOTTOM frame edge
20834 // can hang past the last padded row (1920x792: a unit at
20835 // y=768 wants 832 rows of an 800-row buffer, which panicked
20836 // the film's key frames). Those samples are outside the
20837 // frame: never output, and no block below ever references
20838 // them.
20839 if y + row >= self.height {
20840 break;
20841 }
20842 for col in 0..side {
20843 if x + col >= self.width {
20844 break;
20845 }
20846 let idx = row * side + col;
20847 let mut base = i32::from(prediction[idx]);
20848 if let Some((alpha_q3, ac_q3)) = cfl {
20849 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20850 }
20851 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20852 pix_write(
20853 "reconstruct",
20854 x,
20855 y,
20856 side,
20857 x + col,
20858 y + row,
20859 self.data[(y + row) * self.width + x + col],
20860 sample,
20861 );
20862 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20863 }
20864 }
20865 }
20866}
20867
20868/// Reads one plane's transform block, reconstructs it into `plane` at
20869/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
20870#[allow(clippy::too_many_arguments)]
20871
20872fn read_plane(
20873 dec: &mut SymbolDecoder,
20874 cdfs: &mut Cdfs,
20875 set: TxbSet,
20876 scan: &[u16],
20877 plane_idx: usize,
20878 around: (bool, bool, i32),
20879 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
20880 // it for every plane's `txb` lookup (it is what an intra transform type's
20881 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
20882 tx_mode: usize,
20883 predict_mode: usize,
20884 angle_delta: i32,
20885 reach: Reach,
20886 // lane-wave1 step (i): unread -- this reader records its write
20887 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
20888 // stays in the signature so every call site still proves the plane is
20889 // exclusively held while its coefficients are parsed.
20890 _plane: &mut PlaneBuf<'static>,
20891 x: usize,
20892 y: usize,
20893 side: usize,
20894 tx_side: usize,
20895 base_q_idx: u8,
20896 cfl: Option<(i32, CflSrc)>,
20897 filter_intra: Option<usize>,
20898 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
20899 // smaller than its own block (spec `get_txb_ctx_general`'s
20900 // `plane_bsize != tx_size` branch), carrying the already-looked-up
20901 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
20902 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
20903 // formula below.
20904 luma_skip_ctx: Option<usize>,
20905 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
20906 smooth_neighbor: bool,
20907 fctx: &crate::decode::FrameCtx,
20908) -> Result<Grid> {
20909 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
20910 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
20911 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
20912 // no chroma write is recorded. Return the all-zero grid the caller's
20913 // neighbour bookkeeping reads, without consuming a bit.
20914 if plane_idx > 0 && mono(fctx) {
20915 return Ok(Grid::Zero(side * side));
20916 }
20917 // lane-av1readcensus: the units read from here on are this plane's.
20918 set_census_plane(plane_idx);
20919 let skip_ctx = if plane_idx == 0 {
20920 luma_skip_ctx.unwrap_or(0)
20921 } else {
20922 // libaom `get_txb_ctx`: a chroma unit's context is
20923 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
20924 // plane block is bigger than the transform. Our chroma tables hold the
20925 // offset-7 rows first, so the caller adds 3 for the bigger-block case
20926 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
20927 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
20928 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
20929 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
20930 };
20931 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
20932 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
20933 // not by the block's ordinary `mode` (which is always DC_PRED whenever
20934 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
20935 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
20936 // filter-intra in AV1).
20937 let tx_mode = if plane_idx == 0 {
20938 fi_tx_row(tx_mode, filter_intra)
20939 } else {
20940 tx_mode
20941 };
20942 let mut coding = cdfs.txb(set, tx_mode);
20943 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
20944 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
20945 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
20946 // plane of a lossless block (the residual then goes through the WHT, so
20947 // the type only picks the scan, which is the default one).
20948 if lossless(fctx) {
20949 coding.tx_type = None;
20950 }
20951 // Luma's `default_tx_type` is only a fallback for the sizes whose
20952 // `TxbSet` carries no symbol at all (32-point and up), which the spec
20953 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
20954 // *never* its own coded symbol (`coding.tx_type` is always `None` for
20955 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
20956 // the plane's own predicted mode (`default_intra_tx_type`) -- except
20957 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
20958 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
20959 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
20960 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
20961 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
20962 // narrows there — only `Chroma32` and up do).
20963 let default_tx_type = if plane_idx == 0 || side >= 32 {
20964 TxType::DctDct
20965 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
20966 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
20967 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
20968 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
20969 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
20970 // [`read_inter_plane`]'s own `side < 32` guard).
20971 inherited
20972 } else {
20973 default_intra_tx_type(predict_mode as u8)
20974 };
20975 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
20976 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
20977 let default_tx_type = if lossless(fctx) {
20978 TxType::DctDct
20979 } else {
20980 default_tx_type
20981 };
20982 let (grid, tx_type) = read_coeffs(
20983 dec,
20984 &mut coding,
20985 scan,
20986 skip_ctx,
20987 dc_sign_ctx(around.2),
20988 default_tx_type,
20989 None,
20990 )?;
20991 note_chroma_class1(plane_idx, tx_type);
20992 if plane_idx == 0 {
20993 fctx.luma_tx_type.with(|c| c.set(tx_type));
20994 }
20995 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
20996 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
20997 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
20998 // guard also assumes.
20999 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
21000 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
21001 // keyed by that true size, not the coded corner's -- so the corner
21002 // goes into the top-left of a `side`-sized grid, not the reverse.
21003 let levels = extend_corner(grid, tx_side, tx_side, side, side);
21004 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
21005 let tx = TxParams {
21006 w: side,
21007 h: side,
21008 bit_depth: bit_depth(fctx),
21009 q_idx: block_q_idx(fctx),
21010 dc_delta,
21011 ac_delta,
21012 tx_type,
21013 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
21014 stride: 0,
21015 lossless: lossless(fctx),
21016 };
21017 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21018 let residual = tx.run(&levels);
21019 eprintln!(
21020 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
21021 &*levels,
21022 );
21023 }
21024 push_intra_tx(
21025 plane_idx,
21026 x,
21027 y,
21028 side,
21029 side,
21030 false,
21031 predict_mode,
21032 angle_delta,
21033 reach,
21034 tx,
21035 &levels,
21036 cfl,
21037 filter_intra,
21038 smooth_neighbor,
21039 fctx,
21040 );
21041 // `record`'s neighbour state only reads whether *the coded grid* (not the
21042 // residual) has nonzero entries, so the levels this function already
21043 // built are what it wants back -- both arms of the old `tx_side == side`
21044 // branch returned exactly that, one of them through a full `to_vec` copy
21045 // of the grid per intra transform unit (lane-coefbuf).
21046 Ok(levels)
21047}
21048
21049/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
21050/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
21051/// block's own rect shape, and the `rect` flag selects
21052/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
21053#[allow(clippy::too_many_arguments)]
21054fn push_intra_unit(
21055 plane: usize,
21056 x: usize,
21057 y: usize,
21058 w: usize,
21059 h: usize,
21060 mode: usize,
21061 angle_delta: i32,
21062 reach: Reach,
21063 residual: &[i32],
21064 cfl: Option<(i32, CflSrc)>,
21065 filter_intra: Option<usize>,
21066 smooth_neighbor: bool,
21067 fctx: &crate::decode::FrameCtx,
21068) {
21069 if w == h {
21070 push_intra(
21071 plane,
21072 x,
21073 y,
21074 w,
21075 mode,
21076 angle_delta,
21077 reach,
21078 residual,
21079 cfl,
21080 filter_intra,
21081 smooth_neighbor,
21082 fctx,
21083 );
21084 } else {
21085 push_intra_rect(
21086 plane,
21087 x,
21088 y,
21089 w,
21090 h,
21091 mode,
21092 angle_delta,
21093 reach,
21094 residual,
21095 cfl,
21096 filter_intra,
21097 smooth_neighbor,
21098 fctx,
21099 );
21100 }
21101}
21102
21103/// ONE RECT chroma transform unit of a square block's uv plane
21104/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
21105/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
21106/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
21107/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
21108/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
21109/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
21110/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
21111/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
21112/// predicted mode supplies the mode-derived default `tx_type` unless an armed
21113/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
21114/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
21115/// ([`read_plane`]'s `side >= 32` clamp).
21116#[allow(clippy::too_many_arguments)]
21117fn read_rect_chroma_unit(
21118 dec: &mut SymbolDecoder,
21119 cdfs: &mut Cdfs,
21120 set: TxbSet,
21121 scan: &[u16],
21122 w: usize,
21123 h: usize,
21124 plane_idx: usize,
21125 around: (bool, bool, i32),
21126 uv_predict_mode: usize,
21127 angle_delta_uv: i32,
21128 reach: Reach,
21129 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
21130 // the plane exclusively while the unit's coefficients are parsed.
21131 _plane: &mut PlaneBuf<'static>,
21132 x: usize,
21133 y: usize,
21134 // Signature parity with [`read_plane`]; the dequant reads its q index
21135 // off `block_q_idx(fctx)` like every other reader here.
21136 _base_q_idx: u8,
21137 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
21138 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
21139 // where `ctx_offset` is 10 when the plane block is bigger than the
21140 // transform and 7 otherwise. The port stores the offset-7 rows at
21141 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
21142 // (lane-av1-422b), so a unit SMALLER than its plane block passes
21143 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
21144 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
21145 // rect unit except in the chunk arms.
21146 chroma_skip_offset: Option<usize>,
21147 cfl: Option<(i32, CflSrc)>,
21148 smooth_neighbor_uv: bool,
21149 fctx: &crate::decode::FrameCtx,
21150) -> Result<Grid> {
21151 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
21152 hit!(CHROMA422_RECT_HITS);
21153 }
21154 let default_tx = if w.max(h) >= 32 {
21155 TxType::DctDct
21156 } else {
21157 fctx.intrabc_chroma_tx
21158 .with(std::cell::Cell::get)
21159 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8))
21160 };
21161 let mut coding = cdfs.txb(set, uv_predict_mode);
21162 let (levels, tx_type) = read_coeffs_rect(
21163 dec,
21164 &mut coding,
21165 scan,
21166 w,
21167 h,
21168 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
21169 dc_sign_ctx(around.2),
21170 default_tx,
21171 plane_idx,
21172 )?;
21173 let residual = dequant_and_inverse_typed_wh(
21174 &levels,
21175 w,
21176 h,
21177 crate::decode::bit_depth(fctx),
21178 block_q_idx(fctx),
21179 plane_q_delta(plane_idx, fctx).0,
21180 plane_q_delta(plane_idx, fctx).1,
21181 tx_type,
21182 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
21183 );
21184 push_intra_rect(
21185 plane_idx,
21186 x,
21187 y,
21188 w,
21189 h,
21190 uv_predict_mode,
21191 angle_delta_uv,
21192 reach,
21193 &residual,
21194 cfl,
21195 None,
21196 smooth_neighbor_uv,
21197 fctx,
21198 );
21199 Ok(levels)
21200}
21201
21202/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
21203/// three planes, reconstructing them into `y`/`u`/`v` and updating
21204/// `neighbours`.
21205#[allow(clippy::too_many_arguments)]
21206fn decode_block(
21207 dec: &mut SymbolDecoder,
21208 cdfs: &mut Cdfs,
21209 neighbours: &mut Neighbours,
21210 at: (usize, usize),
21211 side: usize,
21212 luma_set: TxbSet,
21213 chroma_set: TxbSet,
21214 luma_tx: usize,
21215 chroma_tx: usize,
21216 scans: (&[u16], &[u16]),
21217 cfl: bool,
21218 y: &mut PlaneBuf<'static>,
21219 u: &mut PlaneBuf<'static>,
21220 v: &mut PlaneBuf<'static>,
21221 base_q_idx: u8,
21222 enable_filter_intra: bool,
21223 allow_screen_content_tools: bool,
21224 allow_intrabc: bool,
21225 scan32: &[u16],
21226 scan16: &[u16],
21227 scan8: &[u16],
21228 scan4: &[u16],
21229 tx_select: bool,
21230 reduced_tx_set: bool,
21231 fctx: &crate::decode::FrameCtx,
21232) -> Result<()> {
21233 let (r, c) = at;
21234 let (px, py) = (c * SUB, r * SUB);
21235 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
21236 let palette_uv_cache = neighbours.palette_uv_cache(at);
21237 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
21238 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
21239 let (
21240 skip,
21241 mode,
21242 angle_delta_y,
21243 uv_mode,
21244 angle_delta_uv,
21245 alpha,
21246 filter_intra,
21247 palette_y,
21248 palette_uv,
21249 ) = read_intra_mode(
21250 dec,
21251 cdfs,
21252 nb_above_mode,
21253 nb_left_mode,
21254 cfl,
21255 side,
21256 enable_filter_intra,
21257 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
21258 allow_screen_content_tools,
21259 allow_intrabc,
21260 Some((palette_ctx, &palette_cache)),
21261 &palette_uv_cache,
21262 r * (SUB / MI),
21263 c * (SUB / MI),
21264 fctx,
21265 )?;
21266 if at_tile_left && palette_y.is_some() {
21267 hit!(PALETTE_TILE_LEFT_HITS);
21268 }
21269 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
21270 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
21271 // tables/scans are replaced by the 4x4 ones and the block always takes the
21272 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
21273 // sit at the TOP of the function -- before `read_intra_mode`, which is
21274 // where the block's own `segment_id` is read -- so a mixed frame resolved
21275 // every block's geometry against the PREVIOUS block's segment (a lossless
21276 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
21277 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
21278 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
21279 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
21280 // rewrite (which sat above `read_intra_mode`) rides along here -- same
21281 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
21282 // segment like the lossless arm above it.
21283 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
21284 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
21285 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
21286 let tx = if side >= 64 { 32 } else { side };
21287 let (set, scan): (TxbSet, &[u16]) = match tx {
21288 32 => (TxbSet::Chroma32, scan32),
21289 16 => (TxbSet::Chroma16, scan16),
21290 8 => (TxbSet::Chroma8, scan8),
21291 _ => (TxbSet::Chroma4, scan4),
21292 };
21293 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
21294 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21295 // lane-av1-422f: the uv plane block is the (side/2, side) rect
21296 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
21297 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
21298 // the RECT that fills the plane block, NOT the square transform of
21299 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
21300 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
21301 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
21302 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
21303 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
21304 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
21305 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
21306 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
21307 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
21308 let (tx_w, tx_h) = match side {
21309 4 => (4, 4),
21310 8 => (4, 8),
21311 16 => (8, 16),
21312 32 => (16, 32),
21313 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
21314 _ => (32, 32),
21315 };
21316 let (set, scan): (TxbSet, &[u16]) = match side {
21317 4 => (TxbSet::Chroma4, scan4),
21318 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
21319 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
21320 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
21321 _ => (TxbSet::Chroma32, scan32),
21322 };
21323 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
21324 } else {
21325 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
21326 };
21327 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
21328 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
21329 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
21330 // actual chroma-from-luma correlation, same as this decoder always did.
21331 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
21332 DC_PRED
21333 } else {
21334 uv_mode
21335 };
21336 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
21337 if smooth_neighbor {
21338 hit!(SMOOTH_LUMA_HITS);
21339 }
21340 let smooth_neighbor_uv =
21341 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
21342 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21343 eprintln!(
21344 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
21345 angle_delta_uv={angle_delta_uv}"
21346 );
21347 }
21348 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
21349 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
21350 // block, skipped or not. `logical_tx` is what the loop filter's edge
21351 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
21352 // transform size -- 64 even for the 64x64 corner-scanned case, spec
21353 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
21354 // which only differs from it at that one corner case.
21355 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
21356 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
21357 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
21358 // intrabc block reads NO tx-size symbol at all -- it takes
21359 // `maxRectTxSize` -- while every ordinary skipped intra block does read
21360 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
21361 // the tile from that block on (class `equal-range-means-unread`).
21362 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
21363 // tree instead (`read_var_tx_size`), the same syntax the inter block path
21364 // has always read -- libaom's `parse_decode_block` dispatches on
21365 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
21366 // intrabc block as inter.
21367 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
21368 // libaom `parse_decode_block`'s var-tx tree condition carries
21369 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
21370 // block inside a LOSSLESS segment of a mixed frame reads NO
21371 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
21372 // hands back TX_4X4. Invisible while every lossless frame was also
21373 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
21374 // is why the mixed frame is the first stream to reach it.
21375 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
21376 let intrabc_leaves = if intrabc_vartx {
21377 let max_tx = side.min(64);
21378 // `max_block_wide`/`max_block_high`: the frame's own mi grid
21379 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
21380 // right/bottom edge reads no split symbol for the units outside it.
21381 let mi_cols = 2 * y.true_width.div_ceil(8);
21382 let mi_rows = 2 * y.true_height.div_ceil(8);
21383 let side_mi = side / MI;
21384 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
21385 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
21386 let mut leaves = Vec::new();
21387 for row in (0..side_mi).step_by(max_tx / MI) {
21388 for col in (0..side_mi).step_by(max_tx / MI) {
21389 read_var_tx_size(
21390 dec,
21391 cdfs,
21392 neighbours,
21393 (mi_r, mi_c),
21394 side,
21395 (max_w_mi, max_h_mi),
21396 (max_tx, max_tx),
21397 0,
21398 row,
21399 col,
21400 &mut leaves,
21401 );
21402 }
21403 }
21404 hit!(INTRABC_VARTX_HITS);
21405 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
21406 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
21407 // longer refused -- the luma reconstruct below walks the tree's own
21408 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
21409 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
21410 // transform unit), so mixed sizes reconstruct at their own stride.
21411 // The counter marks the shape so a gate can prove a witness actually
21412 // carries a mixed tree and not merely another uniform one.
21413 let uniform = leaves.first().is_some_and(|f| {
21414 leaves
21415 .iter()
21416 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
21417 });
21418 if !uniform {
21419 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
21420 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
21421 eprintln!(
21422 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
21423 dv={intrabc_dv:?} leaves={leaves:?}"
21424 );
21425 }
21426 }
21427 Some(leaves)
21428 } else {
21429 None
21430 };
21431 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
21432 (tx, if tx == 64 { 32 } else { tx })
21433 } else if tx_select && !intrabc_skip_tx {
21434 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
21435 (resolved, if resolved == 64 { 32 } else { resolved })
21436 } else {
21437 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
21438 // TX_64X64, so a 128x128 block is always FOUR luma transform units
21439 // even with `tx_select` off -- the TU loop below, never the
21440 // single-unit path.
21441 (lossless_tx(side.min(64), fctx), luma_tx)
21442 };
21443 if tx_select && logical_tx < side && uv_mode != DC_PRED {
21444 hit!(SQ_CHROMA_TX_HITS);
21445 }
21446 let luma_set = if tx_select {
21447 txbset_for(logical_tx, reduced_tx_set)
21448 } else {
21449 luma_set
21450 };
21451 let luma_set = if intrabc_dv.is_some() {
21452 inter_txbset_for(logical_tx, reduced_tx_set)
21453 } else {
21454 luma_set
21455 };
21456 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
21457 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
21458 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
21459 let chroma_side = side >> ss_x(fctx);
21460 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
21461 // `side / 2` at 4:2:0.
21462 let chroma_height = side >> ss_y(fctx);
21463 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
21464 // frame's own pre-loop-filter reconstruction (all loop filters are off
21465 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
21466 // block vector, with the BILINEAR kernel libaom forces for intrabc --
21467 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
21468 // odd, which is exactly what the bilinear taps then interpolate.
21469 flush_recon(fctx, y, u, v);
21470 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
21471 let mut yb = vec![0u16; side * side];
21472 mc::predict_with_filter(
21473 &y.data,
21474 y.width,
21475 y.true_width,
21476 y.true_height,
21477 mv_to_q4(px, dv_col, 0),
21478 mv_to_q4(py, dv_row, 0),
21479 side,
21480 side,
21481 mc::InterpFilterKind::Bilinear,
21482 &mut yb,
21483 fctx,
21484 );
21485 let mut ub = vec![0u16; chroma_side * chroma_height];
21486 mc::predict_with_filter(
21487 &u.data,
21488 u.width,
21489 u.true_width,
21490 u.true_height,
21491 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21492 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21493 chroma_side,
21494 chroma_height,
21495 mc::InterpFilterKind::Bilinear,
21496 &mut ub,
21497 fctx,
21498 );
21499 let mut vb = vec![0u16; chroma_side * chroma_height];
21500 mc::predict_with_filter(
21501 &v.data,
21502 v.width,
21503 v.true_width,
21504 v.true_height,
21505 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21506 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21507 chroma_side,
21508 chroma_height,
21509 mc::InterpFilterKind::Bilinear,
21510 &mut vb,
21511 fctx,
21512 );
21513 (yb, ub, vb)
21514 });
21515 // A palette-Y block's own prediction is the reconstructed colour-index
21516 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
21517 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
21518 // parameter through this function's dozen `y.reconstruct`/`read_plane`
21519 // sites. A split luma transform (`tx_select && logical_tx != side`)
21520 // would need the map sliced per-TU -- untested against a real
21521 // `--enable-palette=1` stream this round, so refuse by name rather than
21522 // guess at the slicing (charter's own named-acceptable fallback).
21523 let palette_y_buf: Option<Vec<u16>> = palette_y
21524 .as_ref()
21525 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
21526 // lane-t900 r32: the intrabc luma prediction rides the very same
21527 // whole-block override slot, so the multi-TU loop below windows it per
21528 // transform unit exactly like a palette map -- setting it once up front
21529 // handed the whole `side`x`side` buffer to the FIRST unit and left every
21530 // later one predicting off block edges (the var-tx tree above is what
21531 // first makes `logical_tx < side` reachable for an intrabc block).
21532 let palette_y_buf = match &intrabc_bufs {
21533 Some((yb, _, _)) => Some(yb.clone()),
21534 None => palette_y_buf,
21535 };
21536 // With one luma transform unit the whole `side`x`side` map is the
21537 // prediction; with several (`logical_tx != side`) each unit takes its own
21538 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
21539 // below (lane-palette2 r7) -- setting the full-block buffer here would be
21540 // taken by the FIRST unit and indexed at the wrong stride.
21541 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
21542 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
21543 // `split_tx_skip` walk), so its map must be armed here even when the
21544 // transform is split. Gating the arm on `logical_tx == side` alone left a
21545 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
21546 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
21547 // key frame; class override-slot-on-one-arm). Neither prediction is
21548 // edge-derived, so the whole-block buffer at the block's own stride is
21549 // exactly what that single call wants.
21550 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
21551 // that reaches this block apart from one that never does (class
21552 // gate-blind-to-feature).
21553 if palette_y_buf.is_some() && skip && logical_tx < side {
21554 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
21555 }
21556 if let Some(buf) = &palette_y_buf
21557 && (logical_tx == side || skip)
21558 {
21559 set_palette_pred(buf.clone(), fctx);
21560 }
21561 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
21562 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
21563 // plane's own `reconstruct`/`read_plane` call below (never both planes at
21564 // once), since Y's own set-then-take already emptied the slot by the time
21565 // either of these run.
21566 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
21567 (
21568 puv.map
21569 .iter()
21570 .map(|&idx| puv.u_colors[idx as usize])
21571 .collect(),
21572 puv.map
21573 .iter()
21574 .map(|&idx| puv.v_colors[idx as usize])
21575 .collect(),
21576 )
21577 });
21578 // The chroma half of the intrabc prediction rides the same per-plane
21579 // override slot the UV-palette buffers do (set fresh before each plane's
21580 // own `reconstruct`/`read_plane` call below).
21581 let palette_uv_bufs = match &intrabc_bufs {
21582 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
21583 None => palette_uv_bufs,
21584 };
21585 if skip {
21586 // A skipped block codes no residual syntax at all (spec 5.11.34):
21587 // straight prediction, on every plane.
21588 //
21589 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
21590 // is skipped (only an INTER skip forces the largest transform), and
21591 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
21592 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
21593 // already written left/above of it inside this same block. Predicting
21594 // the whole `side`x`side` at once gives a different (uniformly off by
21595 // ~1) answer, which is exactly the residue this lane was chasing.
21596 // The palette/intrabc override path keeps the single-call shape (its
21597 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
21598 // untested for skip and unreachable in these streams).
21599 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
21600 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
21601 // per-unit prediction is keyed on the transform being smaller than
21602 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
21603 // narrower meaning (a READ split tx depth).
21604 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
21605 if split_tx_skip {
21606 if tx_select {
21607 hit!(SKIP_SPLIT_TX_HITS);
21608 }
21609 let n_axis = side / logical_tx;
21610 for tu_row in 0..n_axis {
21611 for tu_col in 0..n_axis {
21612 let tu_px = px + tu_col * logical_tx;
21613 let tu_py = py + tu_row * logical_tx;
21614 if tu_px >= y.true_width || tu_py >= y.true_height {
21615 continue;
21616 }
21617 let tu_reach = tu_reach(
21618 side,
21619 side,
21620 tu_col * logical_tx,
21621 tu_row * logical_tx,
21622 logical_tx,
21623 reach,
21624 px,
21625 py,
21626 y.width,
21627 y.height,
21628 fctx,
21629 );
21630 push_intra(
21631 0,
21632 tu_px,
21633 tu_py,
21634 logical_tx,
21635 mode,
21636 angle_delta_y,
21637 tu_reach,
21638 &ZERO_RESIDUAL[..logical_tx * logical_tx],
21639 None,
21640 filter_intra,
21641 smooth_neighbor,
21642 fctx,
21643 );
21644 }
21645 }
21646 } else {
21647 push_intra(
21648 0,
21649 px,
21650 py,
21651 side,
21652 mode,
21653 angle_delta_y,
21654 reach,
21655 &ZERO_RESIDUAL[..side * side],
21656 None,
21657 filter_intra,
21658 smooth_neighbor,
21659 fctx,
21660 );
21661 }
21662 let ac = alpha.map(|_| cfl_src(px, py, side));
21663 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
21664 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
21665 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
21666 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
21667 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
21668 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
21669 // reads ONE unit per plane, the whole plane block).
21670 let cn_cols = (chroma_side / chroma_tx).max(1);
21671 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21672 let luma_span_x = chroma_tx << ss_x(fctx);
21673 let luma_span_y = chroma_tx_h << ss_y(fctx);
21674 for cu_row in 0..cn_rows {
21675 for cu_col in 0..cn_cols {
21676 let cu_r = if cn_rows == 1 && cn_cols == 1 {
21677 reach
21678 } else {
21679 tu_reach_rect(
21680 side,
21681 side,
21682 cu_col * luma_span_x,
21683 cu_row * luma_span_y,
21684 luma_span_x,
21685 luma_span_y,
21686 reach,
21687 px,
21688 py,
21689 y.width,
21690 y.height,
21691 fctx,
21692 )
21693 };
21694 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21695 // lane-av1chromadc: the chroma override is a whole
21696 // `chroma_side x chroma_height` buffer and
21697 // `PlaneBuf::reconstruct` uses the buffer it takes as the
21698 // UNIT's own `chroma_tx x chroma_tx_h` prediction, so a
21699 // multi-unit plane block must hand each unit its own window of
21700 // it. Handing the whole buffer (the pre-fix shape) made every
21701 // unit predict from the top-left one: at 4:2:0 the chroma plane
21702 // block is a single 32x32 unit, so the whole buffer IS that
21703 // unit's window and the bug is invisible -- which is why every
21704 // 4:2:0 gate stayed green -- and at 4:4:4 a 64x64 block's 64x64
21705 // plane block is a 2x2 grid whose right and bottom columns were
21706 // a copy of its top-left unit.
21707 // MEASURED on `fixtures/r512.obu` (4:4:4 8-bit 512x512, three
21708 // frames): frame 0's skipped 64x64 intra-BC block at
21709 // `mi=(112,80)` `px=(320,448)` reconstructed its `cu=(1,0)`
21710 // unit at `px=(352,448)` as a flat 241 where the oracle has
21711 // 202 -- byte-identical to its `cu=(0,0)` prediction, sum
21712 // 882176 and all -- and the coded 64x64 to its right then read
21713 // 202/175 against the oracle's 165/166. Gate:
21714 // `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`.
21715 let chroma_window = |buf: &[u16]| -> Vec<u16> {
21716 if cn_cols == 1 && cn_rows == 1 {
21717 return buf.to_vec();
21718 }
21719 let mut window = Vec::with_capacity(chroma_tx * chroma_tx_h);
21720 for row in 0..chroma_tx_h {
21721 let at = (cu_row * chroma_tx_h + row) * chroma_side + cu_col * chroma_tx;
21722 window.extend_from_slice(&buf[at..at + chroma_tx]);
21723 }
21724 window
21725 };
21726 if let Some((ub, _)) = &palette_uv_bufs {
21727 if cn_cols * cn_rows > 1 {
21728 hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS);
21729 }
21730 set_palette_pred(chroma_window(ub), fctx);
21731 }
21732 push_intra_unit(
21733 1,
21734 cu_x,
21735 cu_y,
21736 chroma_tx,
21737 chroma_tx_h,
21738 uv_predict_mode,
21739 angle_delta_uv,
21740 cu_r,
21741 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21742 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21743 None,
21744 smooth_neighbor_uv,
21745 fctx,
21746 );
21747 if let Some((_, vb)) = &palette_uv_bufs {
21748 set_palette_pred(chroma_window(vb), fctx);
21749 }
21750 push_intra_unit(
21751 2,
21752 cu_x,
21753 cu_y,
21754 chroma_tx,
21755 chroma_tx_h,
21756 uv_predict_mode,
21757 angle_delta_uv,
21758 cu_r,
21759 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21760 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21761 None,
21762 smooth_neighbor_uv,
21763 fctx,
21764 );
21765 }
21766 }
21767 let luma_grid = vec![0i32; side * side];
21768 let u_grid = vec![0i32; chroma_side * chroma_side];
21769 let v_grid = vec![0i32; chroma_side * chroma_side];
21770 neighbours.record(
21771 at,
21772 side,
21773 mode,
21774 uv_predict_mode,
21775 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21776 );
21777 } else if logical_tx == side {
21778 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
21779 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
21780 // that arm was redundant -- and wrong at 128, where
21781 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
21782 // block is four units whether or not `tx_select` is on.
21783 // A single luma transform unit -- the old path, unchanged (including
21784 // the 64x64 corner case, `logical_tx == side == 64` with
21785 // `coeff_tx_side == 32`).
21786 let around = neighbours.around(at, side);
21787 let luma_grid = read_plane(
21788 dec,
21789 cdfs,
21790 luma_set,
21791 luma_scan,
21792 0,
21793 around[0],
21794 mode,
21795 mode,
21796 angle_delta_y,
21797 reach,
21798 y,
21799 px,
21800 py,
21801 side,
21802 coeff_tx_side,
21803 base_q_idx,
21804 None,
21805 filter_intra,
21806 None,
21807 smooth_neighbor,
21808 fctx,
21809 )?;
21810 let ac = alpha.map(|_| cfl_src(px, py, side));
21811 // Armed for exactly this block's two chroma reads (see
21812 // [`INTRABC_CHROMA_TX`]); the luma call above just set
21813 // [`LUMA_TX_TYPE`] to the type it coded.
21814 if intrabc_dv.is_some() {
21815 fctx.intrabc_chroma_tx
21816 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
21817 }
21818 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
21819 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
21820 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
21821 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
21822 // (every U, then every V) — the same loop the multi-TU arm runs.
21823 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
21824 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
21825 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
21826 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
21827 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
21828 // unit is the plane block's own rect.
21829 let cn_cols = (chroma_side / chroma_tx).max(1);
21830 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21831 let luma_span_x = chroma_tx << ss_x(fctx);
21832 let luma_span_y = chroma_tx_h << ss_y(fctx);
21833 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
21834 if chroma_tx == chroma_tx_h {
21835 if let Some((ub, _)) = &palette_uv_bufs {
21836 set_palette_pred(ub.clone(), fctx);
21837 }
21838 let u_grid = read_plane(
21839 dec,
21840 cdfs,
21841 chroma_set,
21842 scans.1,
21843 1,
21844 around[1],
21845 mode,
21846 uv_predict_mode,
21847 angle_delta_uv,
21848 reach,
21849 u,
21850 cpx,
21851 cpy,
21852 chroma_side,
21853 chroma_tx,
21854 base_q_idx,
21855 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21856 None,
21857 None,
21858 smooth_neighbor_uv,
21859 fctx,
21860 )?;
21861 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21862 eprintln!(
21863 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
21864 &u.data[cpy * u.width + cpx..][..chroma_side]
21865 );
21866 }
21867 if let Some((_, vb)) = &palette_uv_bufs {
21868 set_palette_pred(vb.clone(), fctx);
21869 }
21870 let v_grid = read_plane(
21871 dec,
21872 cdfs,
21873 chroma_set,
21874 scans.1,
21875 2,
21876 around[2],
21877 mode,
21878 uv_predict_mode,
21879 angle_delta_uv,
21880 reach,
21881 v,
21882 cpx,
21883 cpy,
21884 chroma_side,
21885 chroma_tx,
21886 base_q_idx,
21887 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21888 None,
21889 None,
21890 smooth_neighbor_uv,
21891 fctx,
21892 )?;
21893 (u_grid, v_grid, Vec::new())
21894 } else {
21895 // lane-av1-422f: the one unit is a RECT filling the plane
21896 // block -- the square-shaped [`read_plane`] cannot express
21897 // it, so both planes go through [`read_rect_chroma_unit`]
21898 // (U, then V, the same order the square arm reads). The
21899 // chroma context reads per chroma 4-px cell (see
21900 // [`Neighbours::around_mi_422_chroma`]).
21901 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
21902 if let Some((ub, _)) = &palette_uv_bufs {
21903 set_palette_pred(ub.clone(), fctx);
21904 }
21905 let u_grid = read_rect_chroma_unit(
21906 dec,
21907 cdfs,
21908 chroma_set,
21909 scans.1,
21910 chroma_tx,
21911 chroma_tx_h,
21912 1,
21913 chroma_around[1],
21914 uv_predict_mode,
21915 angle_delta_uv,
21916 reach,
21917 u,
21918 cpx,
21919 cpy,
21920 base_q_idx,
21921 None,
21922 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21923 smooth_neighbor_uv,
21924 fctx,
21925 )?;
21926 if let Some((_, vb)) = &palette_uv_bufs {
21927 set_palette_pred(vb.clone(), fctx);
21928 }
21929 let v_grid = read_rect_chroma_unit(
21930 dec,
21931 cdfs,
21932 chroma_set,
21933 scans.1,
21934 chroma_tx,
21935 chroma_tx_h,
21936 2,
21937 chroma_around[2],
21938 uv_predict_mode,
21939 angle_delta_uv,
21940 reach,
21941 v,
21942 cpx,
21943 cpy,
21944 base_q_idx,
21945 None,
21946 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21947 smooth_neighbor_uv,
21948 fctx,
21949 )?;
21950 (u_grid, v_grid, Vec::new())
21951 }
21952 } else {
21953 let chroma_ctx_offset = Some(3);
21954 let mut u_pass: Vec<Grid> = Vec::new();
21955 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21956 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21957 for plane_pass in 1..=2usize {
21958 let mut pass_idx = 0usize;
21959 for cu_row in 0..cn_rows {
21960 for cu_col in 0..cn_cols {
21961 let cu_mi = (
21962 mi_r + cu_row * (luma_span_y / MI),
21963 mi_c + cu_col * (luma_span_x / MI),
21964 );
21965 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21966 // lane-av1-422f: chroma-only loop; per-chroma-cell
21967 // above votes (see [`Neighbours::around_mi_422_chroma`]).
21968 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21969 } else {
21970 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21971 };
21972 let cu_reach = tu_reach_rect(
21973 side,
21974 side,
21975 cu_col * luma_span_x,
21976 cu_row * luma_span_y,
21977 luma_span_x,
21978 luma_span_y,
21979 reach,
21980 px,
21981 py,
21982 y.width,
21983 y.height,
21984 fctx,
21985 );
21986 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21987 if let Some((ub, vb)) = &palette_uv_bufs {
21988 let pbuf = if plane_pass == 1 { ub } else { vb };
21989 set_palette_pred(
21990 palette_window(
21991 pbuf,
21992 chroma_side,
21993 cu_col * chroma_tx,
21994 cu_row * chroma_tx_h,
21995 chroma_tx,
21996 chroma_tx_h,
21997 ),
21998 fctx,
21999 );
22000 }
22001 let buf: &mut PlaneBuf<'static> =
22002 if plane_pass == 1 { &mut *u } else { &mut *v };
22003 let cu_grid = read_plane(
22004 dec,
22005 cdfs,
22006 chroma_set,
22007 scans.1,
22008 plane_pass,
22009 cu_around[plane_pass],
22010 mode,
22011 uv_predict_mode,
22012 angle_delta_uv,
22013 cu_reach,
22014 buf,
22015 cu_x,
22016 cu_y,
22017 chroma_tx,
22018 chroma_tx,
22019 base_q_idx,
22020 alpha
22021 .zip(ac)
22022 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
22023 None,
22024 chroma_ctx_offset,
22025 smooth_neighbor_uv,
22026 fctx,
22027 )?;
22028 hit!(CHROMA_SPLIT_TX_HITS);
22029 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22030 hit!(CHROMA422_SQUARE_HITS);
22031 }
22032 // Immediately, so the next unit of this block reads this
22033 // one's coefficient context. `record` below stamps one
22034 // chroma state across the whole block; the replay after
22035 // it puts the per-unit state back.
22036 neighbours.record_mi_chroma(
22037 cu_mi,
22038 luma_span_x,
22039 luma_span_y,
22040 plane_pass,
22041 &cu_grid,
22042 );
22043 if plane_pass == 1 {
22044 u_pass.push(cu_grid);
22045 } else {
22046 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22047 units.push((
22048 cu_mi,
22049 luma_span_x,
22050 luma_span_y,
22051 u_grid.clone(),
22052 cu_grid.clone(),
22053 ));
22054 last_grids = [u_grid, cu_grid];
22055 }
22056 pass_idx += 1;
22057 }
22058 }
22059 }
22060 (last_grids[0].clone(), last_grids[1].clone(), units)
22061 };
22062 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22063 neighbours.record(
22064 at,
22065 side,
22066 mode,
22067 uv_predict_mode,
22068 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22069 );
22070 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
22071 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
22072 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
22073 }
22074 } else {
22075 // Several luma transform units, raster order (spec
22076 // `transform_block`'s loop): the block's resolved transform is
22077 // genuinely smaller than its own side, so each tile of it predicts
22078 // and codes independently, its own context read fresh off whatever
22079 // the earlier tiles in this same block already wrote -- the same
22080 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
22081 let n_axis = side / logical_tx;
22082 // lane-av1-422f: unit width/height per axis, like walk 2 above --
22083 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
22084 // chunk, the whole plane block.
22085 let cn_cols = (chroma_side / chroma_tx).max(1);
22086 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22087 let luma_span_x = chroma_tx << ss_x(fctx);
22088 let luma_span_y = chroma_tx_h << ss_y(fctx);
22089 // libaom's transform-block loop is over 64x64 luma "mu" chunks
22090 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
22091 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
22092 // before moving to the next one. Below 128 a block is a single chunk,
22093 // so this is byte-for-byte the all-luma-then-all-chroma order that has
22094 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
22095 // and reading all four luma units first desyncs the tile at the second
22096 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
22097 let nchunk = (side / 64).max(1);
22098 // `cn > 1` means the uv plane block is larger than the uv transform,
22099 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
22100 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
22101 let tpc = (n_axis / nchunk).max(1);
22102 let cpc_rows = (cn_rows / nchunk).max(1);
22103 let cpc_cols = (cn_cols / nchunk).max(1);
22104 // The block's luma transform units, raster order inside each mu
22105 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
22106 // tree's own leaf list -- mixed sizes included, exactly what libaom's
22107 // `decode_token_recon_block` token loop reconstructs (one
22108 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
22109 // while every other block's list is the uniform `logical_tx` grid
22110 // this loop has always walked, generated here in the same order.
22111 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
22112 if let Some(leaves) = &intrabc_leaves {
22113 for &(lr, lc, tw, _th) in leaves {
22114 let (off_y, off_x) = (lr * MI, lc * MI);
22115 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
22116 }
22117 } else {
22118 for tu_row in 0..n_axis {
22119 for tu_col in 0..n_axis {
22120 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
22121 tu_row * logical_tx,
22122 tu_col * logical_tx,
22123 logical_tx,
22124 ));
22125 }
22126 }
22127 }
22128 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22129 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22130 for ch_row in 0..nchunk {
22131 for ch_col in 0..nchunk {
22132 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
22133 // type of the co-located luma position (`av1_get_tx_type`,
22134 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
22135 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
22136 // luma unit covering it). Inside a mu chunk that is the chunk's
22137 // FIRST luma unit in raster order (the chunk origin is always the
22138 // first leaf's own origin). Captured right after that unit's read;
22139 // the single-TU arm below does the same for a whole-block unit.
22140 let mut first_leaf_tx: Option<TxType> = None;
22141 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
22142 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
22143 let tu_px = px + tu_off_x;
22144 let tu_py = py + tu_off_y;
22145 // Same libaom clip as `decode_rect_split`'s loop above; a
22146 // square block only hangs off the frame when the frame's mi
22147 // dimensions are odd at the block's own level.
22148 if tu_px >= y.true_width || tu_py >= y.true_height {
22149 continue;
22150 }
22151 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
22152 // A transform unit inside a block is NOT a block at that
22153 // position (lane-palette2 r12): `Reach::of` granted the
22154 // top-right 8x8 unit of a 16x16 D203 block bottom-left
22155 // pixels libaom refuses outright (`col_off > 0`), which is
22156 // the diagonal wedge seed 46 reconstructed wrong.
22157 let tu_reach = tu_reach(
22158 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
22159 fctx,
22160 );
22161 // This transform unit's own bsize (`tu_tx`) is smaller
22162 // than the block it sits in (`side`), so `txb_skip_ctx` is
22163 // the neighbour-magnitude table, not the lone-TU 0 (spec
22164 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
22165 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
22166 // An intrabc unit's CDF set and scan follow the unit's OWN
22167 // resolved size (`get_txsize_entropy_ctx` /
22168 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
22169 // uniform grid's precomputed pair already matches because
22170 // `tu_tx == logical_tx` there.
22171 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
22172 (
22173 inter_txbset_for(tu_tx, reduced_tx_set),
22174 scan_for(
22175 if tu_tx == 64 { 32 } else { tu_tx },
22176 scan32,
22177 scan16,
22178 scan8,
22179 scan4,
22180 ),
22181 )
22182 } else {
22183 (luma_set, luma_scan)
22184 };
22185 if let Some(buf) = &palette_y_buf {
22186 hit!(PALETTE_SPLIT_TX_HITS);
22187 let mut window = vec![0u16; tu_tx * tu_tx];
22188 for row in 0..tu_tx {
22189 let src = (tu_off_y + row) * side + tu_off_x;
22190 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
22191 }
22192 set_palette_pred(window, fctx);
22193 }
22194 let tu_grid = read_plane(
22195 dec,
22196 cdfs,
22197 tu_set,
22198 tu_scan,
22199 0,
22200 tu_around,
22201 mode,
22202 mode,
22203 angle_delta_y,
22204 tu_reach,
22205 y,
22206 tu_px,
22207 tu_py,
22208 tu_tx,
22209 // The unit's own COEFFICIENT grid, half its side at
22210 // TX_64X64 (a 64-point transform codes nothing past 32);
22211 // identical to `tu_tx` at every smaller size
22212 // (lane-sb128b r1).
22213 if tu_tx == 64 { 32 } else { tu_tx },
22214 base_q_idx,
22215 None,
22216 filter_intra,
22217 Some(tu_skip_ctx),
22218 smooth_neighbor,
22219 fctx,
22220 )?;
22221 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22222 eprintln!(
22223 "TRACE tu_bitpos mi=({},{}) tell={}",
22224 tu_mi.0,
22225 tu_mi.1,
22226 dec.debug_bitpos()
22227 );
22228 }
22229 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
22230 if first_leaf_tx.is_none() {
22231 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
22232 }
22233 }
22234 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
22235 // this still runs after every luma unit of the block.
22236 let ac = alpha.map(|_| cfl_src(px, py, side));
22237 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
22238 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
22239 // branch sets before its own chroma reads.
22240 if intrabc_dv.is_some() {
22241 if let Some(t) = first_leaf_tx {
22242 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
22243 }
22244 }
22245 // The block's uv plane block is `chroma_side` across but its uv
22246 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
22247 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
22248 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
22249 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
22250 // FOUR units (lane-sb128b r2) -- one per mu chunk.
22251 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
22252 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
22253 // the chunk, then every V unit. At one unit per plane per chunk --
22254 // every non-lossless case this decoder reaches -- that is the same
22255 // symbol order as the interleaved pair this loop used to read; a
22256 // lossless frame's 4x4 chroma units are the case where it differs
22257 // (lane-lossless2).
22258 let mut u_pass: Vec<Grid> = Vec::new();
22259 for plane_pass in 1..=2usize {
22260 let mut pass_idx = 0usize;
22261 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
22262 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
22263 // libaom `decode_reconstruct_tx`'s frame-edge clip
22264 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
22265 // >= max_blocks_wide` returns before ANY symbol is read): a
22266 // transform unit whose 4x4 origin sits outside the frame's mi
22267 // grid is not coded at all. The luma loop above carries the
22268 // same clip; its absence here read `txb_skip` (+coeffs) for
22269 // chroma units libaom never wrote -- the lossless 64x64 block
22270 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
22271 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
22272 // eight (lane-av1-loss64; 48 chroma units per plane in
22273 // aomdec's EC_COEFF census vs the 64 this loop read).
22274 // `max_block_wide/high` (av1_common_int.h:1565): the plane
22275 // block's pixel span (4:2:0 halves the luma span, clamped to
22276 // 4 by `set_plane_n4`) plus the negative overhang
22277 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
22278 // units.
22279 let span_mi = side / MI;
22280 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
22281 - mi_c as i32
22282 - span_mi as i32;
22283 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
22284 - mi_r as i32
22285 - span_mi as i32;
22286 // `max_block_wide/high` in chroma pixels: the plane block's
22287 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
22288 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
22289 // block's coded units and desynced the tile) plus the
22290 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
22291 // chroma-px scale is `MI >> ss` per mi.
22292 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
22293 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
22294 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
22295 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
22296 // lane-av1-422f: the shared halved formula in the `else` counts
22297 // the plane span in 4-px units through the 2-px-per-mi
22298 // subsampled height, which a 4:2:2 plane does not have (ss_y
22299 // 0) -- its span is the full luma mi count, so a keyed
22300 // formula clips the same units libaom's `max_block_high`
22301 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
22302 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
22303 // pre-ss form spelled).
22304 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22305 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
22306 } else {
22307 ((plane_px + over_h_px) >> 2).max(0) as usize
22308 };
22309 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
22310 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
22311 hit!(CHROMA_EDGE_TU_CLIP_HITS);
22312 continue;
22313 }
22314 // The chroma context arrays are indexed in LUMA mi, so this
22315 // unit's anchor is its own luma quadrant (lane-av1-422b: the
22316 // quadrant spans `chroma_tx << ss_x` luma px wide by
22317 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
22318 // one unit's quadrant is the whole block).
22319 let cu_mi = (
22320 mi_r + cu_row * (luma_span_y / MI),
22321 mi_c + cu_col * (luma_span_x / MI),
22322 );
22323 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22324 // lane-av1-422f: chroma-only loop; per-chroma-cell above
22325 // votes (see [`Neighbours::around_mi_422_chroma`]).
22326 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
22327 } else {
22328 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
22329 };
22330 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
22331 reach
22332 } else {
22333 tu_reach_rect(
22334 side,
22335 side,
22336 cu_col * luma_span_x,
22337 cu_row * luma_span_y,
22338 luma_span_x,
22339 luma_span_y,
22340 reach,
22341 px,
22342 py,
22343 y.width,
22344 y.height,
22345 fctx,
22346 )
22347 };
22348 let (cu_x, cu_y) =
22349 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22350 if let Some((ub, vb)) = &palette_uv_bufs {
22351 let pbuf = if plane_pass == 1 { ub } else { vb };
22352 set_palette_pred(
22353 palette_window(
22354 pbuf,
22355 chroma_side,
22356 cu_col * chroma_tx,
22357 cu_row * chroma_tx_h,
22358 chroma_tx,
22359 chroma_tx_h,
22360 ),
22361 fctx,
22362 );
22363 }
22364 let buf: &mut PlaneBuf<'static> =
22365 if plane_pass == 1 { &mut *u } else { &mut *v };
22366 let cu_grid = if chroma_tx == chroma_tx_h {
22367 read_plane(
22368 dec,
22369 cdfs,
22370 chroma_set,
22371 scans.1,
22372 plane_pass,
22373 cu_around[plane_pass],
22374 mode,
22375 uv_predict_mode,
22376 angle_delta_uv,
22377 cu_reach,
22378 buf,
22379 cu_x,
22380 cu_y,
22381 chroma_tx,
22382 chroma_tx,
22383 base_q_idx,
22384 alpha.zip(ac).map(|((au, av), ac)| {
22385 (if plane_pass == 1 { au } else { av }, ac)
22386 }),
22387 None,
22388 chroma_ctx_offset,
22389 smooth_neighbor_uv,
22390 fctx,
22391 )?
22392 } else {
22393 // lane-av1-422f: the whole plane block as one rect unit;
22394 // `chroma_ctx_offset` is `None` there (the unit covers
22395 // the plane block, so the offset-7 skip rows are right).
22396 read_rect_chroma_unit(
22397 dec,
22398 cdfs,
22399 chroma_set,
22400 scans.1,
22401 chroma_tx,
22402 chroma_tx_h,
22403 plane_pass,
22404 cu_around[plane_pass],
22405 uv_predict_mode,
22406 angle_delta_uv,
22407 cu_reach,
22408 buf,
22409 cu_x,
22410 cu_y,
22411 base_q_idx,
22412 None,
22413 alpha.zip(ac).map(|((au, av), ac)| {
22414 (if plane_pass == 1 { au } else { av }, ac)
22415 }),
22416 smooth_neighbor_uv,
22417 fctx,
22418 )?
22419 };
22420 if cn_rows * cn_cols > 1 {
22421 hit!(CHROMA_SPLIT_TX_HITS);
22422 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22423 hit!(CHROMA422_SQUARE_HITS);
22424 }
22425 // Immediately, so the NEXT unit of this same block reads
22426 // this one's coefficient context (libaom's chroma
22427 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
22428 // 1 from this left neighbour -- measured against aomdec).
22429 // The same writes are replayed after `record_split_luma`
22430 // below, which would otherwise clobber them whole-block.
22431 neighbours.record_mi_chroma(
22432 cu_mi,
22433 luma_span_x,
22434 luma_span_y,
22435 plane_pass,
22436 &cu_grid,
22437 );
22438 }
22439 if plane_pass == 1 {
22440 u_pass.push(cu_grid);
22441 } else {
22442 let u_grid =
22443 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22444 if cn_rows * cn_cols > 1 {
22445 units.push((
22446 cu_mi,
22447 luma_span_x,
22448 luma_span_y,
22449 u_grid.clone(),
22450 cu_grid.clone(),
22451 ));
22452 }
22453 last_grids = [u_grid, cu_grid];
22454 }
22455 pass_idx += 1;
22456 }
22457 }
22458 }
22459 }
22460 if intrabc_dv.is_some() {
22461 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22462 }
22463 }
22464 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
22465 // context write; at `cn > 1` the per-unit writes above are what the
22466 // next block reads, so they run after this (last writer wins).
22467 neighbours.record_split_luma(
22468 at,
22469 side,
22470 mode,
22471 uv_predict_mode,
22472 [&last_grids[0], &last_grids[1]],
22473 );
22474 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
22475 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
22476 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
22477 }
22478 }
22479 // Unconditional, `size == 0` for a non-palette block: clears any stale
22480 // neighbour palette state the same way [`Neighbours::record`] always
22481 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
22482 // (the split-luma-TU branch above always refuses before reaching here
22483 // when `palette_y` is `Some`, so it is never live for that branch).
22484 let (py_size, py_colors) = palette_y
22485 .as_ref()
22486 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22487 neighbours.record_palette_y(at, side, py_size, py_colors);
22488 let (puv_size, puv_colors) = palette_uv
22489 .as_ref()
22490 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22491 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
22492 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
22493 neighbours.fill_lf_grid(
22494 (r * (SUB / MI), c * (SUB / MI)),
22495 side / MI,
22496 logical_tx as u8,
22497 0,
22498 fctx,
22499 );
22500 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
22501 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
22502 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
22503 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
22504 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
22505 // intrabc block publish its BLOCK size instead, intrabc being the only
22506 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
22507 // stays the authority wherever one can appear; with `allow_intrabc` unset
22508 // it writes exactly what the grid already did.
22509 if allow_intrabc {
22510 set_txfm_ctxs(
22511 neighbours,
22512 (mi_r, mi_c),
22513 logical_tx,
22514 side / MI,
22515 side / MI,
22516 skip && intrabc_dv.is_some(),
22517 );
22518 }
22519 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
22520 Ok(())
22521}
22522
22523thread_local! {
22524 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
22525 /// root's HORZ arm, and 64x128 ones at its VERT arm.
22526 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22527 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22528 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
22529 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
22530 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
22531 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
22532 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
22533 /// inter frame) -- (128x64, 64x128).
22534 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
22535 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
22536 /// handed back var-tx leaves, so the per-transform-unit luma publication
22537 /// loop never ran and the block has to clear its own luma coefficient
22538 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
22539 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
22540 /// non-vacuous.
22541 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22542 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
22543 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
22544 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
22545 /// shape non-vacuous -- a stream that never codes one reads 0.
22546 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22547 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
22548 /// intra block re-stamped by the end-of-block replay
22549 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
22550 /// walk published, so every unit replays its own state after it). A
22551 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
22552 /// of them, so this reads 0 on any stream that never codes one -- the
22553 /// non-vacuity anchor for the replay's own gate.
22554 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22555 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
22556 /// height differs from the unit's own LUMA-MI height -- the signature of the
22557 /// width passed to both axes (`luma_span` where the in-loop stamp used
22558 /// `luma_span_h`). Zero on every stream this decoder admits: both
22559 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
22560 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
22561 /// at the sequence header (`stream::decode_frame`), so the arm is
22562 /// defensive until that format is ported. The counter turns a future
22563 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
22564 /// of silent mi-state corruption.
22565 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22566}
22567
22568/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
22569pub fn skip_vartx_luma_reset_hits() -> usize {
22570 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
22571}
22572
22573/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
22574pub(crate) fn intra128_lossless_hits() -> usize {
22575 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
22576}
22577
22578/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
22579pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
22580 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
22581}
22582
22583/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
22584/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
22585pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
22586 (
22587 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
22588 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
22589 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
22590 )
22591}
22592
22593/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
22594/// `decode_block_128rect`'s end-of-block replay) and
22595/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
22596/// not the unit's own), for a gate's own before/after delta.
22597pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
22598 (
22599 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
22600 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
22601 )
22602}
22603
22604/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
22605/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
22606/// `decode_inter_block`'s own rect path).
22607///
22608/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
22609/// transform unit, with the 128-specific geometry:
22610/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
22611/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
22612/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
22613/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
22614/// same CDF a 64x64 square block reads).
22615/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
22616/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
22617/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
22618/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
22619/// a chunk before moving to the next (the interleave lane-sb128b r3
22620/// measured at the 128x128 NONE root).
22621/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
22622/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
22623/// No CfL, no filter intra (both cap at 32x32) and no palette
22624/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
22625/// reader's own size gates already say so, and the guard below is defensive.
22626///
22627/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
22628/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
22629/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
22630/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
22631/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
22632/// units, plane-major inside each 64x64 mu chunk exactly as
22633/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
22634/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
22635/// this lane closed); the geometry and the unit walks below are normalized on
22636/// `lossless_frame`.
22637#[allow(clippy::too_many_arguments)]
22638fn decode_block_128rect(
22639 dec: &mut SymbolDecoder,
22640 cdfs: &mut Cdfs,
22641 neighbours: &mut Neighbours,
22642 at: (usize, usize),
22643 bw: usize,
22644 bh: usize,
22645 y: &mut PlaneBuf<'static>,
22646 u: &mut PlaneBuf<'static>,
22647 v: &mut PlaneBuf<'static>,
22648 base_q_idx: u8,
22649 enable_filter_intra: bool,
22650 allow_screen_content_tools: bool,
22651 tx_select: bool,
22652 reduced_tx_set: bool,
22653 fctx: &crate::decode::FrameCtx,
22654) -> Result<()> {
22655 let (r, c) = at;
22656 let (px, py) = (c * SUB, r * SUB);
22657 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
22658 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22659 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
22660 let palette_uv_cache = neighbours.palette_uv_cache(at);
22661 let (
22662 skip,
22663 mode,
22664 angle_delta_y,
22665 uv_mode,
22666 angle_delta_uv,
22667 alpha,
22668 filter_intra,
22669 palette_y,
22670 palette_uv,
22671 intrabc,
22672 ) = read_intra_mode_rect(
22673 dec,
22674 cdfs,
22675 nb_above_mode,
22676 nb_left_mode,
22677 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
22678 // 13-symbol no-CFL CDF here, never the 14-symbol one.
22679 false,
22680 true,
22681 bw,
22682 bh,
22683 enable_filter_intra,
22684 neighbours.skip_txfm_ctx(mi_r, mi_c),
22685 allow_screen_content_tools,
22686 Some((palette_ctx, &palette_cache)),
22687 &palette_uv_cache,
22688 mi_r,
22689 mi_c,
22690 fctx,
22691 )?;
22692 if let Some((dv_row, dv_col)) = intrabc {
22693 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
22694 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
22695 // from this frame's own reconstruction and runs the INTER residual
22696 // walk (`decode_token_recon_block`'s else arm) over it.
22697 return decode_intrabc_128rect(
22698 dec,
22699 cdfs,
22700 neighbours,
22701 (mi_r, mi_c),
22702 (bw, bh),
22703 skip,
22704 (dv_row, dv_col),
22705 y,
22706 u,
22707 v,
22708 base_q_idx,
22709 fctx,
22710 );
22711 }
22712 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
22713 return Err(unsupported(
22714 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
22715 their size gates caps at 64x64 or below, so none of these symbols exists there)",
22716 ));
22717 }
22718 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22719 DC_PRED
22720 } else {
22721 uv_mode
22722 };
22723 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22724 if smooth_neighbor {
22725 hit!(SMOOTH_LUMA_HITS);
22726 }
22727 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
22728 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
22729 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
22730 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
22731 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
22732 // before the symbol is even considered (`decodeframe.c:141`) and
22733 // `read_tx_size` returns `TX_4X4` before it looks at anything
22734 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
22735 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
22736 let lossless_frame = lossless(fctx);
22737 let in_inter = fctx
22738 .intra_in_inter_mode
22739 .with(std::cell::Cell::get)
22740 .is_some();
22741 let depth = if tx_select && !lossless_frame {
22742 // lane-inter128intra r1: `get_tx_size_context` compares the bands
22743 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
22744 // TX_64X64 for every 128-axis block, hence the `min(64)`.
22745 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
22746 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
22747 } else {
22748 0
22749 };
22750 if depth != 0 {
22751 hit!(TX_DEPTH_HITS);
22752 }
22753 hit_do! {
22754 INTRA_SB128_DEPTH_HITS.with(|c| {
22755 let mut h = c.get();
22756 h[depth.min(2)] += 1;
22757 c.set(h);
22758 });
22759 }
22760 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
22761 if lossless_frame {
22762 hit!(INTRA128_LOSSLESS_HITS);
22763 }
22764 // A 64-point transform codes nothing past its low 32 coefficients.
22765 let coeff_tx_side = logical_tx.min(32);
22766 let luma_set = if lossless_frame {
22767 TxbSet::Luma4
22768 } else {
22769 txbset_for(logical_tx, reduced_tx_set)
22770 };
22771 let luma_scan = default_scan(coeff_tx_side);
22772 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
22773 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
22774 let chroma_tx = if lossless_frame { 4 } else { 32 };
22775 let chroma_set = if lossless_frame {
22776 TxbSet::Chroma4
22777 } else {
22778 TxbSet::Chroma32
22779 };
22780 let chroma_scan = default_scan(chroma_tx);
22781 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22782 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
22783 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
22784 let (nch_x, nch_y) = (bw / 64, bh / 64);
22785 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
22786 // `decode_token_recon_block` clips each vector's walk to
22787 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
22788 // codes nothing.
22789 let mi_cols = 2 * y.true_width.div_ceil(8);
22790 let mi_rows = 2 * y.true_height.div_ceil(8);
22791 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
22792 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
22793 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
22794 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
22795 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
22796 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
22797 debug_assert!(
22798 lossless_frame
22799 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
22800 == (
22801 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
22802 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
22803 )
22804 );
22805 let tpc = 64 / logical_tx;
22806 let zero_tu = vec![0i32; logical_tx * logical_tx];
22807 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
22808 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22809 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
22810 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
22811 // every chunk shares this luma span (2 chroma pixels per luma unit).
22812 let luma_span = chroma_tx << ss_x(fctx);
22813 let luma_span_h = chroma_tx << ss_y(fctx);
22814 for ch_row in 0..nch_y {
22815 for ch_col in 0..nch_x {
22816 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
22817 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
22818 let tu_mi = (
22819 mi_r + tu_row * (logical_tx / MI),
22820 mi_c + tu_col * (logical_tx / MI),
22821 );
22822 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
22823 // libaom clips the transform loop to
22824 // `max_blocks_wide/high`: a unit whose top-left sample is
22825 // outside the frame is never coded.
22826 if tu_px >= y.true_width || tu_py >= y.true_height {
22827 continue;
22828 }
22829 // Edge availability of a unit INSIDE a block, with the
22830 // 128 geometry -- `has_top_right` is false for a block
22831 // whose largest side is > 64, which [`Reach::of_rect`]
22832 // already answered for the block and [`tu_reach`] carries
22833 // down to the units on its own top row.
22834 let tu_r = tu_reach(
22835 bw,
22836 bh,
22837 tu_col * logical_tx,
22838 tu_row * logical_tx,
22839 logical_tx,
22840 reach,
22841 px,
22842 py,
22843 y.width,
22844 y.height,
22845 fctx,
22846 );
22847 if skip {
22848 push_intra(
22849 0,
22850 tu_px,
22851 tu_py,
22852 logical_tx,
22853 mode,
22854 angle_delta_y,
22855 tu_r,
22856 &zero_tu,
22857 None,
22858 None,
22859 smooth_neighbor,
22860 fctx,
22861 );
22862 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
22863 continue;
22864 }
22865 // The unit is smaller than its block, so `txb_skip_ctx`
22866 // is the neighbour-magnitude table, never the lone-TU 0.
22867 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
22868 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
22869 let tu_grid = read_plane(
22870 dec,
22871 cdfs,
22872 luma_set,
22873 &luma_scan,
22874 0,
22875 tu_around,
22876 mode,
22877 mode,
22878 angle_delta_y,
22879 tu_r,
22880 y,
22881 tu_px,
22882 tu_py,
22883 logical_tx,
22884 coeff_tx_side,
22885 base_q_idx,
22886 None,
22887 None,
22888 Some(tu_skip_ctx),
22889 smooth_neighbor,
22890 fctx,
22891 )?;
22892 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
22893 }
22894 }
22895 // Transform units per axis inside this mu chunk's chroma span:
22896 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
22897 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
22898 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
22899 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
22900 // chroma plane block is 32x64 there, so the two axes' counts
22901 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
22902 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
22903 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
22904 // libaom's per-chunk `unit_width/height` (plane-mi units of the
22905 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
22906 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
22907 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
22908 let stepc = (chroma_tx / 4).max(1);
22909 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
22910 // unit of the chunk, then every V unit. At one unit per plane per
22911 // chunk (every non-lossless 128-axis block) that is the same
22912 // symbol order the interleaved pair used to read; a lossless
22913 // frame's 4x4 chroma units are where it becomes observable.
22914 for plane_pass in 1..=2usize {
22915 for ci_row in 0..cn_h {
22916 for ci_col in 0..cn {
22917 // The clamp strides are the CHUNK's chroma mi extent
22918 // per axis: 16 luma mi >> the axis's own ss.
22919 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
22920 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
22921 {
22922 continue;
22923 }
22924 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
22925 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
22926 let cu_mi = (
22927 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
22928 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
22929 );
22930 let cu_r = tu_reach_rect(
22931 bw,
22932 bh,
22933 ch_col * 64 + ci_col * luma_span,
22934 ch_row * 64 + ci_row * luma_span_h,
22935 luma_span,
22936 luma_span_h,
22937 reach,
22938 px,
22939 py,
22940 y.width,
22941 y.height,
22942 fctx,
22943 );
22944 if skip {
22945 push_intra(
22946 plane_pass,
22947 cu_x,
22948 cu_y,
22949 chroma_tx,
22950 uv_predict_mode,
22951 angle_delta_uv,
22952 cu_r,
22953 &zero_cu,
22954 None,
22955 None,
22956 smooth_neighbor_uv,
22957 fctx,
22958 );
22959 continue;
22960 }
22961 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
22962 let buf: &mut PlaneBuf<'static> =
22963 if plane_pass == 1 { &mut *u } else { &mut *v };
22964 let grid = read_plane(
22965 dec,
22966 cdfs,
22967 chroma_set,
22968 &chroma_scan,
22969 plane_pass,
22970 cu_around[plane_pass],
22971 mode,
22972 uv_predict_mode,
22973 angle_delta_uv,
22974 cu_r,
22975 buf,
22976 cu_x,
22977 cu_y,
22978 chroma_tx,
22979 chroma_tx,
22980 base_q_idx,
22981 None,
22982 None,
22983 Some(3),
22984 smooth_neighbor_uv,
22985 fctx,
22986 )?;
22987 last_grids[plane_pass - 1] = grid.clone();
22988 // Immediately, so the NEXT unit of this same block
22989 // reads this one's coefficient context; replayed after
22990 // `record_split_luma_rect` below, which would otherwise
22991 // clobber them whole-block.
22992 neighbours.record_mi_chroma(
22993 cu_mi,
22994 luma_span,
22995 luma_span_h,
22996 plane_pass,
22997 &grid,
22998 );
22999 units.push((plane_pass, cu_mi, grid));
23000 }
23001 }
23002 }
23003 if !skip {
23004 hit!(CHROMA_SPLIT_TX_HITS);
23005 }
23006 }
23007 }
23008 if skip {
23009 neighbours.record_rect(
23010 at,
23011 bw,
23012 bh,
23013 mode,
23014 uv_predict_mode,
23015 &[
23016 &ZERO_RESIDUAL[..bw * bh],
23017 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23018 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23019 ],
23020 );
23021 } else {
23022 neighbours.record_split_luma_rect(
23023 at,
23024 bw,
23025 bh,
23026 mode,
23027 uv_predict_mode,
23028 [&last_grids[0], &last_grids[1]],
23029 );
23030 // lane-av1-128rectspan: the replay must re-stamp each unit over the
23031 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
23032 // height drives `left[]` and its width `above[]`, and the walk used
23033 // the per-axis `luma_span_h`. Passing the width on both axes doubled
23034 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
23035 // rows below the block on the last unit of a 128x64/64x128 strip and
23036 // smearing a neighbour chunk's unit over its neighbour's rows.
23037 //
23038 // DEFENSIVE at the decoder's current capability set: both admitted
23039 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
23040 // (0,0)), so the two spans are equal and this line is a no-op on
23041 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
23042 // format where they differ -- is refused by name at the sequence
23043 // header, so the arm is unreachable there. It stays per-axis because
23044 // the walk it replays is per-axis, and a 4:2:2 port must not have to
23045 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
23046 // day that changes.
23047 if luma_span != luma_span_h {
23048 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
23049 }
23050 for (plane, cu_mi, grid) in &units {
23051 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
23052 hit!(SB128RECT_CHROMA_REPLAY_HITS);
23053 }
23054 }
23055 // No palette exists at this size; the unconditional stamp clears any
23056 // stale neighbour palette state, as every other block path does.
23057 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
23058 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
23059 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
23060 neighbours.fill_lf_grid_rect(
23061 (mi_r, mi_c),
23062 bw / MI,
23063 bh / MI,
23064 logical_tx as u8,
23065 logical_tx as u8,
23066 0,
23067 fctx,
23068 );
23069 if in_inter || allow_intrabc_frame(fctx) {
23070 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
23071 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
23072 // inter frame, intra ones included: an intra block stamps its
23073 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
23074 // A key frame reads those bands only when it allows intrabc
23075 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
23076 // stamps here too -- lane-av1-intrabc r3.
23077 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
23078 }
23079 if in_inter {
23080 hit_do! {
23081 INTRA128_IN_INTER_HITS.with(|c| {
23082 let mut h = c.get();
23083 h[usize::from(bw < bh)] += 1;
23084 c.set(h);
23085 });
23086 }
23087 } else if bw > bh {
23088 hit!(INTRA_SB128_HORZ_HITS);
23089 } else {
23090 hit!(INTRA_SB128_VERT_HITS);
23091 }
23092 Ok(())
23093}
23094
23095/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
23096/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
23097/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
23098/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
23099/// just-decoded mode, not the enclosing slot's stale one, is the true
23100/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
23101/// units, which is what its coefficient context (finer than [`SUB`]) is read
23102/// at. Returns the mode this leaf decoded, for the caller's own
23103/// `prev_leaf`/final mode-writeback bookkeeping.
23104#[allow(clippy::too_many_arguments)]
23105/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
23106/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
23107/// `above_mode[col]`, and its true above neighbour is the mi directly above
23108/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
23109/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
23110/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
23111/// (bottom-right) into both, as this path did, is right only when all four
23112/// leaves happen to share a mode. `done` may be short at the true frame edge
23113/// (the straddle caller filters positions off the frame), so each side falls
23114/// back to the last leaf actually decoded.
23115fn write_back_split_modes(
23116 neighbours: &mut Neighbours,
23117 done: &[((usize, usize), usize)],
23118 parent_mi: (usize, usize),
23119 slot: (usize, usize),
23120) {
23121 let (sr, sc) = slot;
23122 let Some(&(_, last)) = done.last() else {
23123 return;
23124 };
23125 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
23126 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
23127 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
23128}
23129
23130fn decode_leaf8(
23131 dec: &mut SymbolDecoder,
23132 cdfs: &mut Cdfs,
23133 neighbours: &mut Neighbours,
23134 outer_at: (usize, usize),
23135 leaf_mi: (usize, usize),
23136 scans: (&[u16], &[u16]),
23137 prev_leaf: Option<((usize, usize), usize)>,
23138 y: &mut PlaneBuf<'static>,
23139 u: &mut PlaneBuf<'static>,
23140 v: &mut PlaneBuf<'static>,
23141 base_q_idx: u8,
23142 enable_filter_intra: bool,
23143 allow_screen_content_tools: bool,
23144 allow_intrabc: bool,
23145 tx_select: bool,
23146 reduced_tx_set: bool,
23147 fctx: &crate::decode::FrameCtx,
23148) -> Result<usize> {
23149 let (r, c) = outer_at;
23150 // lane-modectx r1: the group's own availability-correct fallback pair, not
23151 // the raw coarse bands (which leak across a tile edge -- see
23152 // `modes_above_left`).
23153 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
23154 if let Some(((pr, pc), pmode)) = prev_leaf {
23155 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
23156 above_mode = pmode;
23157 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
23158 left_mode = pmode;
23159 }
23160 }
23161 // The mi-exact neighbour wins over both the coarse 16x16 slot and
23162 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
23163 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
23164 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
23165 // lane-rectsplitx r2 swept this arm into
23166 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
23167 // "no neighbour" at a tile edge, where the coarse cell holds the block
23168 // above/left of it inside the same 16x16.
23169 let (above_mode, left_mode) =
23170 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
23171 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
23172 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
23173 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
23174 // this leaf's `smooth_neighbor` is built from -- passing `false` here
23175 // filtered a directional chroma block's edge at the wrong strength
23176 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
23177 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
23178 // with the coarse [`SUB`] slot as the fallback when no block recorded
23179 // that exact mi cell.
23180 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
23181 if smooth_neighbor {
23182 hit!(SMOOTH_LUMA_HITS);
23183 }
23184 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
23185 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
23186 // `decode_block` caller at 16x16 and up.
23187 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
23188 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
23189 // `read_palette_mode_info`), at its REAL mi position -- passing
23190 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
23191 // moment a real 8x8 palette block fired, which is where every 8-bit
23192 // `--tune-content=screen --min-partition-size=8` stream stopped.
23193 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
23194 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
23195 let (
23196 skip,
23197 mode,
23198 angle_delta_y,
23199 uv_mode,
23200 angle_delta_uv,
23201 alpha,
23202 filter_intra,
23203 palette_y,
23204 palette_uv,
23205 ) = read_intra_mode(
23206 dec,
23207 cdfs,
23208 above_mode,
23209 left_mode,
23210 true,
23211 8,
23212 enable_filter_intra,
23213 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
23214 allow_screen_content_tools,
23215 allow_intrabc,
23216 Some((palette_ctx, &palette_cache)),
23217 &palette_uv_cache,
23218 leaf_mi.0,
23219 leaf_mi.1,
23220 fctx,
23221 )?;
23222 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
23223 // `read_intra_mode` and then decoded the block as if it were ordinary
23224 // intra. libaom's `is_inter_block` counts an intrabc block
23225 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
23226 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
23227 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
23228 // same value with a different interval, so the tile desynced at the very
23229 // next symbol (class `wrong-alphabet-same-value`). Everything below
23230 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
23231 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
23232 if intrabc_dv.is_some() {
23233 hit!(LEAF8_INTRABC_HITS);
23234 }
23235 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
23236 // index map, mapped through the base colours, IS the block's prediction --
23237 // carried to the next `reconstruct`/`read_plane` through the same
23238 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
23239 let palette_y_buf: Option<Vec<u16>> = palette_y
23240 .as_ref()
23241 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
23242 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
23243 (
23244 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
23245 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
23246 )
23247 });
23248 let (pal_y_size, pal_y_colors) = palette_y
23249 .as_ref()
23250 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
23251 let (pal_uv_size, pal_uv_colors) = palette_uv
23252 .as_ref()
23253 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
23254 if palette_y.is_some() || palette_uv.is_some() {
23255 hit!(PALETTE_LEAF8_HITS);
23256 }
23257 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23258 DC_PRED
23259 } else {
23260 uv_mode
23261 };
23262 neighbours.above_uv_mode[c] = uv_predict_mode;
23263 neighbours.left_uv_mode[r] = uv_predict_mode;
23264 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
23265 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
23266 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
23267 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
23268 // transform units, same raster-order per-TU pattern `decode_block`'s
23269 // multi-TU branch runs).
23270 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
23271 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
23272 // intrabc block, so a SKIPPED one takes the largest transform and an
23273 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
23274 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
23275 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
23276 // `parse_decode_block`'s tree condition carries
23277 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
23278 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
23279 // `read_tx_size`'s first line (lane-av1mixloss).
23280 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
23281 let mut leaves = Vec::new();
23282 let mi_cols = 2 * y.true_width.div_ceil(8);
23283 let mi_rows = 2 * y.true_height.div_ceil(8);
23284 read_var_tx_size(
23285 dec,
23286 cdfs,
23287 neighbours,
23288 leaf_mi,
23289 8,
23290 (
23291 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
23292 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
23293 ),
23294 (8, 8),
23295 0,
23296 0,
23297 0,
23298 &mut leaves,
23299 );
23300 hit!(INTRABC_VARTX_HITS);
23301 leaves.first().map_or(8, |l| l.2)
23302 } else if tx_select && intrabc_dv.is_none() {
23303 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
23304 } else {
23305 // lane-lossless: TX_4X4 on a lossless frame, no symbol
23306 // (libaom `read_tx_size`).
23307 lossless_tx(8, fctx)
23308 };
23309 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
23310 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
23311 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
23312 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
23313 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
23314 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
23315 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
23316 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
23317 // TX_4X8): one txb_skip + one scan per plane in the
23318 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
23319 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
23320 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
23321 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
23322 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
23323 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
23324 let (csz, cset, cscan) = if chroma_444 {
23325 (8usize, TxbSet::Chroma8, scans.0)
23326 } else {
23327 (4usize, TxbSet::Chroma4, scans.1)
23328 };
23329 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
23330 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
23331 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
23332 // the full-pel block vector, with the BILINEAR kernel libaom forces.
23333 flush_recon(fctx, y, u, v);
23334 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
23335 let mut yb = vec![0u16; 8 * 8];
23336 mc::predict_with_filter(
23337 &y.data,
23338 y.width,
23339 y.true_width,
23340 y.true_height,
23341 mv_to_q4(px, dv_col, 0),
23342 mv_to_q4(py, dv_row, 0),
23343 8,
23344 8,
23345 mc::InterpFilterKind::Bilinear,
23346 &mut yb,
23347 fctx,
23348 );
23349 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
23350 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
23351 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
23352 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
23353 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
23354 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
23355 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
23356 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
23357 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
23358 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
23359 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
23360 // so all three heal with this one sizing.
23361 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
23362 let mut ub = vec![0u16; cw * ch];
23363 mc::predict_with_filter(
23364 &u.data,
23365 u.width,
23366 u.true_width,
23367 u.true_height,
23368 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23369 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23370 cw,
23371 ch,
23372 mc::InterpFilterKind::Bilinear,
23373 &mut ub,
23374 fctx,
23375 );
23376 let mut vb = vec![0u16; cw * ch];
23377 mc::predict_with_filter(
23378 &v.data,
23379 v.width,
23380 v.true_width,
23381 v.true_height,
23382 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23383 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23384 cw,
23385 ch,
23386 mc::InterpFilterKind::Bilinear,
23387 &mut vb,
23388 fctx,
23389 );
23390 (yb, ub, vb)
23391 });
23392 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
23393 // `decode_block` uses: set fresh right before each plane's own
23394 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
23395 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
23396 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
23397 // first shape that reaches that loop with an override set).
23398 let palette_y_buf = match &intrabc_bufs {
23399 Some((yb, _, _)) => Some(yb.clone()),
23400 None => palette_y_buf,
23401 };
23402 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
23403 // `decode_block` does the same for its own `palette_uv_bufs`
23404 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
23405 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
23406 // chroma reads with the override unset: the unit predicted INTRA from
23407 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
23408 // R5 first differing pixel U(184,4), block mi (2,92).
23409 let palette_uv_bufs = match &intrabc_bufs {
23410 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
23411 None => palette_uv_bufs,
23412 };
23413 let (luma_grid, u_grid, v_grid);
23414 if skip {
23415 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
23416 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
23417 // transform units, each off the units already written left/above of
23418 // it inside this same leaf -- an intra block's transform size is read
23419 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
23420 // A palette block's prediction is the whole-block index map, never
23421 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
23422 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
23423 // even when `tx_depth` resolved to TX_4X4.
23424 if resolved == 4 && palette_y_buf.is_none() {
23425 hit!(SKIP_SPLIT_TX_HITS);
23426 for tu_row in 0..2 {
23427 for tu_col in 0..2 {
23428 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
23429 if tu_px >= y.true_width || tu_py >= y.true_height {
23430 continue;
23431 }
23432 let tu_reach = tu_reach(
23433 8,
23434 8,
23435 tu_col * 4,
23436 tu_row * 4,
23437 4,
23438 reach,
23439 px,
23440 py,
23441 y.width,
23442 y.height,
23443 fctx,
23444 );
23445 push_intra(
23446 0,
23447 tu_px,
23448 tu_py,
23449 4,
23450 mode,
23451 angle_delta_y,
23452 tu_reach,
23453 &ZERO_RESIDUAL[..16],
23454 None,
23455 filter_intra,
23456 smooth_neighbor,
23457 fctx,
23458 );
23459 }
23460 }
23461 } else {
23462 if let Some(buf) = &palette_y_buf {
23463 set_palette_pred(buf.clone(), fctx);
23464 }
23465 push_intra(
23466 0,
23467 px,
23468 py,
23469 8,
23470 mode,
23471 angle_delta_y,
23472 reach,
23473 &ZERO_RESIDUAL[..64],
23474 None,
23475 filter_intra,
23476 smooth_neighbor,
23477 fctx,
23478 );
23479 }
23480 let ac = alpha.map(|_| cfl_src(px, py, 8));
23481 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
23482 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
23483 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
23484 // skip-arm rule); no coefficient symbol exists, so the entropy
23485 // context never enters the rect read.
23486 if chroma_422 {
23487 u_grid = leaf8_chroma422_unit(
23488 dec,
23489 cdfs,
23490 (false, false, 0),
23491 uv_predict_mode,
23492 angle_delta_uv,
23493 reach,
23494 1,
23495 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23496 true,
23497 intrabc_bufs
23498 .as_ref()
23499 .map(|(_, ub, _)| ub.clone())
23500 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23501 u,
23502 cpx,
23503 cpy,
23504 smooth_neighbor_uv,
23505 fctx,
23506 )?;
23507 v_grid = leaf8_chroma422_unit(
23508 dec,
23509 cdfs,
23510 (false, false, 0),
23511 uv_predict_mode,
23512 angle_delta_uv,
23513 reach,
23514 2,
23515 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23516 true,
23517 intrabc_bufs
23518 .as_ref()
23519 .map(|(_, _, vb)| vb.clone())
23520 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23521 v,
23522 cpx,
23523 cpy,
23524 smooth_neighbor_uv,
23525 fctx,
23526 )?;
23527 luma_grid = Grid::Zero(64);
23528 } else {
23529 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
23530 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
23531 // plane), so a skipped leaf predicts per unit -- each from its own
23532 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
23533 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
23534 // chroma plane block is 8x8), and intrabc/palette keep the
23535 // whole-plane-block prediction they already run. The guard also
23536 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
23537 let chroma_units_444 =
23538 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
23539 if let Some((_, ub, _)) = &intrabc_bufs {
23540 set_palette_pred(ub.clone(), fctx);
23541 } else if let Some((ub, _)) = &palette_uv_bufs {
23542 set_palette_pred(ub.clone(), fctx);
23543 }
23544 if chroma_units_444 {
23545 for cu_row in 0..2 {
23546 for cu_col in 0..2 {
23547 let cu_reach = tu_reach(
23548 8,
23549 8,
23550 cu_col * 4,
23551 cu_row * 4,
23552 4,
23553 reach,
23554 px,
23555 py,
23556 y.width,
23557 y.height,
23558 fctx,
23559 );
23560 push_intra(
23561 1,
23562 cpx + cu_col * 4,
23563 cpy + cu_row * 4,
23564 4,
23565 uv_predict_mode,
23566 angle_delta_uv,
23567 cu_reach,
23568 &ZERO_RESIDUAL[..16],
23569 None,
23570 None,
23571 smooth_neighbor_uv,
23572 fctx,
23573 );
23574 }
23575 }
23576 } else {
23577 push_intra(
23578 1,
23579 cpx,
23580 cpy,
23581 csz,
23582 uv_predict_mode,
23583 angle_delta_uv,
23584 reach,
23585 &ZERO_RESIDUAL[..csz * csz],
23586 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23587 None,
23588 smooth_neighbor_uv,
23589 fctx,
23590 );
23591 }
23592 if let Some((_, _, vb)) = &intrabc_bufs {
23593 set_palette_pred(vb.clone(), fctx);
23594 } else if let Some((_, vb)) = &palette_uv_bufs {
23595 set_palette_pred(vb.clone(), fctx);
23596 }
23597 if chroma_units_444 {
23598 for cu_row in 0..2 {
23599 for cu_col in 0..2 {
23600 let cu_reach = tu_reach(
23601 8,
23602 8,
23603 cu_col * 4,
23604 cu_row * 4,
23605 4,
23606 reach,
23607 px,
23608 py,
23609 y.width,
23610 y.height,
23611 fctx,
23612 );
23613 push_intra(
23614 2,
23615 cpx + cu_col * 4,
23616 cpy + cu_row * 4,
23617 4,
23618 uv_predict_mode,
23619 angle_delta_uv,
23620 cu_reach,
23621 &ZERO_RESIDUAL[..16],
23622 None,
23623 None,
23624 smooth_neighbor_uv,
23625 fctx,
23626 );
23627 }
23628 }
23629 } else {
23630 push_intra(
23631 2,
23632 cpx,
23633 cpy,
23634 csz,
23635 uv_predict_mode,
23636 angle_delta_uv,
23637 reach,
23638 &ZERO_RESIDUAL[..csz * csz],
23639 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23640 None,
23641 smooth_neighbor_uv,
23642 fctx,
23643 );
23644 }
23645 luma_grid = Grid::Zero(64);
23646 u_grid = Grid::Zero(csz * csz);
23647 v_grid = Grid::Zero(csz * csz);
23648 }
23649 } else if resolved != 4 {
23650 let around = neighbours.around_mi(leaf_mi, 8);
23651 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
23652 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
23653 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
23654 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
23655 // the doubled sum crosses zero (the same class
23656 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
23657 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
23658 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
23659 let chroma_around = if chroma_422 {
23660 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23661 } else {
23662 around
23663 };
23664 if let Some(buf) = &palette_y_buf {
23665 set_palette_pred(buf.clone(), fctx);
23666 }
23667 luma_grid = read_plane(
23668 dec,
23669 cdfs,
23670 if intrabc_dv.is_some() {
23671 inter_txbset_for(8, reduced_tx_set)
23672 } else if reduced_tx_set {
23673 TxbSet::Luma8
23674 } else {
23675 TxbSet::Luma8Set1
23676 },
23677 scans.0,
23678 0,
23679 around[0],
23680 mode,
23681 mode,
23682 angle_delta_y,
23683 reach,
23684 y,
23685 px,
23686 py,
23687 8,
23688 TX8,
23689 base_q_idx,
23690 None,
23691 filter_intra,
23692 None,
23693 smooth_neighbor,
23694 fctx,
23695 )?;
23696 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
23697 // an intrabc block's chroma tx_type is the colocated LUMA transform's
23698 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
23699 if intrabc_dv.is_some() {
23700 fctx.intrabc_chroma_tx
23701 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
23702 }
23703 let ac = alpha.map(|_| cfl_src(px, py, 8));
23704 if chroma_422 {
23705 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
23706 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
23707 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
23708 u_grid = leaf8_chroma422_unit(
23709 dec,
23710 cdfs,
23711 chroma_around[1],
23712 uv_predict_mode,
23713 angle_delta_uv,
23714 reach,
23715 1,
23716 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23717 false,
23718 intrabc_bufs
23719 .as_ref()
23720 .map(|(_, ub, _)| ub.clone())
23721 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23722 u,
23723 cpx,
23724 cpy,
23725 smooth_neighbor_uv,
23726 fctx,
23727 )?;
23728 v_grid = leaf8_chroma422_unit(
23729 dec,
23730 cdfs,
23731 chroma_around[2],
23732 uv_predict_mode,
23733 angle_delta_uv,
23734 reach,
23735 2,
23736 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23737 false,
23738 intrabc_bufs
23739 .as_ref()
23740 .map(|(_, _, vb)| vb.clone())
23741 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23742 v,
23743 cpx,
23744 cpy,
23745 smooth_neighbor_uv,
23746 fctx,
23747 )?;
23748 } else {
23749 if let Some((_, ub, _)) = &intrabc_bufs {
23750 set_palette_pred(ub.clone(), fctx);
23751 } else if let Some((ub, _)) = &palette_uv_bufs {
23752 set_palette_pred(ub.clone(), fctx);
23753 }
23754 u_grid = read_plane(
23755 dec,
23756 cdfs,
23757 cset,
23758 cscan,
23759 1,
23760 around[1],
23761 mode,
23762 uv_predict_mode,
23763 angle_delta_uv,
23764 reach,
23765 u,
23766 cpx,
23767 cpy,
23768 csz,
23769 csz,
23770 base_q_idx,
23771 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23772 None,
23773 None,
23774 smooth_neighbor_uv,
23775 fctx,
23776 )?;
23777 if let Some((_, _, vb)) = &intrabc_bufs {
23778 set_palette_pred(vb.clone(), fctx);
23779 } else if let Some((_, vb)) = &palette_uv_bufs {
23780 set_palette_pred(vb.clone(), fctx);
23781 }
23782 v_grid = read_plane(
23783 dec,
23784 cdfs,
23785 cset,
23786 cscan,
23787 2,
23788 around[2],
23789 mode,
23790 uv_predict_mode,
23791 angle_delta_uv,
23792 reach,
23793 v,
23794 cpx,
23795 cpy,
23796 csz,
23797 csz,
23798 base_q_idx,
23799 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23800 None,
23801 None,
23802 smooth_neighbor_uv,
23803 fctx,
23804 )?;
23805 }
23806 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
23807 // two chroma reads (`decode_block`'s own tail does the same) -- left
23808 // set, every later chroma block would inherit this luma tx_type,
23809 // which picks the scan and the inverse transform.
23810 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23811 } else {
23812 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
23813 // grid of 4x4 transform units, each predicted from the leaf's own
23814 // 8x8 `mode` and reading its own fresh context off the earlier
23815 // units in this same leaf (the same per-TU pattern `decode_block`'s
23816 // multi-TU branch runs at bigger blocks).
23817 let mut first_leaf_tx: Option<TxType> = None;
23818 for tu_row in 0..2 {
23819 for tu_col in 0..2 {
23820 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
23821 let tu_px = px + tu_col * 4;
23822 let tu_py = py + tu_row * 4;
23823 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
23824 if crate::encode::Reach::in_vert_ab() {
23825 hit!(VERT_AB_TX4_HITS);
23826 }
23827 let tu_reach = tu_reach(
23828 8,
23829 8,
23830 tu_col * 4,
23831 tu_row * 4,
23832 4,
23833 reach,
23834 px,
23835 py,
23836 y.width,
23837 y.height,
23838 fctx,
23839 );
23840 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
23841 // Each 4x4 unit predicts from its own window of the block's
23842 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
23843 // 16x16 and up) -- the whole-block buffer would be taken by
23844 // the FIRST unit and indexed at the wrong stride.
23845 if let Some(buf) = &palette_y_buf {
23846 hit!(PALETTE_SPLIT_TX_HITS);
23847 let mut window = vec![0u16; 16];
23848 for row in 0..4 {
23849 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
23850 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
23851 }
23852 set_palette_pred(window, fctx);
23853 }
23854 let tu_grid = read_plane(
23855 dec,
23856 cdfs,
23857 if intrabc_dv.is_some() {
23858 inter_txbset_for(4, reduced_tx_set)
23859 } else if reduced_tx_set {
23860 TxbSet::Luma4
23861 } else {
23862 TxbSet::Luma4Set1
23863 },
23864 scans.1,
23865 0,
23866 tu_around,
23867 mode,
23868 mode,
23869 angle_delta_y,
23870 tu_reach,
23871 y,
23872 tu_px,
23873 tu_py,
23874 4,
23875 4,
23876 base_q_idx,
23877 None,
23878 filter_intra,
23879 Some(tu_skip_ctx),
23880 smooth_neighbor,
23881 fctx,
23882 )?;
23883 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23884 eprintln!(
23885 "TRACE tu_bitpos mi=({},{}) tell={}",
23886 tu_mi.0,
23887 tu_mi.1,
23888 dec.debug_bitpos()
23889 );
23890 }
23891 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
23892 // The FIRST (top-left, co-located with this group's chroma)
23893 // TU's coded tx_type is what the group's chroma inherits --
23894 // the same capture [`decode_block`]'s multi-TU branch makes
23895 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
23896 // an inter-classified block's `PLANE_TYPE_UV` reads
23897 // `tx_type_map`, and intrabc is inter-classified).
23898 if first_leaf_tx.is_none() {
23899 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
23900 }
23901 }
23902 }
23903 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
23904 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
23905 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
23906 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
23907 // the inherited luma type's (R5's first fork: mi (36,66), luma
23908 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
23909 // decoded its `eob` from the wrong CDF row). Same arm the
23910 // `resolved != 4` branch above runs for its whole-leaf unit.
23911 if intrabc_dv.is_some() {
23912 if let Some(t) = first_leaf_tx {
23913 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
23914 }
23915 }
23916 let ac = alpha.map(|_| cfl_src(px, py, 8));
23917 // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm
23918 // above -- the doubled above sum crosses zero at mi(2,24) plane 2.
23919 let chroma_around = if chroma_422 {
23920 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23921 } else {
23922 neighbours.around_mi(leaf_mi, 8)
23923 };
23924 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
23925 // by this arm's chroma reads means the frame-copy + inherited-type
23926 // route ran; zero at gate time means the fixture stopped reaching it.
23927 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
23928 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
23929 }
23930 if chroma_422 {
23931 // lane-av1-422d: the chroma unit does NOT follow the luma var-tx
23932 // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block,
23933 // still the one 4x8 rect unit per plane at ss (1,0).
23934 u_grid = leaf8_chroma422_unit(
23935 dec,
23936 cdfs,
23937 chroma_around[1],
23938 uv_predict_mode,
23939 angle_delta_uv,
23940 reach,
23941 1,
23942 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23943 false,
23944 intrabc_bufs
23945 .as_ref()
23946 .map(|(_, ub, _)| ub.clone())
23947 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23948 u,
23949 cpx,
23950 cpy,
23951 smooth_neighbor_uv,
23952 fctx,
23953 )?;
23954 v_grid = leaf8_chroma422_unit(
23955 dec,
23956 cdfs,
23957 chroma_around[2],
23958 uv_predict_mode,
23959 angle_delta_uv,
23960 reach,
23961 2,
23962 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23963 false,
23964 intrabc_bufs
23965 .as_ref()
23966 .map(|(_, _, vb)| vb.clone())
23967 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23968 v,
23969 cpx,
23970 cpy,
23971 smooth_neighbor_uv,
23972 fctx,
23973 )?;
23974 } else if chroma_444 && lossless(fctx) {
23975 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
23976 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
23977 // lossless forces TX_4X4 on EVERY plane) -- the same walk
23978 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
23979 // TX_8X8 unit here panicked before: the lossless inverse is the
23980 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
23981 // invariant), and the unit count desyncs the tile either way.
23982 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
23983 // inside, which is why the tail's whole-leaf chroma stamp below
23984 // is skipped for this shape.
23985 let (mut uo, mut vo) = (Vec::new(), Vec::new());
23986 read_intra_chroma_lossless(
23987 dec,
23988 cdfs,
23989 neighbours,
23990 u,
23991 v,
23992 leaf_mi,
23993 (px, py),
23994 (cpx, cpy),
23995 8,
23996 (8, 8),
23997 (0, 0),
23998 (8, 8),
23999 8,
24000 reach,
24001 (y.width, y.height),
24002 mode,
24003 uv_predict_mode,
24004 angle_delta_uv,
24005 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
24006 smooth_neighbor_uv,
24007 base_q_idx,
24008 &mut uo,
24009 &mut vo,
24010 fctx,
24011 )?;
24012 u_grid = if uo.is_empty() {
24013 Grid::Zero(64)
24014 } else {
24015 Grid::Own(uo)
24016 };
24017 v_grid = if vo.is_empty() {
24018 Grid::Zero(64)
24019 } else {
24020 Grid::Own(vo)
24021 };
24022 } else {
24023 if let Some((ub, _)) = &palette_uv_bufs {
24024 set_palette_pred(ub.clone(), fctx);
24025 }
24026 u_grid = read_plane(
24027 dec,
24028 cdfs,
24029 cset,
24030 cscan,
24031 1,
24032 chroma_around[1],
24033 mode,
24034 uv_predict_mode,
24035 angle_delta_uv,
24036 reach,
24037 u,
24038 cpx,
24039 cpy,
24040 csz,
24041 csz,
24042 base_q_idx,
24043 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24044 None,
24045 None,
24046 smooth_neighbor_uv,
24047 fctx,
24048 )?;
24049 if let Some((_, vb)) = &palette_uv_bufs {
24050 set_palette_pred(vb.clone(), fctx);
24051 }
24052 v_grid = read_plane(
24053 dec,
24054 cdfs,
24055 cset,
24056 cscan,
24057 2,
24058 chroma_around[2],
24059 mode,
24060 uv_predict_mode,
24061 angle_delta_uv,
24062 reach,
24063 v,
24064 cpx,
24065 cpy,
24066 csz,
24067 csz,
24068 base_q_idx,
24069 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24070 None,
24071 None,
24072 smooth_neighbor_uv,
24073 fctx,
24074 )?;
24075 }
24076 // The two chroma reads above are the only consulters of this leaf's
24077 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
24078 // leaf's chroma inherit this leaf's luma type instead of its own
24079 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
24080 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
24081 // luma's `V_ADST` for its chroma eob row).
24082 if intrabc_dv.is_some() {
24083 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24084 }
24085 // `record_split_luma` expects a `record`-style `(r, c)` position in
24086 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
24087 // already in mi units, so calling it here double-scaled the
24088 // position. Plane 0 is already correct per-TU from the
24089 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
24090 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
24091 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
24092 // leaf's own 8x8 side over `MI`).
24093 let side_mi = 2;
24094 for cell in 0..side_mi {
24095 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
24096 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
24097 }
24098 let round_up_even = |n: usize| n.div_ceil(2) * 2;
24099 let bound_h = round_up_even(neighbours.mi_rows);
24100 let bound_w = round_up_even(neighbours.mi_cols);
24101 let u_state = neighbour_state(&u_grid);
24102 let v_state = neighbour_state(&v_grid);
24103 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
24104 // (its raster-order last writer per cell is exactly libaom's
24105 // per-entry last update); this whole-leaf aggregate would clobber
24106 // four distinct unit states with one, so it runs only for the shapes
24107 // whose chroma really is one unit.
24108 if !(chroma_444 && lossless(fctx)) {
24109 for cell in 0..side_mi {
24110 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
24111 neighbours.left[leaf_mi.0 + cell][1] = u_state;
24112 neighbours.left[leaf_mi.0 + cell][2] = v_state;
24113 }
24114 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
24115 neighbours.above[leaf_mi.1 + cell][1] = u_state;
24116 neighbours.above[leaf_mi.1 + cell][2] = v_state;
24117 }
24118 }
24119 }
24120 // This leaf's own palette state into the mi-granular above/left bands
24121 // (sizes 0 when it used none, which is what clears a previous block's
24122 // palette out of the next block's ctx and colour cache).
24123 {
24124 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
24125 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
24126 }
24127 neighbours.fill_skip_grid(leaf_mi, 2, skip);
24128 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
24129 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
24130 // own copy; only an intrabc var-tx read consumes these bands on the intra
24131 // path, so the write is armed by `allow_intrabc`.
24132 if allow_intrabc {
24133 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
24134 }
24135 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
24136 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
24137 return Ok(mode);
24138 }
24139 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
24140 // This leaf's own palette state into the mi-granular above/left bands
24141 // (sizes 0 when it used none, which is what clears a previous block's
24142 // palette out of the next block's ctx and colour cache).
24143 {
24144 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
24145 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
24146 }
24147 hit!(INTER8_SKIP_BAND_HITS);
24148 neighbours.fill_skip_grid(leaf_mi, 2, skip);
24149 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
24150 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
24151 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
24152 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
24153 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
24154 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
24155 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
24156 // wrong CDF row, so the msac range diverged mid-frame with no refusal
24157 // (class `wrong-alphabet-same-value`; the ReelB key frame at
24158 // -ss 900, first bad luma sample row 186 col 1803).
24159 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
24160 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
24161 // `decode_block`'s own copy for why this stays beside
24162 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
24163 // BLOCK-size term).
24164 if allow_intrabc {
24165 set_txfm_ctxs(
24166 neighbours,
24167 leaf_mi,
24168 resolved,
24169 2,
24170 2,
24171 skip && intrabc_dv.is_some(),
24172 );
24173 }
24174 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
24175 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
24176 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
24177 // publish its own cells exactly like `decode_block` does.
24178 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
24179 Ok(mode)
24180}
24181
24182/// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf
24183/// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and
24184/// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to
24185/// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is
24186/// a single rect unit -- one txb_skip + one scan per plane in the
24187/// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
24188/// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved
24189/// position: the entropy context is the leaf's own 8x8 luma-span
24190/// above/left state (the `chroma_tiled` arm's convention; no `+3`
24191/// plane-block-bigger term -- the unit covers the plane block exactly), the
24192/// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted
24193/// mode supplies the mode-derived default `tx_type` unless an armed
24194/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller
24195/// arms and disarms it, exactly as it does around its square reads).
24196#[allow(clippy::too_many_arguments)]
24197fn leaf8_chroma422_unit(
24198 dec: &mut SymbolDecoder,
24199 cdfs: &mut Cdfs,
24200 around: (bool, bool, i32),
24201 uv_predict_mode: usize,
24202 angle_delta_uv: i32,
24203 reach: Reach,
24204 plane_idx: usize,
24205 cfl: Option<(i32, CflSrc)>,
24206 skip: bool,
24207 // The prediction override the square arms feed through
24208 // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes
24209 // priority over a palette block's colour-index map.
24210 pred_override: Option<Vec<u16>>,
24211 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
24212 // the plane exclusively while the unit's coefficients are parsed.
24213 _plane: &mut PlaneBuf<'static>,
24214 cpx: usize,
24215 cpy: usize,
24216 smooth_neighbor_uv: bool,
24217 fctx: &crate::decode::FrameCtx,
24218) -> Result<Grid> {
24219 // The unit's prediction runs whether or not a residual follows it -- a
24220 // skipped leaf still predicts (the CfL contribution survives a skip),
24221 // and a skipped intrabc leaf still copies the frame at its DV.
24222 if let Some(buf) = pred_override {
24223 set_palette_pred(buf, fctx);
24224 }
24225 if skip {
24226 push_intra_rect(
24227 plane_idx,
24228 cpx,
24229 cpy,
24230 4,
24231 8,
24232 uv_predict_mode,
24233 angle_delta_uv,
24234 reach,
24235 &ZERO_RESIDUAL[..4 * 8],
24236 cfl,
24237 None,
24238 smooth_neighbor_uv,
24239 fctx,
24240 );
24241 return Ok(Grid::Zero(4 * 8));
24242 }
24243 let default_tx = fctx
24244 .intrabc_chroma_tx
24245 .with(std::cell::Cell::get)
24246 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8));
24247 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
24248 let (levels, tx_type) = read_coeffs_rect(
24249 dec,
24250 &mut coding,
24251 &SCAN_4X8,
24252 4,
24253 8,
24254 usize::from(around.0) + usize::from(around.1),
24255 dc_sign_ctx(around.2),
24256 default_tx,
24257 plane_idx,
24258 )?;
24259 let residual = dequant_and_inverse_typed_wh(
24260 &levels,
24261 4,
24262 8,
24263 crate::decode::bit_depth(fctx),
24264 block_q_idx(fctx),
24265 plane_q_delta(plane_idx, fctx).0,
24266 plane_q_delta(plane_idx, fctx).1,
24267 tx_type,
24268 block_iqmatrix(fctx, plane_idx, 4, 8, tx_type),
24269 );
24270 push_intra_rect(
24271 plane_idx,
24272 cpx,
24273 cpy,
24274 4,
24275 8,
24276 uv_predict_mode,
24277 angle_delta_uv,
24278 reach,
24279 &residual,
24280 cfl,
24281 None,
24282 smooth_neighbor_uv,
24283 fctx,
24284 );
24285 Ok(levels)
24286}
24287
24288/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
24289/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
24290/// bottom, where no partition symbol is read at all -- `decode_block` runs
24291/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
24292/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
24293/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
24294/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
24295/// of the 2x2 4x4 group carries chroma syntax at all.
24296#[allow(clippy::too_many_arguments)]
24297fn read_intra_mode_sub8(
24298 dec: &mut SymbolDecoder,
24299 cdfs: &mut Cdfs,
24300 above_mode: usize,
24301 left_mode: usize,
24302 has_chroma: bool,
24303 enable_filter_intra: bool,
24304 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
24305 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
24306 // from the wrong row is the same VALUE with a different interval, so it
24307 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
24308 fi_class: usize,
24309 skip_ctx: usize,
24310 allow_intrabc: bool,
24311 mi_r: usize,
24312 mi_c: usize,
24313 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
24314 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
24315 // left the second mi column at segment 0, which reads back as a
24316 // neighbour's `cdf_index`/prediction two blocks later.
24317 seg_w_mi: usize,
24318 seg_h_mi: usize,
24319 fctx: &crate::decode::FrameCtx,
24320) -> Result<(
24321 bool,
24322 usize,
24323 i32,
24324 Option<(usize, i32, Option<(i32, i32)>)>,
24325 Option<usize>,
24326 Option<(i32, i32)>,
24327)> {
24328 // lane-av1mono: a monochrome leaf codes no chroma mode

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