forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB06be466Tahinli2 months ago3574 commits

decode.rs24345 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}
2714
2715/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2716pub fn skip_split_tx_override_hits() -> usize {
2717 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2718}
2719
2720/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2721pub fn reset_skip_split_tx_override_hits() {
2722 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2723}
2724
2725// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2726// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2727// really are smaller than the block and FEWER symbols are read than the
2728// block has cells (class map-read-past-frame-edge).
2729thread_local! {
2730 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2731}
2732
2733/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2734pub fn palette_onscreen_cut_hits() -> usize {
2735 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2736}
2737
2738/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2739pub fn reset_palette_onscreen_cut_hits() {
2740 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2741}
2742
2743/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2744pub fn reset_skip_split_tx_hits() {
2745 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2746}
2747
2748// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2749// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2750// the gate's proof that the lifted path actually ran, per size.
2751thread_local! {
2752 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2753 const { std::cell::Cell::new([0; 4]) };
2754}
2755
2756/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2757#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2758pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2759 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2760}
2761
2762/// A just-decoded palette-Y block's own predicted pixels
2763/// (`side*side`, row-major, `colors[map[i]]`), consumed by
2764/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2765/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2766/// per-block override through `read_plane`'s two dozen call sites is the
2767/// alternative this avoids). Always empty again once that call consumes
2768/// it (`.take()`), so a non-palette block's own `reconstruct` call never
2769/// sees stale state.
2770
2771/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2772/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2773/// site whose reconstruct never runs would be picked up by the NEXT block's
2774/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2775/// lane-lossless2: one transform unit's window on a block-sized palette
2776/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2777/// handing it the whole-block buffer makes every unit reconstruct the block's
2778/// top-left corner (the luma split-transform paths already window; the chroma
2779/// ones did not, which is invisible until a lossless frame codes a palette
2780/// block as 4x4 chroma units).
2781fn palette_window(
2782 buf: &[u16],
2783 stride: usize,
2784 ox: usize,
2785 oy: usize,
2786 w: usize,
2787 h: usize,
2788) -> Vec<u16> {
2789 (0..h)
2790 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2791 .collect()
2792}
2793
2794/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2795#[track_caller]
2796fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2797 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2798 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2799 eprintln!(
2800 "PALSET len={} stale={stale} at {}",
2801 buf.len(),
2802 std::panic::Location::caller()
2803 );
2804 }
2805 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2806}
2807
2808#[track_caller]
2809fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2810 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2811 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2812 eprintln!(
2813 "PALTAKE len={:?} at {}",
2814 got.as_ref().map(Vec::len),
2815 std::panic::Location::caller()
2816 );
2817 }
2818 got
2819}
2820
2821/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2822/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2823/// pixels, because at parse time this block's own luma is still queued.
2824#[derive(Clone, Copy, Debug)]
2825pub(crate) struct CflSrc {
2826 px: usize,
2827 py: usize,
2828 bw: usize,
2829 bh: usize,
2830}
2831
2832fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2833 CflSrc {
2834 px,
2835 py,
2836 bw: side,
2837 bh: side,
2838 }
2839}
2840
2841fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2842 CflSrc { px, py, bw, bh }
2843}
2844
2845/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2846/// instead of executed. Each variant is the resolved argument tuple of the
2847/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2848/// order performs exactly the same writes in exactly the same order --
2849/// entropy parsing no longer touches the frame's own planes (except the two
2850/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2851/// the replay on a superblock-row wavefront worker.
2852/// The dequantization + inverse transform of one transform unit, kept as its
2853/// INPUTS so that a recorded write carries the work instead of its result
2854/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2855/// recon worker, not on the parsing thread. `stride == 0` means the dense
2856/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2857/// `reconstruct_mc_rect` reads both of its buffers at.
2858#[derive(Clone, Copy)]
2859pub(crate) struct TxParams {
2860 pub(crate) w: usize,
2861 pub(crate) h: usize,
2862 pub(crate) bit_depth: u8,
2863 pub(crate) q_idx: i32,
2864 pub(crate) dc_delta: i32,
2865 pub(crate) ac_delta: i32,
2866 pub(crate) tx_type: TxType,
2867 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
2868 /// on the parse thread by [`block_iqmatrix`] and captured here so the
2869 /// recon worker scales identically without touching frame state.
2870 pub(crate) qm: Option<crate::qm::Iqm>,
2871 pub(crate) stride: usize,
2872 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
2873 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
2874 /// the 4x4 Walsh-Hadamard
2875 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2876 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2877 pub(crate) lossless: bool,
2878}
2879
2880/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
2881/// The mixed-lossless witness's proof the per-segment lossless path really
2882/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
2883/// workers run this on their own threads.
2884static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2885
2886/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
2887/// delta around one decode.
2888#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2889pub(crate) fn lossless_wht_units() -> usize {
2890 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2891}
2892
2893/// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
2894/// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
2895/// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
2896/// `coded_lossless` frame before it looks at the `tx_mode` symbol,
2897/// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree,
2898/// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for
2899/// EVERY plane of a lossless block, and of `av1/common/idct.c`'s
2900/// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a
2901/// `lossless` branch -- every other size falls through to the IDCT, because
2902/// there is no non-4x4 lossless inverse transform to dispatch to. So one of
2903/// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape;
2904/// read as a before/after delta around one decode it names the caller. Must
2905/// read 0 on a stream whose lossless unit geometry is right. Atomic: the
2906/// wavefront workers run the transform on their own threads.
2907static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
2908 std::sync::atomic::AtomicUsize::new(0);
2909
2910/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
2911/// before/after delta around one decode.
2912#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2913pub(crate) fn lossless_wht_split_units() -> usize {
2914 LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2915}
2916
2917impl TxParams {
2918 /// The one copy of the produce-the-residual code: the inline path calls it
2919 /// on the parse thread, the wavefront worker calls it on its own, so both
2920 /// are the same function on the same inputs and byte-identical.
2921 fn run(self, grid: &[i32]) -> Vec<i32> {
2922 let residual = if self.lossless {
2923 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2924 // lane-whtshape: a non-4x4 unit here is this decoder's own
2925 // transform-unit geometry being wrong (see
2926 // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used
2927 // to be stopped by a `debug_assert_eq!` that RELEASE never ran:
2928 // the 4x4 WHT returned 16 values for a `w * h` block and the
2929 // release build died one frame later in the strided copy with an
2930 // opaque `range end index 8 out of range for slice of length 0`
2931 // that never named lossless or the transform. Counted, and
2932 // reconstructed as the raster of 4x4 WHT units
2933 // ([`crate::transform::dequant_and_inverse_wht`]) instead: total,
2934 // the same in both profiles, and the 4x4 fast path is the same
2935 // single call it always was. The old
2936 // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with
2937 // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does
2938 // not either), and `av1_get_tx_type` already answers `DCT_DCT` on
2939 // every plane of a lossless block, so asserting an argument
2940 // nothing reads was a debug-only panic on a value release
2941 // ignores.
2942 if self.w != 4 || self.h != 4 {
2943 LOSSLESS_WHT_SPLIT_UNITS.fetch_add(
2944 self.w.div_ceil(4) * self.h.div_ceil(4),
2945 std::sync::atomic::Ordering::Relaxed,
2946 );
2947 }
2948 crate::transform::dequant_and_inverse_wht(
2949 grid,
2950 self.w,
2951 self.h,
2952 self.bit_depth,
2953 self.q_idx,
2954 self.dc_delta,
2955 self.ac_delta,
2956 )
2957 } else {
2958 dequant_and_inverse_typed_wh(
2959 grid,
2960 self.w,
2961 self.h,
2962 self.bit_depth,
2963 self.q_idx,
2964 self.dc_delta,
2965 self.ac_delta,
2966 self.tx_type,
2967 self.qm,
2968 )
2969 };
2970 // An all-zero grid transforms to the empty marker, and a strided copy
2971 // of zeros is still zeros: the marker passes straight through.
2972 if residual.is_empty() {
2973 return residual;
2974 }
2975 if self.stride == 0 {
2976 return residual;
2977 }
2978 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
2979 // height exceeds its (narrow) prediction stride needs the full
2980 // stride * h; every square caller has h == stride and is unchanged.
2981 let mut strided = vec![0i32; self.stride * self.h];
2982 for row in 0..self.h {
2983 strided[row * self.stride..][..self.w]
2984 .copy_from_slice(&residual[row * self.w..][..self.w]);
2985 }
2986 strided
2987 }
2988}
2989
2990/// A recorded write's residual: already transformed, or the coefficients and
2991/// [`TxParams`] the worker transforms itself.
2992pub(crate) enum Residual {
2993 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2994 /// `len` is the all-zero marker [`dense_residual`] expands.
2995 Done(u32, u32),
2996 /// The coefficients live in the pushing tile's arena
2997 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2998 /// len)` in it.
2999 Coeffs(TxParams, u32, u32),
3000}
3001
3002impl Residual {
3003 /// The record for a transform unit whose coefficient grid is all zero:
3004 /// the empty marker, so neither the grid nor the residual is cloned and
3005 /// the worker never runs the transform (60% of the 4K segment's units).
3006 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3007 if is_zero_grid(grid) {
3008 return Self::Done(0, 0);
3009 }
3010 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
3011 }
3012
3013 /// A residual the parse thread already transformed, kept in the arena
3014 /// instead of its own `Vec`.
3015 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3016 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
3017 // which is exactly the all-zero marker -- one pointer compare instead
3018 // of copying up to 64 KB of zeros into the arena per block.
3019 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
3020 return Self::Done(0, 0);
3021 }
3022 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
3023 }
3024
3025 /// The residual to reconstruct with; `scratch` is where a transform run
3026 /// on this thread lands, so the caller owns that buffer.
3027 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
3028 match self {
3029 Self::Done(off, len) => &arena[off as usize..][..len as usize],
3030 Self::Coeffs(p, off, len) => {
3031 *scratch = p.run(&arena[off as usize..][..len as usize]);
3032 scratch
3033 }
3034 }
3035 }
3036}
3037
3038/// Appends to the tile's coefficient arena, returning the offset the record
3039/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
3040fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
3041 fctx.coeff_arena.with(|a| {
3042 let mut a = a.borrow_mut();
3043 let off = a.len();
3044 a.extend_from_slice(v);
3045 off as u32
3046 })
3047}
3048
3049/// [`push_coeffs`] for a recorded prediction.
3050fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
3051 fctx.pred_arena.with(|a| {
3052 let mut a = a.borrow_mut();
3053 let off = a.len();
3054 a.extend_from_slice(v);
3055 off as u32
3056 })
3057}
3058
3059/// An all-zero residual, for the transform units that code no coefficient:
3060/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
3061/// and the reconstruction loops below read this instead of a per-unit
3062/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
3063/// (a 128-wide inter block's prediction stride).
3064pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
3065
3066/// lane-blockscratch: one plane's coefficient levels as the block-tail
3067/// neighbour writes want them. A plane that coded nothing (a skipped block, a
3068/// strip with no chroma, luma under a var-tx split whose units already wrote
3069/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
3070/// zeroing up to 64 KB of its own per block.
3071#[derive(Clone)]
3072enum Grid {
3073 Zero(usize),
3074 Own(Vec<i32>),
3075}
3076
3077/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
3078/// unit that writes into it. Only a block wider or taller than 64 px codes its
3079/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
3080/// collectors per block and then drop them untouched.
3081fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
3082 if v.is_empty() {
3083 *v = vec![0i32; n];
3084 }
3085 v
3086}
3087
3088impl std::ops::Deref for Grid {
3089 type Target = [i32];
3090 fn deref(&self) -> &[i32] {
3091 match self {
3092 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
3093 Grid::Own(v) => v,
3094 }
3095 }
3096}
3097
3098/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
3099/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
3100/// transform units that code no coefficient without the scan (lane-coefgrid).
3101pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
3102 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
3103}
3104
3105/// `residual`, or `n` zeros when it is the empty all-zero marker.
3106fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
3107 if residual.is_empty() {
3108 &ZERO_RESIDUAL[..n]
3109 } else {
3110 residual
3111 }
3112}
3113
3114/// Where a recorded motion-compensated write reads its prediction from.
3115///
3116/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
3117/// the parse thread's single biggest reconstruction cost, so at
3118/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
3119/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
3120/// runs it into its own three-plane slot, and every transform unit of that
3121/// block then reads its window out of that slot ([`Pred::Cur`]).
3122#[derive(Clone, Copy)]
3123pub(crate) enum Pred<'a> {
3124 /// A prediction the parse thread already built, at its own stride
3125 /// (`stride == 0` means "the reader's own `stride` argument").
3126 Inline(&'a [u16], usize),
3127 /// The current block's deferred prediction: plane, its stride, and this
3128 /// unit's offset into it.
3129 Cur {
3130 plane: usize,
3131 stride: usize,
3132 off: usize,
3133 },
3134}
3135
3136impl<'a> Pred<'a> {
3137 /// The same prediction read at an explicit stride.
3138 fn view(self, stride: usize) -> Self {
3139 match self {
3140 Self::Inline(b, _) => Self::Inline(b, stride),
3141 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
3142 }
3143 }
3144 /// The materialised buffer and the stride to read it at (`stride` is the
3145 /// reader's own when this prediction was built dense); `None` for a
3146 /// deferred prediction, which only a recorded op can carry.
3147 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
3148 match self {
3149 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
3150 Self::Cur { .. } => None,
3151 }
3152 }
3153 /// This prediction's window starting `n` samples in.
3154 fn offset(self, n: usize) -> Self {
3155 match self {
3156 Self::Inline(b, s) => Self::Inline(&b[n..], s),
3157 Self::Cur { plane, stride, off } => Self::Cur {
3158 plane,
3159 stride,
3160 off: off + n,
3161 },
3162 }
3163 }
3164}
3165
3166/// [`Pred`], resolved into what a recorded op carries.
3167pub(crate) enum PredSrc {
3168 /// A prediction window in the tile's prediction arena, `(offset, len)`.
3169 Owned(u32, u32),
3170 /// A window of the block prediction: its plane, its offset, and the
3171 /// stride it is read at -- which is the block's, not necessarily the
3172 /// op's (a transform unit's residual stays dense, so the worker takes
3173 /// its window out of the block prediction itself).
3174 Cur {
3175 plane: usize,
3176 off: usize,
3177 src: usize,
3178 },
3179}
3180
3181/// One block's whole-block prediction build, deferred to a recon worker.
3182///
3183/// The closure borrows the tile's reference pictures and its own frame-level
3184/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
3185/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
3186/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
3187pub(crate) struct PredBuild(
3188 Box<
3189 dyn FnOnce(
3190 &mut PlaneBuf<'static>,
3191 &mut PlaneBuf<'static>,
3192 &mut PlaneBuf<'static>,
3193 &crate::decode::FrameCtx,
3194 // lane-blockmem: the previous block's three prediction buffers,
3195 // refilled in place -- the build used to return three fresh
3196 // `Vec`s per block and drop these.
3197 &mut [Vec<u16>; 3],
3198 ),
3199 >,
3200);
3201
3202// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
3203// pictures and frame tables, and the closure runs on exactly one worker.
3204#[allow(unsafe_code)]
3205unsafe impl Send for PredBuild {}
3206
3207/// `true` when this tile's writes are recorded for the wavefront instead of
3208/// performed at the push site, i.e. when a prediction may be deferred.
3209fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
3210 fctx.recon_planes.with(std::cell::Cell::get).is_none()
3211}
3212
3213/// The previous block's prediction buffer, cleared and zero-filled to `n`
3214/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
3215/// without the per-block allocation and free.
3216fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
3217 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
3218 // than resized element by element -- which is every block on the inline
3219 // path, where there is no previous buffer to reuse.
3220 if v.capacity() < n {
3221 return vec![0u16; n];
3222 }
3223 v.clear();
3224 v.resize(n, 0);
3225 v
3226}
3227
3228/// Records one block's prediction build for the worker that reconstructs it.
3229#[allow(unsafe_code)]
3230fn push_pred<'a>(
3231 fctx: &crate::decode::FrameCtx,
3232 f: impl FnOnce(
3233 &mut PlaneBuf<'static>,
3234 &mut PlaneBuf<'static>,
3235 &mut PlaneBuf<'static>,
3236 &crate::decode::FrameCtx,
3237 &mut [Vec<u16>; 3],
3238 ) + 'a,
3239) {
3240 type Dyn<'x> = dyn FnOnce(
3241 &mut PlaneBuf<'static>,
3242 &mut PlaneBuf<'static>,
3243 &mut PlaneBuf<'static>,
3244 &crate::decode::FrameCtx,
3245 &mut [Vec<u16>; 3],
3246 ) + 'x;
3247 let boxed: Box<Dyn<'a>> = Box::new(f);
3248 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
3249 // before the borrows the closure holds go out of scope.
3250 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
3251 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
3252}
3253
3254/// One superblock's recorded writes plus the two arenas they index -- the
3255/// unit a wavefront worker takes off the queue (lane-recoparse).
3256pub(crate) struct ReconJob {
3257 ops: Vec<ReconOp>,
3258 coeffs: Vec<i32>,
3259 preds: Vec<u16>,
3260}
3261
3262pub(crate) enum ReconOp {
3263 /// lane-wave4: build this block's prediction into the worker's slot.
3264 Pred(PredBuild),
3265 Intra {
3266 plane: usize,
3267 x: usize,
3268 y: usize,
3269 bw: usize,
3270 bh: usize,
3271 /// `true` when the parse site called `reconstruct_rect` (whose
3272 /// `edges_rect` differs from `edges` even at `bw == bh`).
3273 rect: bool,
3274 mode: usize,
3275 angle_delta: i32,
3276 reach: Reach,
3277 residual: Residual,
3278 cfl: Option<(i32, CflSrc)>,
3279 filter_intra: Option<usize>,
3280 smooth_neighbor: bool,
3281 /// The palette/intrabc prediction override, taken off
3282 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
3283 /// from that slot by the replay.
3284 pred: Option<Vec<u16>>,
3285 },
3286 Mc {
3287 plane: usize,
3288 x: usize,
3289 y: usize,
3290 stride: usize,
3291 w: usize,
3292 h: usize,
3293 prediction: PredSrc,
3294 residual: Residual,
3295 },
3296}
3297
3298/// The three planes of the tile currently being decoded, as raw pointers.
3299///
3300/// corner-cut: at one reconstruction thread a recorded write must cost
3301/// nothing -- deferring it to the end of the superblock is +1.2%
3302/// instructions and +4.5% wall on 4K, because the residual is written at
3303/// parse and read back cache-cold at replay. So the recorded op is performed
3304/// at the push site instead, through the pointers the tile decoder registers
3305/// once ([`ReconInline`]), which is the same thread, the same order and the
3306/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
3307/// stack still holds aliases them, exactly the [`crate::par::Shared`]
3308/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
3309/// threading the three planes down every `read_plane`/`read_inter_plane`
3310/// call site (~40) so the push site owns the borrow it writes through.
3311#[derive(Clone, Copy)]
3312pub(crate) struct ReconPlanes(
3313 *mut PlaneBuf<'static>,
3314 *mut PlaneBuf<'static>,
3315 *mut PlaneBuf<'static>,
3316);
3317
3318// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
3319// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
3320// value travelling is `None`; the pointers never leave the tile decoder's
3321// own thread.
3322#[allow(unsafe_code)]
3323unsafe impl Send for ReconPlanes {}
3324// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
3325// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
3326// contract, one superblock per band instead of one row band.
3327#[allow(unsafe_code)]
3328unsafe impl Sync for ReconPlanes {}
3329
3330/// Registers the tile's planes for inline reconstruction and unregisters them
3331/// on every exit from the tile decoder, including the `?` ones -- a stale
3332/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
3333/// tile.
3334pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
3335
3336#[allow(unsafe_code)]
3337impl<'a> ReconInline<'a> {
3338 /// Installs the guard for this tile when reconstruction is inline
3339 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
3340 /// to the queue instead, for the wavefront workers to replay.
3341 fn install(
3342 fctx: &'a crate::decode::FrameCtx,
3343 y: &mut PlaneBuf<'static>,
3344 u: &mut PlaneBuf<'static>,
3345 v: &mut PlaneBuf<'static>,
3346 ) -> Option<Self> {
3347 if crate::par::recon_threads() != 1 {
3348 return None;
3349 }
3350 // SAFETY: the planes are locals of the tile decoder and outlive the
3351 // guard, which is dropped on every exit from it (including `?`); see
3352 // [`ReconPlanes`] for the aliasing trade-off.
3353 let planes = ReconPlanes(
3354 std::ptr::from_mut(y),
3355 std::ptr::from_mut(u),
3356 std::ptr::from_mut(v),
3357 );
3358 fctx.recon_planes.with(|c| c.set(Some(planes)));
3359 Some(Self(fctx))
3360 }
3361}
3362
3363impl Drop for ReconInline<'_> {
3364 fn drop(&mut self) {
3365 self.0.recon_planes.with(|c| c.set(None));
3366 }
3367}
3368
3369#[allow(unsafe_code)]
3370fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
3371 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
3372 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
3373 // the parse site would have performed itself before lane-wave1.
3374 // The inline path never records coefficients (the transform runs at
3375 // the push site), so the arena is not read here.
3376 unsafe {
3377 exec_op(
3378 op,
3379 &mut *y,
3380 &mut *u,
3381 &mut *v,
3382 &mut Default::default(),
3383 &[],
3384 &[],
3385 fctx,
3386 )
3387 };
3388 return;
3389 }
3390 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
3391}
3392
3393/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
3394/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
3395///
3396/// The parser keeps parsing and never touches the planes; each superblock's
3397/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
3398/// `(row, column)` inside the tile (128x128 superblocks are one job for all
3399/// four of their 64x64 visits, since a 128 block writes across quadrants).
3400/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
3401/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
3402/// every pixel an intra predictor can read (its edges reach one block right
3403/// along the row above and one block down the column to the left, both
3404/// inside those two neighbours) and every CfL AC read (this block's own
3405/// luma, written by this same job). Jobs are handed out in raster order, so
3406/// the oldest outstanding one always has its dependencies met: no deadlock.
3407///
3408/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
3409/// `thread_local!` and miss every worker, which is why the default is 1.
3410pub(crate) struct WaveState {
3411 q: std::sync::Mutex<WaveQueue>,
3412 cv: std::sync::Condvar,
3413 planes: ReconPlanes,
3414 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
3415 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
3416 bit_depth: u8,
3417 enable_edge_filter: bool,
3418 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
3419 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3420 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3421 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3422 /// default halved every worker's chroma reference position and lost the
3423 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3424 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3425 subsampling: (u8, u8),
3426 last_col: usize,
3427}
3428
3429struct WaveQueue {
3430 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3431 /// row's front job can ever be runnable -- a job waits on its own left
3432 /// neighbour -- so a worker takes the lowest row whose front job's
3433 /// dependencies are met. Popping the raster-oldest job instead (what
3434 /// this replaced) put every worker on the SAME row, where the wavefront
3435 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3436 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3437 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3438 /// walking it.
3439 queued: usize,
3440 /// Per superblock row, the last column reconstructed (-1 = none yet).
3441 done: Vec<isize>,
3442 /// Per superblock row, the last column PARSED (submitted, whether or not
3443 /// it recorded any write) and the last column actually pushed as a job
3444 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3445 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3446 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3447 last_sub: Vec<isize>,
3448 last_push: Vec<isize>,
3449 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3450 active: usize,
3451 closed: bool,
3452 /// lane-sballoc: the three per-superblock buffers a finished job hands
3453 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3454 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3455 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3456 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3457 /// inside the queue's own mutex, which both sides already take.
3458 free: Vec<JobBufs>,
3459 free_cap: usize,
3460}
3461
3462/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3463type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3464
3465impl WaveQueue {
3466 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3467 /// or `None` (with the blocking condition counted when instrumented).
3468 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, ReconJob)> {
3469 let mut blocked: Option<bool> = None;
3470 for r in 0..self.rows.len() {
3471 let Some(front) = self.rows[r].front() else {
3472 continue;
3473 };
3474 let c = front.0;
3475 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3476 let left = c == 0 || self.done[r] >= c as isize - 1;
3477 if above && left {
3478 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3479 self.queued -= 1;
3480 return Some((r, c, job));
3481 }
3482 if blocked.is_none() {
3483 blocked = Some(above);
3484 }
3485 }
3486 if stats {
3487 match blocked {
3488 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3489 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3490 None => 0,
3491 };
3492 }
3493 None
3494 }
3495}
3496
3497/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3498/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3499/// empty queue), how far ahead the parse thread is, and how often the two
3500/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3501/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3502/// whole run.
3503const WS_SLOTS: usize = 16;
3504use std::sync::atomic::AtomicU64;
3505use std::sync::atomic::Ordering::Relaxed;
3506static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3507static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3508static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3509static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3510static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3511static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3512/// Parse-thread time between two submits, i.e. everything parse still does
3513/// itself (symbol decode plus the predictions not deferred).
3514static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3515/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3516/// (the intrabc/interintra reads) and at the tile's end.
3517static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3518static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3519static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3520static WS_TILES: AtomicU64 = AtomicU64::new(0);
3521
3522fn wave_stats() -> bool {
3523 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3524 match ON.load(Relaxed) {
3525 0 => {
3526 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3527 .map(|v| v.trim() == "1")
3528 .unwrap_or(false);
3529 ON.store(1 + u8::from(on), Relaxed);
3530 on
3531 }
3532 n => n == 2,
3533 }
3534}
3535
3536fn wave_stats_dump() {
3537 let ms = |n: u64| n as f64 / 1e6;
3538 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3539 for i in 0..WS_SLOTS {
3540 let jobs = WS_JOBS[i].load(Relaxed);
3541 if jobs == 0 {
3542 continue;
3543 }
3544 s += &format!(
3545 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3546 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3547 ms(WS_BUSY[i].load(Relaxed)),
3548 ms(WS_WAIT[i].load(Relaxed)),
3549 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3550 );
3551 }
3552 s += &format!(
3553 " | pipe={}/{}",
3554 PIPE_FRAMES.load(Relaxed),
3555 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3556 );
3557 s += &format!(
3558 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3559 ms(WS_PARSE.load(Relaxed)),
3560 ms(WS_BARRIER.load(Relaxed)),
3561 WS_BARRIERS.load(Relaxed),
3562 ms(WS_DRAIN.load(Relaxed)),
3563 WS_BLOCK_ABOVE.load(Relaxed),
3564 WS_BLOCK_LEFT.load(Relaxed),
3565 );
3566 eprintln!("{s}");
3567}
3568
3569#[allow(unsafe_code)]
3570fn wave_worker(st: &WaveState, idx: usize) {
3571 let fctx = FrameCtx::new();
3572 fctx.bit_depth.set(st.bit_depth);
3573 fctx.enable_edge_filter.set(st.enable_edge_filter);
3574 let (sx, sy) = st.subsampling;
3575 fctx.subsampling_x.set(sx);
3576 fctx.subsampling_y.set(sy);
3577 let stats = wave_stats();
3578 let slot = idx.min(WS_SLOTS - 1);
3579 loop {
3580 let t0 = std::time::Instant::now();
3581 let mut q = st.q.lock().unwrap();
3582 let (r, c, job) = loop {
3583 if let Some(job) = q.take_runnable(st.last_col, stats) {
3584 break job;
3585 }
3586 if q.closed && q.queued == 0 {
3587 return;
3588 }
3589 q = st.cv.wait(q).unwrap();
3590 };
3591 q.active += 1;
3592 drop(q);
3593 if stats {
3594 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3595 WS_JOBS[slot].fetch_add(1, Relaxed);
3596 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3597 }
3598 let t1 = std::time::Instant::now();
3599 let ReconPlanes(y, u, v) = st.planes;
3600 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3601 // every superblock that could have written or be reading them is
3602 // complete by the wavefront rule above.
3603 let mut cur: [Vec<u16>; 3] = Default::default();
3604 let ReconJob {
3605 mut ops,
3606 mut coeffs,
3607 mut preds,
3608 } = job;
3609 unsafe {
3610 for op in ops.drain(..) {
3611 exec_op(
3612 op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx,
3613 );
3614 }
3615 }
3616 if stats {
3617 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3618 }
3619 coeffs.clear();
3620 preds.clear();
3621 let mut q = st.q.lock().unwrap();
3622 // lane-sballoc: hand the three buffers back for the next submit.
3623 if q.free.len() < q.free_cap {
3624 q.free.push((ops, coeffs, preds));
3625 }
3626 q.done[r] = c as isize;
3627 q.active -= 1;
3628 st.cv.notify_all();
3629 }
3630}
3631
3632/// Installs the wavefront for one tile and joins its workers on every exit
3633/// from the tile decoder, including the `?` ones -- the jobs hold raw
3634/// pointers into the tile's planes, so no worker may outlive them.
3635/// (lane-pool1: the workers come from this thread's persistent pool, so a
3636/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3637/// with fresh scratch.)
3638pub(crate) struct WaveGuard<'a>(
3639 &'a crate::decode::FrameCtx,
3640 Option<crate::par::Batch<'static>>,
3641);
3642
3643#[allow(unsafe_code)]
3644impl<'a> WaveGuard<'a> {
3645 fn install(
3646 fctx: &'a crate::decode::FrameCtx,
3647 y: &mut PlaneBuf<'static>,
3648 u: &mut PlaneBuf<'static>,
3649 v: &mut PlaneBuf<'static>,
3650 rows: usize,
3651 cols: usize,
3652 ) -> Option<Self> {
3653 let threads = crate::par::recon_threads();
3654 if threads == 1 || rows == 0 || cols == 0 {
3655 return None;
3656 }
3657 let st = std::sync::Arc::new(WaveState {
3658 q: std::sync::Mutex::new(WaveQueue {
3659 rows: (0..rows)
3660 .map(|_| std::collections::VecDeque::new())
3661 .collect(),
3662 queued: 0,
3663 done: vec![-1; rows],
3664 last_sub: vec![-1; rows],
3665 last_push: vec![-1; rows],
3666 active: 0,
3667 closed: false,
3668 free: Vec::new(),
3669 free_cap: threads + 2,
3670 }),
3671 cv: std::sync::Condvar::new(),
3672 // SAFETY: the planes are locals of the tile decoder and outlive
3673 // this guard, which joins every worker in `drop`.
3674 planes: ReconPlanes(
3675 std::ptr::from_mut(y),
3676 std::ptr::from_mut(u),
3677 std::ptr::from_mut(v),
3678 ),
3679 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3680 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3681 subsampling: (
3682 fctx.subsampling_x.with(std::cell::Cell::get),
3683 fctx.subsampling_y.with(std::cell::Cell::get),
3684 ),
3685 last_col: cols - 1,
3686 });
3687 let batch = crate::par::Batch::new("ec-av1-recon");
3688 for idx in 0..threads {
3689 let st = std::sync::Arc::clone(&st);
3690 batch.submit(move || wave_worker(&st, idx));
3691 }
3692 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3693 fctx.wave_mark
3694 .with(|c| c.set(Some(std::time::Instant::now())));
3695 Some(Self(fctx, Some(batch)))
3696 }
3697}
3698
3699impl Drop for WaveGuard<'_> {
3700 fn drop(&mut self) {
3701 let st = self.0.wave.with(|w| w.borrow_mut().take());
3702 if let Some(st) = st {
3703 st.q.lock().unwrap().closed = true;
3704 st.cv.notify_all();
3705 }
3706 let t0 = std::time::Instant::now();
3707 // Dropping the batch waits every worker out, as the joins did.
3708 drop(self.1.take());
3709 if wave_stats() {
3710 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3711 WS_TILES.fetch_add(1, Relaxed);
3712 wave_stats_dump();
3713 }
3714 }
3715}
3716
3717/// An empty buffer for the next superblock: the recycled one when it is at
3718/// least as big as the superblock just parsed, else a fresh sized one
3719/// (lane-sballoc; `v` is always empty).
3720fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3721 if v.capacity() < cap {
3722 v.reserve_exact(cap - v.len());
3723 }
3724 v
3725}
3726
3727/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3728/// when there is no wavefront (one reconstruction thread), in which case the
3729/// caller replays them itself.
3730fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3731 let st = fctx.wave.with(|w| w.borrow().clone());
3732 let Some(st) = st else { return false };
3733 // lane-blockmem: the op list is replaced sized for the next superblock,
3734 // exactly as the two arenas below are -- taking it left a zero-capacity
3735 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3736 // every superblock.
3737 // lane-sballoc: the replacement comes from the finished jobs' free list
3738 // when there is one (warm capacity, already faulted in); only the first
3739 // superblocks of a tile allocate.
3740 let mut q = st.q.lock().unwrap();
3741 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3742 let ops = fctx.recon_ops.with(|c| {
3743 let mut c = c.borrow_mut();
3744 let cap = c.len();
3745 std::mem::replace(&mut *c, reuse(sops, cap))
3746 });
3747 // The job owns its coefficients: the arena is replaced by an empty one
3748 // sized for the next superblock, so parse never regrows from nothing and
3749 // the worker frees this buffer once, instead of once per unit.
3750 let coeffs = fctx.coeff_arena.with(|c| {
3751 let mut c = c.borrow_mut();
3752 let cap = c.len();
3753 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3754 });
3755 let preds = fctx.pred_arena.with(|c| {
3756 let mut c = c.borrow_mut();
3757 let cap = c.len();
3758 std::mem::replace(&mut *c, reuse(spreds, cap))
3759 });
3760 {
3761 if (c as isize) > q.last_sub[r] {
3762 q.last_sub[r] = c as isize;
3763 }
3764 if !ops.is_empty() {
3765 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3766 q.queued += 1;
3767 q.last_push[r] = c as isize;
3768 }
3769 drop(q);
3770 st.cv.notify_all();
3771 }
3772 if wave_stats() {
3773 let now = std::time::Instant::now();
3774 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3775 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3776 }
3777 }
3778 true
3779}
3780
3781/// Waits until every submitted job is reconstructed, so the parser may read
3782/// the planes itself (the intrabc source fetch and the interintra intra
3783/// predictor -- see [`flush_recon`]).
3784fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3785 let st = fctx.wave.with(|w| w.borrow().clone());
3786 let Some(st) = st else { return };
3787 let stats = wave_stats();
3788 let t0 = std::time::Instant::now();
3789 let mut q = st.q.lock().unwrap();
3790 while q.queued > 0 || q.active > 0 {
3791 q = st.cv.wait(q).unwrap();
3792 }
3793 drop(q);
3794 if stats {
3795 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3796 WS_BARRIERS.fetch_add(1, Relaxed);
3797 }
3798}
3799
3800/// Performs an intra write at its push site when the tile registered its
3801/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3802/// caller must record it for the wavefront workers instead.
3803#[allow(unsafe_code)]
3804#[allow(clippy::too_many_arguments)]
3805fn inline_intra(
3806 plane: usize,
3807 x: usize,
3808 oy: usize,
3809 bw: usize,
3810 bh: usize,
3811 rect: bool,
3812 mode: usize,
3813 angle_delta: i32,
3814 reach: Reach,
3815 residual: &[i32],
3816 cfl: Option<(i32, CflSrc)>,
3817 filter_intra: Option<usize>,
3818 smooth_neighbor: bool,
3819 fctx: &crate::decode::FrameCtx,
3820) -> bool {
3821 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3822 return false;
3823 };
3824 let pred = take_palette_pred(fctx);
3825 // SAFETY: see [`ReconPlanes`].
3826 unsafe {
3827 exec_intra(
3828 &mut *y,
3829 &mut *u,
3830 &mut *v,
3831 plane,
3832 x,
3833 oy,
3834 bw,
3835 bh,
3836 rect,
3837 mode,
3838 angle_delta,
3839 reach,
3840 residual,
3841 cfl,
3842 filter_intra,
3843 smooth_neighbor,
3844 pred,
3845 fctx,
3846 );
3847 }
3848 true
3849}
3850
3851/// [`inline_intra`] for a motion-compensated write.
3852#[allow(unsafe_code)]
3853#[allow(clippy::too_many_arguments)]
3854fn inline_mc(
3855 plane: usize,
3856 x: usize,
3857 oy: usize,
3858 stride: usize,
3859 w: usize,
3860 h: usize,
3861 prediction: &[u16],
3862 residual: &[i32],
3863 fctx: &crate::decode::FrameCtx,
3864) -> bool {
3865 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3866 return false;
3867 };
3868 // SAFETY: see [`ReconPlanes`].
3869 unsafe {
3870 exec_mc(
3871 &mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx,
3872 );
3873 }
3874 true
3875}
3876
3877/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3878#[allow(clippy::too_many_arguments)]
3879fn push_intra(
3880 plane: usize,
3881 x: usize,
3882 y: usize,
3883 side: usize,
3884 mode: usize,
3885 angle_delta: i32,
3886 reach: Reach,
3887 residual: &[i32],
3888 cfl: Option<(i32, CflSrc)>,
3889 filter_intra: Option<usize>,
3890 smooth_neighbor: bool,
3891 fctx: &crate::decode::FrameCtx,
3892) {
3893 if inline_intra(
3894 plane,
3895 x,
3896 y,
3897 side,
3898 side,
3899 false,
3900 mode,
3901 angle_delta,
3902 reach,
3903 residual,
3904 cfl,
3905 filter_intra,
3906 smooth_neighbor,
3907 fctx,
3908 ) {
3909 return;
3910 }
3911 let pred = take_palette_pred(fctx);
3912 push_op(
3913 fctx,
3914 ReconOp::Intra {
3915 plane,
3916 x,
3917 y,
3918 bw: side,
3919 bh: side,
3920 rect: false,
3921 mode,
3922 angle_delta,
3923 reach,
3924 residual: Residual::done(residual, fctx),
3925 cfl,
3926 filter_intra,
3927 smooth_neighbor,
3928 pred,
3929 },
3930 );
3931}
3932
3933/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3934#[allow(clippy::too_many_arguments)]
3935fn push_intra_rect(
3936 plane: usize,
3937 x: usize,
3938 y: usize,
3939 bw: usize,
3940 bh: usize,
3941 mode: usize,
3942 angle_delta: i32,
3943 reach: Reach,
3944 residual: &[i32],
3945 cfl: Option<(i32, CflSrc)>,
3946 filter_intra: Option<usize>,
3947 smooth_neighbor: bool,
3948 fctx: &crate::decode::FrameCtx,
3949) {
3950 if inline_intra(
3951 plane,
3952 x,
3953 y,
3954 bw,
3955 bh,
3956 true,
3957 mode,
3958 angle_delta,
3959 reach,
3960 residual,
3961 cfl,
3962 filter_intra,
3963 smooth_neighbor,
3964 fctx,
3965 ) {
3966 return;
3967 }
3968 let pred = take_palette_pred(fctx);
3969 push_op(
3970 fctx,
3971 ReconOp::Intra {
3972 plane,
3973 x,
3974 y,
3975 bw,
3976 bh,
3977 rect: true,
3978 mode,
3979 angle_delta,
3980 reach,
3981 residual: Residual::done(residual, fctx),
3982 cfl,
3983 filter_intra,
3984 smooth_neighbor,
3985 pred,
3986 },
3987 );
3988}
3989
3990/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3991fn push_mc(
3992 plane: usize,
3993 x: usize,
3994 y: usize,
3995 side: usize,
3996 prediction: Pred<'_>,
3997 residual: &[i32],
3998 fctx: &crate::decode::FrameCtx,
3999) {
4000 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
4001}
4002
4003/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
4004#[allow(clippy::too_many_arguments)]
4005fn push_mc_rect(
4006 plane: usize,
4007 x: usize,
4008 y: usize,
4009 stride: usize,
4010 w: usize,
4011 h: usize,
4012 prediction: Pred<'_>,
4013 residual: &[i32],
4014 fctx: &crate::decode::FrameCtx,
4015) {
4016 let (src, stride) = match prediction.inline(stride) {
4017 Some(v) => v,
4018 None => {
4019 let Pred::Cur {
4020 plane: sp,
4021 stride: ss,
4022 off,
4023 } = prediction
4024 else {
4025 unreachable!()
4026 };
4027 push_op(
4028 fctx,
4029 ReconOp::Mc {
4030 plane,
4031 x,
4032 y,
4033 stride: ss,
4034 w,
4035 h,
4036 prediction: PredSrc::Cur {
4037 plane: sp,
4038 off,
4039 src: ss,
4040 },
4041 residual: Residual::done(residual, fctx),
4042 },
4043 );
4044 return;
4045 }
4046 };
4047 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
4048 return;
4049 }
4050 push_op(
4051 fctx,
4052 ReconOp::Mc {
4053 plane,
4054 x,
4055 y,
4056 stride,
4057 w,
4058 h,
4059 // The whole window `reconstruct_mc_rect` reads at `stride`, not
4060 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
4061 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
4062 residual: Residual::done(residual, fctx),
4063 },
4064 );
4065}
4066
4067/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
4068/// thread the transform runs here, exactly as before; on the wavefront it
4069/// travels with the op and runs on the worker (lane-wave3).
4070#[allow(clippy::too_many_arguments)]
4071fn push_intra_tx(
4072 plane: usize,
4073 x: usize,
4074 y: usize,
4075 bw: usize,
4076 bh: usize,
4077 rect: bool,
4078 mode: usize,
4079 angle_delta: i32,
4080 reach: Reach,
4081 tx: TxParams,
4082 grid: &[i32],
4083 cfl: Option<(i32, CflSrc)>,
4084 filter_intra: Option<usize>,
4085 smooth_neighbor: bool,
4086 fctx: &crate::decode::FrameCtx,
4087) {
4088 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4089 inline_intra(
4090 plane,
4091 x,
4092 y,
4093 bw,
4094 bh,
4095 rect,
4096 mode,
4097 angle_delta,
4098 reach,
4099 &tx.run(grid),
4100 cfl,
4101 filter_intra,
4102 smooth_neighbor,
4103 fctx,
4104 );
4105 return;
4106 }
4107 let pred = take_palette_pred(fctx);
4108 push_op(
4109 fctx,
4110 ReconOp::Intra {
4111 plane,
4112 x,
4113 y,
4114 bw,
4115 bh,
4116 rect,
4117 mode,
4118 angle_delta,
4119 reach,
4120 residual: Residual::coeffs(tx, grid, fctx),
4121 cfl,
4122 filter_intra,
4123 smooth_neighbor,
4124 pred,
4125 },
4126 );
4127}
4128
4129/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
4130#[allow(clippy::too_many_arguments)]
4131fn push_mc_rect_tx(
4132 plane: usize,
4133 x: usize,
4134 y: usize,
4135 stride: usize,
4136 w: usize,
4137 h: usize,
4138 prediction: Pred<'_>,
4139 tx: TxParams,
4140 grid: &[i32],
4141 fctx: &crate::decode::FrameCtx,
4142) {
4143 // lane-wave4: a deferred prediction is not there to be windowed -- the
4144 // op carries its offset into the block's prediction instead, and the
4145 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
4146 // both buffers at one stride).
4147 let (prediction, stride) = match prediction.inline(stride) {
4148 Some(v) => v,
4149 None => {
4150 let Pred::Cur {
4151 plane: sp,
4152 stride: ss,
4153 off,
4154 } = prediction
4155 else {
4156 unreachable!()
4157 };
4158 let mut tx = tx;
4159 tx.stride = 0;
4160 push_op(
4161 fctx,
4162 ReconOp::Mc {
4163 plane,
4164 x,
4165 y,
4166 stride: w,
4167 w,
4168 h,
4169 prediction: PredSrc::Cur {
4170 plane: sp,
4171 off,
4172 src: ss,
4173 },
4174 residual: Residual::coeffs(tx, grid, fctx),
4175 },
4176 );
4177 return;
4178 }
4179 };
4180 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4181 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
4182 // stride, so a prediction handed over at the block's stride (a var-tx
4183 // unit's window, lane-wave4) has to be densified for a dense residual
4184 // -- which is exactly what the recorded path below does.
4185 let residual = tx.run(grid);
4186 let res_stride = if tx.stride == 0 { w } else { tx.stride };
4187 let window;
4188 let prediction = if stride == res_stride {
4189 prediction
4190 } else {
4191 debug_assert_eq!(res_stride, w);
4192 let mut win = Vec::with_capacity(w * h);
4193 for row in 0..h {
4194 win.extend_from_slice(&prediction[row * stride..][..w]);
4195 }
4196 window = win;
4197 &window[..]
4198 };
4199 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
4200 return;
4201 }
4202 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
4203 // two buffers at `stride`, so the record carries that window densely
4204 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
4205 // copied 64*64 samples on the PARSING thread before. The residual is then
4206 // produced dense too (`TxParams::stride = 0`), which is the same numbers
4207 // in the same places at stride `w`.
4208 let off = fctx.pred_arena.with(|a| {
4209 let mut a = a.borrow_mut();
4210 let off = a.len();
4211 for row in 0..h {
4212 a.extend_from_slice(&prediction[row * stride..][..w]);
4213 }
4214 off as u32
4215 });
4216 let mut tx = tx;
4217 tx.stride = 0;
4218 push_op(
4219 fctx,
4220 ReconOp::Mc {
4221 plane,
4222 x,
4223 y,
4224 stride: w,
4225 w,
4226 h,
4227 prediction: PredSrc::Owned(off, (w * h) as u32),
4228 residual: Residual::coeffs(tx, grid, fctx),
4229 },
4230 );
4231}
4232
4233/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
4234/// and empties the queue (lane-wave1 step (i)).
4235///
4236/// Called at the top of each superblock visit and at the end of each tile, so
4237/// a whole superblock's parsing runs with no plane access at all; the two
4238/// parse-time pixel READS that survive -- the intrabc source fetch and the
4239/// interintra intra predictor -- flush ahead of themselves instead, which
4240/// keeps them byte-exact and names exactly what step (ii) still has to move.
4241fn flush_recon(
4242 fctx: &crate::decode::FrameCtx,
4243 y: &mut PlaneBuf<'static>,
4244 u: &mut PlaneBuf<'static>,
4245 v: &mut PlaneBuf<'static>,
4246) {
4247 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
4248 // writes in place, not just this superblock's queue.
4249 wave_barrier(fctx);
4250 let mut ops = fctx
4251 .recon_spare
4252 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4253 fctx.recon_ops
4254 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
4255 let mut coeffs = fctx
4256 .coeff_spare
4257 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4258 fctx.coeff_arena
4259 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
4260 let mut preds = fctx
4261 .pred_spare
4262 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4263 fctx.pred_arena
4264 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
4265 let mut cur: [Vec<u16>; 3] = Default::default();
4266 for op in ops.drain(..) {
4267 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
4268 }
4269 coeffs.clear();
4270 preds.clear();
4271 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
4272 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
4273 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
4274}
4275
4276/// Performs one recorded write: the body [`flush_recon`] replays, and the
4277/// body [`push_op`] runs immediately when reconstruction is inline.
4278fn exec_op(
4279 op: ReconOp,
4280 y: &mut PlaneBuf<'static>,
4281 u: &mut PlaneBuf<'static>,
4282 v: &mut PlaneBuf<'static>,
4283 cur: &mut [Vec<u16>; 3],
4284 coeffs: &[i32],
4285 preds: &[u16],
4286 fctx: &crate::decode::FrameCtx,
4287) {
4288 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
4289 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
4290 // alone. It makes the encoder's own streams garbage, so it is a
4291 // MEASUREMENT rung only -- what it measures is how much of the encoder's
4292 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
4293 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
4294 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
4295 // stage and the parse plus the neighbour grids are the other 94%. That
4296 // is why handing the decoder the encoder's own reconstruction cannot
4297 // shrink the stage: only publishing the per-mi neighbour state the
4298 // filters read (and so never parsing at all) can.
4299 if crate::envflags::env_flag!("EC_AV1_NORECON") {
4300 return;
4301 }
4302 let mut scratch = Vec::new();
4303 match op {
4304 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
4305 ReconOp::Intra {
4306 plane,
4307 x,
4308 y: oy,
4309 bw,
4310 bh,
4311 rect,
4312 mode,
4313 angle_delta,
4314 reach,
4315 residual,
4316 cfl,
4317 filter_intra,
4318 smooth_neighbor,
4319 pred,
4320 } => exec_intra(
4321 y,
4322 u,
4323 v,
4324 plane,
4325 x,
4326 oy,
4327 bw,
4328 bh,
4329 rect,
4330 mode,
4331 angle_delta,
4332 reach,
4333 residual.resolve(coeffs, &mut scratch),
4334 cfl,
4335 filter_intra,
4336 smooth_neighbor,
4337 pred,
4338 fctx,
4339 ),
4340 ReconOp::Mc {
4341 plane,
4342 x,
4343 y: oy,
4344 stride,
4345 w,
4346 h,
4347 prediction,
4348 residual,
4349 } => {
4350 let residual = residual.resolve(coeffs, &mut scratch);
4351 match prediction {
4352 PredSrc::Owned(off, len) => {
4353 let p = &preds[off as usize..][..len as usize];
4354 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
4355 }
4356 PredSrc::Cur {
4357 plane: sp,
4358 off,
4359 src,
4360 } => {
4361 let block = std::mem::take(&mut cur[sp]);
4362 if src == stride {
4363 exec_mc(
4364 y,
4365 u,
4366 v,
4367 plane,
4368 x,
4369 oy,
4370 stride,
4371 w,
4372 h,
4373 &block[off..],
4374 residual,
4375 fctx,
4376 );
4377 } else {
4378 // A transform unit's residual is dense, so its window
4379 // of the block prediction is taken out dense too --
4380 // the copy the parsing thread used to make, made here.
4381 let mut window = Vec::with_capacity(w * h);
4382 for row in 0..h {
4383 window.extend_from_slice(&block[off + row * src..][..w]);
4384 }
4385 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
4386 }
4387 cur[sp] = block;
4388 }
4389 }
4390 }
4391 }
4392}
4393
4394/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
4395/// path ([`push_op`]'s registered planes) reaches it without ever building
4396/// the record -- which is what keeps one reconstruction thread at the cost of
4397/// the pre-lane-wave1 decoder.
4398#[allow(clippy::too_many_arguments)]
4399fn exec_intra(
4400 y: &mut PlaneBuf<'static>,
4401 u: &mut PlaneBuf<'static>,
4402 v: &mut PlaneBuf<'static>,
4403 plane: usize,
4404 x: usize,
4405 oy: usize,
4406 bw: usize,
4407 bh: usize,
4408 rect: bool,
4409 mode: usize,
4410 angle_delta: i32,
4411 reach: Reach,
4412 residual: &[i32],
4413 cfl: Option<(i32, CflSrc)>,
4414 filter_intra: Option<usize>,
4415 smooth_neighbor: bool,
4416 pred: Option<Vec<u16>>,
4417 fctx: &crate::decode::FrameCtx,
4418) {
4419 // The CfL AC signal is read HERE, off the luma that has already been
4420 // written for this block -- at parse time it would have been the previous
4421 // frame's samples.
4422 let ac = cfl.map(|(alpha, src)| {
4423 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
4424 (alpha, sig)
4425 });
4426 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
4427 let target: &mut PlaneBuf<'static> = match plane {
4428 0 => &mut *y,
4429 1 => &mut *u,
4430 _ => &mut *v,
4431 };
4432 // lane-av1cmpaudit: label the in-flight reconstruction's plane for the
4433 // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`).
4434 // Saved and restored so the rung reports THIS call's plane even under
4435 // nesting, and so both of exec_intra's return paths need no cleanup.
4436 let prev_plane = RECON_PLANE.with(|c| c.replace(plane));
4437 let _plane_guard = PlaneGuard(prev_plane);
4438 if rect {
4439 target.reconstruct_rect(
4440 x,
4441 oy,
4442 bw,
4443 bh,
4444 mode,
4445 angle_delta,
4446 reach,
4447 residual,
4448 cfl,
4449 filter_intra,
4450 smooth_neighbor,
4451 pred,
4452 fctx,
4453 );
4454 } else {
4455 target.reconstruct(
4456 x,
4457 oy,
4458 bw,
4459 mode,
4460 angle_delta,
4461 reach,
4462 residual,
4463 cfl,
4464 filter_intra,
4465 smooth_neighbor,
4466 pred,
4467 fctx,
4468 );
4469 }
4470}
4471
4472/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4473#[allow(clippy::too_many_arguments)]
4474fn exec_mc(
4475 y: &mut PlaneBuf<'static>,
4476 u: &mut PlaneBuf<'static>,
4477 v: &mut PlaneBuf<'static>,
4478 plane: usize,
4479 x: usize,
4480 oy: usize,
4481 stride: usize,
4482 w: usize,
4483 h: usize,
4484 prediction: &[u16],
4485 residual: &[i32],
4486 fctx: &crate::decode::FrameCtx,
4487) {
4488 let target: &mut PlaneBuf<'static> = match plane {
4489 0 => &mut *y,
4490 1 => &mut *u,
4491 _ => &mut *v,
4492 };
4493 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
4494}
4495
4496thread_local! {
4497 /// The current frame's `mi` grid, kept only while a frame header set
4498 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4499 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4500 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4501 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4502 /// does not allow intrabc (so nothing is paid for it).
4503 ///
4504 /// corner-cut: only [`decode_block`] (the square path) records into it,
4505 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4506 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4507 /// be wrong there; upgrade = record from the rect/leaf paths too.
4508 /// The block vector [`read_intra_mode`] just decoded, handed to
4509 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4510 /// which the alternative -- a tenth tuple member through every caller --
4511 /// already avoids). Always `.take()`n by the block that reads it.
4512 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4513 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4514 /// returns too, so it counts reads, not reconstructions (a refused block
4515 /// is never reconstructed).
4516 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4517}
4518// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4519// an intrabc block's chroma reads can inherit it (see
4520// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4521// through that one arming site.
4522// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4523// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4524// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4525// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4526// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4527// intrabc block's two chroma [`read_plane`] calls; the type decides the
4528// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4529// -- getting it wrong desyncs the chroma coefficients, it is not a
4530// reconstruction-only detail.
4531
4532/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4533/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4534/// needs no separate plumbing to reach the rect-strip mode reader.
4535fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4536 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4537}
4538
4539thread_local! {
4540 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4541 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4542 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4543 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4544}
4545
4546/// Current value of [`RECT_INTRABC_READS`].
4547pub(crate) fn rect_intrabc_reads() -> usize {
4548 RECT_INTRABC_READS.with(|c| c.get())
4549}
4550
4551/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4552#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4553pub(crate) fn reset_rect_intrabc_reads() {
4554 RECT_INTRABC_READS.with(|c| c.set(0));
4555}
4556
4557thread_local! {
4558 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4559 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4560 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4561}
4562
4563thread_local! {
4564 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4565 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4566 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4567 /// counter: zero means the gate's fixture no longer reaches the route).
4568 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4569 const { std::cell::Cell::new(0) };
4570}
4571
4572/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4573#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4574pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4575 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4576}
4577
4578/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4579#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4580pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4581 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4582}
4583
4584/// Current value of [`LEAF8_INTRABC_HITS`].
4585pub(crate) fn leaf8_intrabc_hits() -> usize {
4586 LEAF8_INTRABC_HITS.with(|c| c.get())
4587}
4588
4589/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4590#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4591pub(crate) fn reset_leaf8_intrabc_hits() {
4592 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4593}
4594
4595/// Current value of [`INTRABC_HITS`].
4596#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4597pub(crate) fn intrabc_hits() -> usize {
4598 INTRABC_HITS.with(|c| c.get())
4599}
4600
4601thread_local! {
4602 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4603 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4604 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4605 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4606 /// here. A non-zero value is what makes the disarm below load-bearing.
4607 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4608 const { std::cell::Cell::new(0) };
4609}
4610
4611/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4612#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4613pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4614 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4615}
4616
4617/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4618/// decode).
4619#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4620pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4621 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4622}
4623
4624thread_local! {
4625 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4626 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4627 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4628 /// Before the fix this route predicted intra-DC and every one of this
4629 /// fixture's 150 such cells differed from the oracle on both chroma
4630 /// planes.
4631 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4632 const { std::cell::Cell::new(0) };
4633}
4634
4635/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4636#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4637pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4638 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4639}
4640
4641/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4642/// decode).
4643#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4644pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4645 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4646}
4647
4648/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4649#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4650pub(crate) fn reset_intrabc_hits() {
4651 INTRABC_HITS.with(|c| c.set(0));
4652}
4653
4654thread_local! {
4655 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4656 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4657 /// that replaced the refusal "an intrabc block under TxMode::Select".
4658 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4659 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4660 /// sizes (not one square size across every leaf) -- the engagement
4661 /// counter proving a witness actually exercises the per-leaf reconstruct.
4662 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4663 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4664 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4665 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4666 /// symbol here desynced `warped.obu` at the very next block.
4667 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4668 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4669 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4670 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4671 /// this one).
4672 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4673 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4674 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4675 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4676 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4677 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4678 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4679 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4680 /// counts neither orientation nor the skip flag, so an arm that flipped
4681 /// to an all-skip stream (no residual reader at all) would stay green.
4682 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4683 const { std::cell::Cell::new([0, 0]) };
4684 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4685 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4686 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4687 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4688 /// invisible to every gate because they only counted CODED strips.
4689 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4690 const { std::cell::Cell::new([0, 0]) };
4691 /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized
4692 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4693 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no
4694 /// halving of its own. At 4:2:0 this is the same arithmetic as the halving,
4695 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4696 /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's
4697 /// chroma plane block.
4698 static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4699 const { std::cell::Cell::new(0) };
4700 /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block
4701 /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR
4702 /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes
4703 /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block,
4704 /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's
4705 /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a
4706 /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm:
4707 /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot
4708 /// be satisfied by any older route.
4709 static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell<usize> =
4710 const { std::cell::Cell::new(0) };
4711 /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips
4712 /// ([`decode_intrabc_owned_rect`]) 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:1372) applies
4715 /// no halving of its own. At 4:2:0 the two forms are the same arithmetic,
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 a 128-root intra-BC
4718 /// strip's chroma plane block.
4719 static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4720 const { std::cell::Cell::new(0) };
4721}
4722
4723/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4724/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4725#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4726pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4727 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4728}
4729
4730/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4731/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4732#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4733pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4734 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4735}
4736
4737/// Current value of [`INTRABC_RECT_HITS`].
4738#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4739pub fn intrabc_rect_hits() -> usize {
4740 INTRABC_RECT_HITS.with(|c| c.get())
4741}
4742
4743/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4744#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4745pub(crate) fn reset_intrabc_rect_hits() {
4746 INTRABC_RECT_HITS.with(|c| c.set(0));
4747 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4748 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4749 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4750}
4751
4752/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4753#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4754pub fn ibc_rect_chroma_footprint_444_hits() -> usize {
4755 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4756}
4757
4758/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4759#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4760pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() {
4761 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4762}
4763
4764/// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4765#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4766pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
4767 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4768}
4769
4770/// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4771#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4772pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
4773 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4774}
4775
4776/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4777#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4778pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
4779 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
4780}
4781
4782/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4783#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4784pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
4785 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
4786}
4787
4788/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4789#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4790pub fn intrabc_rect_vartx_hits() -> usize {
4791 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4792}
4793
4794thread_local! {
4795 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4796 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4797 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4798 /// guard (`decode_block_128rect`). A refused block bumps
4799 /// [`INTRABC_HITS`] but never this one.
4800 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4801 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4802 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4803 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4804 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4805 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4806 /// side` model walked the 4:2:0 count on every axis, so this counter is
4807 /// the reach/arm witness for the per-axis walk.
4808 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4809 const { std::cell::Cell::new(0) };
4810 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4811 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4812 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4813 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4814 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4815 const { std::cell::Cell::new(0) };
4816}
4817
4818/// Current value of [`INTRABC_128RECT_HITS`].
4819#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4820pub fn intrabc_128rect_hits() -> usize {
4821 INTRABC_128RECT_HITS.with(|c| c.get())
4822}
4823
4824/// Zeroes [`INTRABC_128RECT_HITS`].
4825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4826pub(crate) fn reset_intrabc_128rect_hits() {
4827 INTRABC_128RECT_HITS.with(|c| c.set(0));
4828}
4829
4830/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
4831#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4832pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
4833 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
4834}
4835
4836/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
4837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4838pub fn intrabc_128rect_chunk_shape() -> usize {
4839 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
4840}
4841
4842/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
4843/// [`INTRABC_128RECT_CHUNK_SHAPE`].
4844#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4845pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
4846 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
4847 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
4848}
4849
4850/// Current value of [`INTRABC_VARTX_HITS`].
4851pub fn intrabc_vartx_hits() -> usize {
4852 INTRABC_VARTX_HITS.with(|c| c.get())
4853}
4854
4855/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4856pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4857 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4858}
4859
4860/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4862pub(crate) fn reset_intrabc_vartx_hits() {
4863 INTRABC_VARTX_HITS.with(|c| c.set(0));
4864}
4865
4866/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4867/// decode).
4868#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4869pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4870 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4871}
4872
4873/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4874#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4875pub fn rect_intrabc_vartx_hits() -> usize {
4876 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4877}
4878
4879/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4880/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4881/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4882/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4883fn record_intrabc_mi(
4884 mi_r: usize,
4885 mi_c: usize,
4886 n4: usize,
4887 dv: Option<(i32, i32)>,
4888 n: &mut Neighbours,
4889 fctx: &crate::decode::FrameCtx,
4890) {
4891 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4892}
4893
4894/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4895/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4896/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4897///
4898/// Also stamps libaom's `is_inter_block` verdict for this block into the
4899/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4900/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4901/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4902/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4903/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4904/// every block runs; this runs after it (class leaked-band otherwise).
4905fn record_intrabc_mi_rect(
4906 mi_r: usize,
4907 mi_c: usize,
4908 n4_w: usize,
4909 n4_h: usize,
4910 dv: Option<(i32, i32)>,
4911 n: &mut Neighbours,
4912 fctx: &crate::decode::FrameCtx,
4913) {
4914 if dv.is_some() {
4915 for i in 0..n4_w {
4916 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4917 *cell = true;
4918 }
4919 }
4920 for i in 0..n4_h {
4921 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4922 *cell = true;
4923 }
4924 }
4925 }
4926 fctx.intrabc_mi_grid.with(|g| {
4927 let mut g = g.borrow_mut();
4928 let Some((grid, _, _)) = g.as_mut() else {
4929 return;
4930 };
4931 let info = crate::mvstack::MiInfo {
4932 is_inter: dv.is_some(),
4933 ref_frame: 0,
4934 ref_frame1: NO_REF1,
4935 mv: mv16(dv.unwrap_or((0, 0))),
4936 mv1: (0, 0),
4937 is_new_mv: dv.is_some(),
4938 is_global_mv0: false,
4939 is_global_mv1: false,
4940 size: n4_w as u8,
4941 size_h: n4_h as u8,
4942 };
4943 for r in mi_r..mi_r + n4_h {
4944 for c in mi_c..mi_c + n4_w {
4945 grid.set(r, c, info);
4946 }
4947 }
4948 });
4949}
4950
4951// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4952// proves a real `skip_mode_present` stream actually reached a block that
4953// picked it, not just that the frame header bit was set.
4954thread_local! {
4955 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4956 const { std::cell::Cell::new(0) };
4957}
4958
4959/// Current value of [`SKIP_MODE_HITS`].
4960#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4961pub(crate) fn skip_mode_hits() -> usize {
4962 SKIP_MODE_HITS.with(|c| c.get())
4963}
4964
4965// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4966// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4967// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4968// reached [`obmc_blend`], not just the header bit.
4969thread_local! {
4970 static OBMC_HITS: std::cell::Cell<usize> =
4971 const { std::cell::Cell::new(0) };
4972}
4973
4974// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4975// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4976// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4977// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4978// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
4979// decoder used to read with the wrong alphabet, so a gate that asserts this
4980// counter advanced proves the fixed path fired (class
4981// `gate-blind-to-feature`).
4982thread_local! {
4983 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4984}
4985
4986/// Current value of [`FIMV_ALPHABET_HITS`].
4987pub fn fimv_alphabet_hits() -> usize {
4988 FIMV_ALPHABET_HITS.with(|c| c.get())
4989}
4990
4991// lane-fimv r1: how many frame headers this decoder has decoded with
4992// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
4993// prove the encoder really produced the header state under test rather than
4994// assume it.
4995thread_local! {
4996 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4997}
4998
4999/// Current value of [`FIMV_FRAME_HITS`].
5000pub fn fimv_frame_hits() -> usize {
5001 FIMV_FRAME_HITS.with(|c| c.get())
5002}
5003
5004/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
5005/// `force_integer_mv` bit is set.
5006pub fn note_force_integer_mv_frame() {
5007 hit!(FIMV_FRAME_HITS);
5008}
5009
5010/// Current value of [`OBMC_HITS`].
5011#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5012pub(crate) fn obmc_hits() -> usize {
5013 OBMC_HITS.with(|c| c.get())
5014}
5015
5016// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
5017// off the neighbour band -- the positive half of the proof for "an OBMC
5018// neighbour whose switchable interp filter was never recorded". A
5019// fixed-filter frame returns before this point (its neighbours legitimately
5020// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
5021// `interp_filter` symbols were published by `record_inter_rect_mi`.
5022thread_local! {
5023 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5024}
5025
5026/// Current value of [`OBMC_FILTER_BAND_READS`].
5027#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5028pub(crate) fn obmc_filter_band_reads() -> usize {
5029 OBMC_FILTER_BAND_READS.with(|c| c.get())
5030}
5031
5032// lane-scaledref r1: per-case firing counts for the scaled-reference gate
5033// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
5034// reference would pass just as well and prove nothing, so the gate
5035// hard-asserts each combination this round lifts actually occurred:
5036// a compound block with a scaled tap, a warp block whose warp libaom
5037// suppresses because the reference is scaled, an OBMC block, an interintra
5038// block, and an 8x8 leaf.
5039thread_local! {
5040 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5041 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5042 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5043 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5044 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5045 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5046 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5047}
5048
5049/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5050/// scaled and one unscaled tap.
5051#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5052pub(crate) fn mixed_scale_compound_hits() -> usize {
5053 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5054}
5055
5056/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5057/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5058/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5059/// `blockd.h:1484`).
5060#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5061pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5062 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5063}
5064
5065/// Current value of [`SCALED_COMPOUND_HITS`].
5066#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5067pub(crate) fn scaled_compound_hits() -> usize {
5068 SCALED_COMPOUND_HITS.with(|c| c.get())
5069}
5070
5071/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5072pub fn scaled_warp_fallback_hits() -> usize {
5073 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5074}
5075
5076/// Current value of [`SCALED_OBMC_HITS`].
5077#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5078pub(crate) fn scaled_obmc_hits() -> usize {
5079 SCALED_OBMC_HITS.with(|c| c.get())
5080}
5081
5082/// Current value of [`SCALED_INTERINTRA_HITS`].
5083#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5084pub(crate) fn scaled_interintra_hits() -> usize {
5085 SCALED_INTERINTRA_HITS.with(|c| c.get())
5086}
5087
5088/// Current value of [`SCALED_BLOCK8_HITS`].
5089#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5090pub(crate) fn scaled_block8_hits() -> usize {
5091 SCALED_BLOCK8_HITS.with(|c| c.get())
5092}
5093
5094// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5095// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5096// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5097// 8x8-leaf OBMC block apart from a 16x16+ one.
5098thread_local! {
5099 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5100}
5101
5102// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5103// pair whose two directions differ (`enable_dual_filter` only -- with dual
5104// filter off both directions take the single symbol, so this can never fire).
5105// A gate asserting it proves the stream really carries dual-filter blocks.
5106thread_local! {
5107 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5108}
5109
5110// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5111// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5112// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5113// no-filter sentinel that made a neighbouring OBMC block panic).
5114thread_local! {
5115 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5116}
5117
5118/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5119#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5120pub(crate) fn dual_filter_diff_hits() -> usize {
5121 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5122}
5123
5124/// Current value of [`COMPOUND8_FILTER_HITS`].
5125#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5126pub(crate) fn compound8_filter_hits() -> usize {
5127 COMPOUND8_FILTER_HITS.with(|c| c.get())
5128}
5129
5130// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5131// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5132// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5133// -- the gate's proof that a fixture really exercises the alphabet this
5134// round changed, even though the block itself still refuses (warp
5135// estimation/filter not ported).
5136thread_local! {
5137 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5138 const { std::cell::Cell::new(0) };
5139}
5140
5141/// Current value of [`WARP_SELECTED_HITS`].
5142#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5143pub(crate) fn warp_selected_hits() -> usize {
5144 WARP_SELECTED_HITS.with(|c| c.get())
5145}
5146
5147// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5148// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5149// into the compound intermediate) rather than translationally -- the
5150// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5151// really reached [`crate::warp::warp_affine_compound`].
5152// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5153// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5154// counter is frame-global. These two are the same arms restricted to blocks
5155// whose top mode-info row is in the frame's upper half, which is the half
5156// this lane's evidence covers.
5157thread_local! {
5158 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5159 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5160}
5161
5162/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5163/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5164///
5165/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5166/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5167/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5168/// The figure quoted for that fixture comes from a patch-run-restore build
5169/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5170/// is the same discipline every 4:2:2 lane in this family uses.
5171#[allow(dead_code)]
5172pub(crate) fn top_half_compound_hits() -> usize {
5173 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5174}
5175
5176/// How many inter blocks in the frame's upper half satisfy libaom's
5177/// `is_global_mv_block` on at least one reference slot -- mode
5178/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5179/// model > `TRANSLATION`. This is the block set whose prediction goes
5180/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5181/// as computed at the increment site; it is NOT merely "some slot has a
5182/// non-TRANSLATION model", which also counts blocks that are not global-mv
5183/// blocks.
5184///
5185/// Like [`top_half_compound_hits`], no committed test reads it: with the
5186/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5187/// these numbers describe.
5188#[allow(dead_code)]
5189pub(crate) fn top_half_warp_hits() -> usize {
5190 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5191}
5192
5193thread_local! {
5194 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5195 const { std::cell::Cell::new(0) };
5196}
5197
5198/// Current value of [`COMPOUND_WARP_HITS`].
5199#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5200pub(crate) fn compound_warp_hits() -> usize {
5201 COMPOUND_WARP_HITS.with(|c| c.get())
5202}
5203
5204// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5205// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5206// translationally until r3, so a gate needs to tell a warped 8x8 compound
5207// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5208thread_local! {
5209 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5210 const { std::cell::Cell::new(0) };
5211}
5212
5213/// Current value of [`COMPOUND_WARP_HITS_8`].
5214#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5215pub(crate) fn compound_warp_hits_8() -> usize {
5216 COMPOUND_WARP_HITS_8.with(|c| c.get())
5217}
5218
5219// lane-gmaffine r1: how many blocks built their prediction from a
5220// SIX-parameter (`AFFINE`) global-motion model through
5221// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5222// carried an AFFINE `global_motion_params` AND that a block was predicted
5223// with it, not merely that the header parsed one.
5224thread_local! {
5225 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5226 const { std::cell::Cell::new(0) };
5227}
5228
5229/// Current value of [`AFFINE_GM_HITS`].
5230#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5231pub(crate) fn affine_gm_hits() -> usize {
5232 AFFINE_GM_HITS.with(|c| c.get())
5233}
5234
5235// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5236// combine rather than the simple average -- `compound_idx == 0` under
5237// `enable_jnt_comp`, whose weights come from
5238// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5239// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5240// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5241// stream that carries `enable_jnt_comp = true` in its sequence header but
5242// codes every compound block with `compound_idx == 1` leaves this at 0 and
5243// decoded identically without the whole distance-weight path.
5244thread_local! {
5245 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5246 const { std::cell::Cell::new(0) };
5247}
5248
5249/// Current value of [`DIST_WTD_COMP_HITS`].
5250#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5251pub(crate) fn dist_wtd_comp_hits() -> usize {
5252 DIST_WTD_COMP_HITS.with(|c| c.get())
5253}
5254
5255/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5256#[allow(dead_code)] // test-only
5257pub(crate) fn reset_dist_wtd_comp_hits() {
5258 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5259}
5260
5261// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5262// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5263// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5264// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5265// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5266// side build and its own counter, [`AFFINE_GM_HITS`]).
5267thread_local! {
5268 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5269 const { std::cell::Cell::new(0) };
5270}
5271
5272/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5273#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5274pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5275 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5276}
5277
5278// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5279// differently at the block's WIDTH than at libaom's
5280// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5281// pick the wrong motion_mode alphabet.
5282thread_local! {
5283 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5284}
5285
5286/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5287pub fn tr_reach_longer_side_hits() -> usize {
5288 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5289}
5290
5291// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5292// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5293// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5294// reads its interp-filter symbol. Counts the blocks where that guard flips
5295// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5296// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5297// entropy desync one symbol wide).
5298thread_local! {
5299 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5300}
5301
5302/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5303pub fn gm_nontrans_small_side_hits() -> usize {
5304 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5305}
5306
5307// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5308// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5309// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5310// only once `find_projection` returned a usable model, unlike
5311// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5312// proof that the leaf path itself fired, not the 16x16+ one.
5313thread_local! {
5314 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5315 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5316}
5317
5318/// Current value of [`GLOBALMV_HITS_8`].
5319#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5320pub(crate) fn globalmv_hits_8() -> usize {
5321 GLOBALMV_HITS_8.with(|c| c.get())
5322}
5323
5324/// Current value of [`WARP_HITS_8`].
5325#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5326pub(crate) fn warp_hits_8() -> usize {
5327 WARP_HITS_8.with(|c| c.get())
5328}
5329
5330// How many blocks decoded `interintra == 1` with the non-wedge blended
5331// prediction applied (lane-interintra r1) -- the gate's proof that a
5332// stream actually exercised interintra.
5333thread_local! {
5334 static INTERINTRA_HITS: std::cell::Cell<usize> =
5335 const { std::cell::Cell::new(0) };
5336}
5337
5338/// Current value of [`INTERINTRA_HITS`].
5339#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5340pub(crate) fn interintra_hits() -> usize {
5341 INTERINTRA_HITS.with(|c| c.get())
5342}
5343
5344// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5345// -- the shape `interintra_blend` used to build a square `side x side` intra
5346// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5347// pre-existing interintra gate passed with that bug, so the rect arm needs
5348// its own counter to stop being vacuous.
5349thread_local! {
5350 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5351}
5352
5353/// Current value of [`INTERINTRA_RECT_HITS`].
5354pub fn interintra_rect_hits() -> usize {
5355 INTERINTRA_RECT_HITS.with(|c| c.get())
5356}
5357
5358// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5359// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5360// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5361// gate fixture actually exercises this alphabet, even though the block
5362// still refuses (the mask blend itself is unported).
5363thread_local! {
5364 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5365 const { std::cell::Cell::new(0) };
5366}
5367
5368/// Current value of [`MASKED_COMPOUND_HITS`].
5369#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5370pub(crate) fn masked_compound_hits() -> usize {
5371 MASKED_COMPOUND_HITS.with(|c| c.get())
5372}
5373
5374// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5375// masked-compound block whose true footprint is rectangular, i.e. the case
5376// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5377// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5378// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5379thread_local! {
5380 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5381 const { std::cell::Cell::new(0) };
5382}
5383
5384/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5385#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5386pub(crate) fn rect_masked_compound_hits() -> usize {
5387 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5388}
5389
5390// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5391// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5392// actually exercised the wedge blend, not just the DIFFWTD half of
5393// `MASKED_COMPOUND_HITS`.
5394thread_local! {
5395 static WEDGE_HITS: std::cell::Cell<usize> =
5396 const { std::cell::Cell::new(0) };
5397}
5398
5399/// Current value of [`WEDGE_HITS`].
5400#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5401pub(crate) fn wedge_hits() -> usize {
5402 WEDGE_HITS.with(|c| c.get())
5403}
5404
5405// How many blocks decoded a real wedge-INTERINTRA block
5406// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5407// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5408// smooth arm counted by `INTERINTRA_HITS`.
5409thread_local! {
5410 static WII_HITS: std::cell::Cell<usize> =
5411 const { std::cell::Cell::new(0) };
5412}
5413
5414/// Current value of [`WII_HITS`].
5415#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5416pub(crate) fn wii_hits() -> usize {
5417 WII_HITS.with(|c| c.get())
5418}
5419
5420// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5421// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5422// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5423// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5424// frame carrying one.
5425thread_local! {
5426 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5427}
5428
5429/// Current value of [`NOCFL_UV_MODE_HITS`].
5430#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5431pub(crate) fn nocfl_uv_mode_hits() -> usize {
5432 NOCFL_UV_MODE_HITS.with(|c| c.get())
5433}
5434
5435/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5436/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5437pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5438 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5439
5440fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5441 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5442}
5443
5444// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5445// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5446// the rect wedge masks lifted this round actually fired, not just the square
5447// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5448thread_local! {
5449 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5450 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5451}
5452
5453/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5454pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5455 RECT_WEDGE_HITS.with(|c| c.get())
5456}
5457
5458/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5459pub(crate) fn rect_wii_hits() -> [usize; 6] {
5460 RECT_WII_HITS.with(|c| c.get())
5461}
5462
5463// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5464// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5465// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5466// aomdec, neighbour list included).
5467thread_local! {
5468 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5469}
5470
5471/// Current value of [`OBMC_RECT_LEAF_HITS`].
5472pub(crate) fn obmc_rect_leaf_hits() -> usize {
5473 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5474}
5475
5476// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5477// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5478// to be read from the pair's FIRST mi, which is a different block and, when
5479// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5480// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5481thread_local! {
5482 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5483}
5484
5485/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5486pub(crate) fn obmc_pair_filter_hits() -> usize {
5487 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5488}
5489
5490// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5491// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5492// own side, so a block overhanging the bottom/right still predicts the full
5493// neighbour strip (the destination write is what clips). We used to shrink the
5494// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5495// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5496thread_local! {
5497 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5498}
5499
5500/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5501#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5502pub(crate) fn obmc_edge_span_hits() -> usize {
5503 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5504}
5505
5506/// Current value of [`OBMC_HITS_8`].
5507#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5508pub(crate) fn obmc_hits_8() -> usize {
5509 OBMC_HITS_8.with(|c| c.get())
5510}
5511
5512// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5513// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5514// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5515// `VERT_B` all still fall into the generic "a partition type this encoder
5516// never writes" refusal below) -- the gate's proof that a free-partition
5517// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5518// coincidentally never selecting one.
5519thread_local! {
5520 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5521 const { std::cell::Cell::new(0) };
5522}
5523
5524/// Current value of [`EXTENDED_PARTITION_HITS`].
5525#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5526pub(crate) fn extended_partition_hits() -> usize {
5527 EXTENDED_PARTITION_HITS.with(|c| c.get())
5528}
5529
5530// lane-partitions r1: how many 32x32 quadrants decoded a real
5531// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5532// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5533// gate's proof this round's arms actually fired.
5534thread_local! {
5535 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5536 const { std::cell::Cell::new(0) };
5537}
5538
5539/// Current value of [`RECT_PARTITION_HITS`].
5540#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5541pub(crate) fn rect_partition_hits() -> usize {
5542 RECT_PARTITION_HITS.with(|c| c.get())
5543}
5544
5545// lane-inter8 r1: how many superblocks an inter tile coded as a single
5546// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5547// static content, previously a named refusal).
5548thread_local! {
5549 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5550 /// path decoded as one whole block (its gate's own witness).
5551 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5552 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5553 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5554 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5555}
5556
5557/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5558pub(crate) fn inter_sb128_horz_hits() -> usize {
5559 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5560}
5561
5562/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5563pub(crate) fn inter_sb128_vert_hits() -> usize {
5564 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5565}
5566
5567/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5568pub fn inter_sb128_none_hits() -> usize {
5569 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5570}
5571
5572thread_local! {
5573 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5574 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5575 /// units) -- the gate's witness that the lifted refusal's case fired.
5576 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5577}
5578
5579/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5580pub fn intra_128_in_inter_hits() -> usize {
5581 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5582}
5583
5584thread_local! {
5585 /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the
5586 /// intra-in-inter 128x128 root read (`decode_inter_block`'s
5587 /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every
5588 /// unit is one `read_plane` on U and one on V, so the counter is the
5589 /// gate's proof the arm ran at all -- no committed 4:4:4 fixture
5590 /// reached it before this lane.
5591 pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell<usize> =
5592 const { std::cell::Cell::new(0) };
5593}
5594
5595/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's
5596/// before/after delta.
5597pub fn intra_128_in_inter_mu_chroma_hits() -> usize {
5598 INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get)
5599}
5600
5601thread_local! {
5602 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5603 const { std::cell::Cell::new(0) };
5604}
5605
5606/// Current value of [`INTER_SB_NONE_HITS`].
5607#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5608pub(crate) fn inter_sb_none_hits() -> usize {
5609 INTER_SB_NONE_HITS.with(|c| c.get())
5610}
5611
5612// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5613// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5614// path has always run that loop, so only this counter proves the newly-lifted
5615// alphabet value fired.
5616thread_local! {
5617 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5618 const { std::cell::Cell::new(0) };
5619}
5620
5621/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5622#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5623pub(crate) fn inter_sub16_split_hits() -> usize {
5624 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5625}
5626
5627// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5628// while at least one reference picture was SCALED (superres) -- the counter
5629// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5630thread_local! {
5631 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5632 const { std::cell::Cell::new(0) };
5633}
5634
5635/// Current value of [`SCALED_LEAF8_HITS`].
5636pub fn scaled_leaf8_hits() -> usize {
5637 SCALED_LEAF8_HITS.with(|c| c.get())
5638}
5639
5640// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5641// rect pair) were predicted from a SCALED reference -- the counter behind the
5642// lifted "sub-8x8 inter block under a scaled reference" refusal.
5643thread_local! {
5644 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5645 const { std::cell::Cell::new(0) };
5646}
5647
5648/// Current value of [`SCALED_SUB8_HITS`].
5649pub fn scaled_sub8_hits() -> usize {
5650 SCALED_SUB8_HITS.with(|c| c.get())
5651}
5652
5653// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5654// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5655// rect coefficient reader itself fired, not just the strip-level partition
5656// symbol [`RECT_PARTITION_HITS`] already counts.
5657thread_local! {
5658 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5659 const { std::cell::Cell::new(0) };
5660}
5661
5662/// Current value of [`RECT_COEFF_HITS`].
5663#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5664pub(crate) fn rect_coeff_hits() -> usize {
5665 RECT_COEFF_HITS.with(|c| c.get())
5666}
5667
5668// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5669// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5670// charter's real-aomenc gate hard-asserts.
5671thread_local! {
5672 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5673 const { std::cell::Cell::new(0) };
5674}
5675
5676/// Current value of [`RECT_LEAF_COEFF_HITS`].
5677#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5678pub(crate) fn rect_leaf_coeff_hits() -> usize {
5679 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5680}
5681
5682// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5683// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5684// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5685// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5686// needs rectangular intra prediction" before this round.
5687thread_local! {
5688 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5689 const { std::cell::Cell::new([0; 3]) };
5690}
5691
5692/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5693/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5694#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5695pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5696 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5697}
5698
5699// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5700// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5701// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5702// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5703// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5704// a single counter cannot tell an axis swap from a working arm
5705// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5706thread_local! {
5707 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5708 const { std::cell::Cell::new([0; 2]) };
5709}
5710
5711/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5712/// (0 = 64x32, 1 = 32x64).
5713pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5714 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5715}
5716
5717// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5718// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5719// is never incremented) -- the gate's proof that the lifted path ran per depth.
5720thread_local! {
5721 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5722 const { std::cell::Cell::new([0; 3]) };
5723}
5724
5725// lane-t900 r21: rect intra strips inside an inter frame that read the
5726// screen-content palette syntax (`allow_screen_content_tools` set and the
5727// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5728// refusal used to guard, so this counter is what keeps its witness gate
5729// non-vacuous.
5730thread_local! {
5731 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5732}
5733
5734/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5735#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5736pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5737 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5738}
5739
5740/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5741#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5742pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5743 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5744}
5745
5746/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5747#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5748pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5749 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5750}
5751
5752// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5753// approximation would have resolved off a DIFFERENT CDF row than the real
5754// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5755// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5756// tally is green on the old code too (class gate-blind-to-feature).
5757thread_local! {
5758 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5759 const { std::cell::Cell::new(0) };
5760}
5761
5762/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5763#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5764pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5765 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5766}
5767
5768// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5769// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5770// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5771// rect strip on the inter block path" before this round.
5772thread_local! {
5773 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5774 const { std::cell::Cell::new([0; 4]) };
5775}
5776
5777/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5778/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5779pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5780 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5781}
5782
5783// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5784// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5785// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5786// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5787// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
5788// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
5789// REACH only, never that the fix bites -- that is the gate's byte compare and
5790// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
5791thread_local! {
5792 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5793}
5794
5795/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5796#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5797pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5798 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5799}
5800
5801/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
5802#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5803pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
5804 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
5805}
5806
5807// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
5808// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
5809// stream of the same recipe leaves it at 0, which is what makes it the
5810// 4:4:4-only route.
5811//
5812// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
5813// never was. A route counter fires identically before and after a change that
5814// changes nothing downstream, so a non-zero count proves REACH and nothing
5815// more. On this lane it is also armed deliberately OUTSIDE the `own444`
5816// expression, so that the mutation (`own444 = false`) still increments it and
5817// the red comes from the pixel/entropy arm instead. The evidence that the ss
5818// gate bites is the measured fork move -- first entropy fork read 11750 ->
5819// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
5820// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
5821// a DIFFERS-style assertion to carry a claim.
5822thread_local! {
5823 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5824}
5825
5826/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
5827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5828pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
5829 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5830}
5831
5832/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
5833#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5834pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
5835 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
5836}
5837
5838// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
5839// through one of the key-frame rect readers ([`decode_block_rect4`],
5840// [`decode_block_rect64`]). `Some((size_group, skip))` tells
5841// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
5842// already read by [`decode_inter_block`] and (b) the luma mode comes off
5843// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
5844// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
5845
5846// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
5847// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
5848// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
5849// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
5850thread_local! {
5851 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5852 const { std::cell::Cell::new(0) };
5853}
5854
5855/// Current value of [`MODE_MI_OVERRIDE_HITS`].
5856#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5857pub(crate) fn mode_mi_override_hits() -> usize {
5858 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5859}
5860
5861// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
5862// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
5863// mode from the previous tile, where libaom's `up_available`/`left_available`
5864// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
5865// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
5866// per superblock row in `start_row`, so the luma fallback cannot leak the way
5867// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
5868// the invariant that makes the coarse fallback safe.
5869thread_local! {
5870 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
5871 const { std::cell::Cell::new(0) };
5872}
5873
5874/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
5875#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5876pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
5877 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
5878}
5879
5880// lane-cfl r1: how many times a chroma intra-edge filter-type read
5881// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
5882// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
5883// r1 defect would have filtered a chroma edge with the wrong strength.
5884thread_local! {
5885 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5886 const { std::cell::Cell::new(0) };
5887}
5888
5889/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
5890#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5891pub(crate) fn uv_mode_mi_override_hits() -> usize {
5892 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5893}
5894
5895// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
5896// `uv_mode` from the mi GRID where the one-slot-per-column map would have
5897// answered differently -- the sub-8x8 pair case where the pair's own first
5898// half had already overwritten the column slot the chroma-ref half reads.
5899thread_local! {
5900 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
5901 const { std::cell::Cell::new(0) };
5902}
5903
5904/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
5905pub fn uv_mode_grid_override_hits() -> usize {
5906 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
5907}
5908
5909// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
5910// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
5911// from an earlier block in that pixel row/column while the mi-exact map --
5912// which an inter block only started writing this round -- correctly says the
5913// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
5914// an INTER mode, and its `uv_mode` "is not set for inter blocks").
5915thread_local! {
5916 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
5917 const { std::cell::Cell::new(0) };
5918}
5919
5920/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
5921#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5922pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
5923 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
5924}
5925
5926// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
5927// suppressed at a TILE edge that is not a frame edge -- the above/left
5928// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
5929// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
5930// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
5931// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
5932// above would decide this tile's chroma edge filter strength.
5933thread_local! {
5934 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
5935 const { std::cell::Cell::new(0) };
5936}
5937
5938/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
5939#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5940pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
5941 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
5942}
5943
5944// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
5945// left neighbour whose `uv_mode` at libaom's real read cell
5946// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
5947// cell this decoder used to read (its own mi row). Two buckets: the raw mode
5948// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
5949// flipped. The second is the one that can move pixels.
5950thread_local! {
5951 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
5952 const { std::cell::Cell::new(0) };
5953 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
5954 const { std::cell::Cell::new(0) };
5955}
5956thread_local! {
5957 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5958}
5959
5960/// Current value of [`UV_LEFT_SS_Y_READS`].
5961pub fn uv_left_ss_y_reads() -> usize {
5962 UV_LEFT_SS_Y_READS.with(|c| c.get())
5963}
5964
5965/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
5966pub fn uv_left_ss_y_mode_diff_hits() -> usize {
5967 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
5968}
5969
5970/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
5971pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
5972 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
5973}
5974
5975// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
5976// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
5977// decoder reads (its own mi row) and the cell libaom reads (one row down)
5978// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
5979// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
5980// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
5981thread_local! {
5982 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5983}
5984
5985/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
5986pub fn uv_left_1mi_split_hits() -> usize {
5987 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
5988}
5989
5990// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
5991// Bumped in `Neighbours::start_tile`; never read by decode logic.
5992thread_local! {
5993 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
5994}
5995
5996// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
5997// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
5998// shapes the r1 chroma defect showed up on.
5999thread_local! {
6000 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6001 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6002}
6003// lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4
6004// arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample)
6005// and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two
6006// reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability
6007// evidence for that function's format-blind extent.
6008thread_local! {
6009 static CFL_AC_444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6010 static CFL_AC_422_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6011 static CFL_AC_420_SQ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6012 static CFL_AC_420_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6013 static CFL_AC_Q3_AT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6014}
6015
6016/// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits.
6017pub fn cfl_ac_arm_hits() -> [usize; 4] {
6018 [
6019 CFL_AC_444_HITS.with(|c| c.get()),
6020 CFL_AC_422_HITS.with(|c| c.get()),
6021 CFL_AC_420_SQ_HITS.with(|c| c.get()),
6022 CFL_AC_420_RECT_HITS.with(|c| c.get()),
6023 ]
6024}
6025
6026/// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is
6027/// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate
6028/// proves it is reached ONLY at 4:2:0.
6029pub fn cfl_ac_q3_at_hits() -> usize {
6030 CFL_AC_Q3_AT_HITS.with(|c| c.get())
6031}
6032
6033/// Current value of [`CFL_BLOCK_HITS`].
6034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6035pub(crate) fn cfl_block_hits() -> usize {
6036 CFL_BLOCK_HITS.with(|c| c.get())
6037}
6038
6039/// Current value of [`UV_ANGLE_DELTA_HITS`].
6040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6041pub(crate) fn uv_angle_delta_hits() -> usize {
6042 UV_ANGLE_DELTA_HITS.with(|c| c.get())
6043}
6044
6045// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
6046// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
6047// gate's proof this round's arms actually reached a real block, not just
6048// that `partition_w64` read one of those two symbol values.
6049thread_local! {
6050 static SB_RECT_HITS: std::cell::Cell<usize> =
6051 const { std::cell::Cell::new(0) };
6052}
6053
6054// Current value of [`SB_RECT_HITS`].
6055// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
6056// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
6057// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
6058// non-SPLIT edge arm actually decoded (before this round the bit was read and
6059// thrown away, so that arm was unreachable).
6060thread_local! {
6061 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6062}
6063
6064/// Current value of [`EDGE_PART_HITS`].
6065#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6066pub(crate) fn edge_part_hits() -> [usize; 4] {
6067 EDGE_PART_HITS.with(|c| c.get())
6068}
6069
6070/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
6071#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6072pub(crate) fn reset_edge_part_hits() {
6073 EDGE_PART_HITS.with(|c| c.set([0; 4]));
6074}
6075
6076fn bump_edge_part(slot: usize) {
6077 hit_do! {
6078 EDGE_PART_HITS.with(|c| {
6079 let mut h = c.get();
6080 h[slot] += 1;
6081 c.set(h);
6082 });
6083 }
6084}
6085
6086#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6087pub(crate) fn sb_rect_hits() -> usize {
6088 SB_RECT_HITS.with(|c| c.get())
6089}
6090
6091// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
6092// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
6093// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
6094// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6095// paths (intra and inter) feed the same counter.
6096//
6097// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6098// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6099// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6100// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6101// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6102// every SB of the last row), so the 32-level slots stay 0 on that content and
6103// only these prove the arm fired.
6104thread_local! {
6105 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6106 const { std::cell::Cell::new([0; 8]) };
6107}
6108
6109/// Current value of [`EDGE32_HITS`].
6110#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6111pub(crate) fn edge32_hits() -> [usize; 8] {
6112 EDGE32_HITS.with(|c| c.get())
6113}
6114
6115/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6116/// reads are `if`-conditions, so the counter has to ride the expression.
6117fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6118 bump_edge32(base + bit.min(1));
6119 bit
6120}
6121
6122fn bump_edge32(slot: usize) {
6123 hit_do! {
6124 EDGE32_HITS.with(|c| {
6125 let mut h = c.get();
6126 h[slot] += 1;
6127 c.set(h)
6128 });
6129 }
6130}
6131
6132// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6133// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6134// strip) fired. Real aomenc picks these at 64 even with
6135// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6136// the counter the gate hard-asserts.
6137thread_local! {
6138 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6139 const { std::cell::Cell::new([0; 4]) };
6140}
6141
6142/// Current value of [`SB_AB_HITS`], summed over the four arms.
6143#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6144pub(crate) fn sb_ab_hits() -> usize {
6145 SB_AB_HITS.with(|c| c.get().iter().sum())
6146}
6147
6148/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6149/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6150/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6151/// proof of all four.
6152#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6153pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6154 SB_AB_HITS.with(std::cell::Cell::get)
6155}
6156
6157// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6158// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6159// strips). Two counters, not one, because a gate that only proved "some 1:4
6160// strip fired" would pass on a stream that never coded the other axis, and
6161// every scan/context table this round added comes in a transposed pair.
6162thread_local! {
6163 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6164 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6165}
6166
6167/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6168#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6169pub(crate) fn sb_rect4_horz_hits() -> usize {
6170 SB_RECT4_HORZ_HITS.with(|c| c.get())
6171}
6172
6173/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6174#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6175pub(crate) fn sb_rect4_vert_hits() -> usize {
6176 SB_RECT4_VERT_HITS.with(|c| c.get())
6177}
6178
6179// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6180// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6181// strips), the arms the ReelB mid-film extract stops at.
6182thread_local! {
6183 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6184 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6185 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6186 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6187 /// `PARTITION_VERT_4`.
6188 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6189 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6190 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6191 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6192 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6193 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6194 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6195 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6196}
6197
6198// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6199// a gate that only counted strips would pass on an all-skip stream, which
6200// exercises none of the new scan/context tables.
6201thread_local! {
6202 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6203}
6204
6205// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6206// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6207// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6208// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6209// counts the same for a 16x8/8x16 strip below 16x16.
6210thread_local! {
6211 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6212 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6213 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6214}
6215
6216/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6217#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6218pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6219 (
6220 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6221 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6222 )
6223}
6224
6225/// Current value of `SUB16_SPLIT_HITS`.
6226#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6227pub(crate) fn sub16_split_hits() -> usize {
6228 SUB16_SPLIT_HITS.with(|c| c.get())
6229}
6230
6231// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6232// luma transform is SPLIT and which therefore leave through that fn's early
6233// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6234thread_local! {
6235 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6236}
6237
6238/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6239#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6240pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6241 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6242}
6243
6244/// Current value of `RECT4_COEFF_HITS`.
6245pub(crate) fn rect4_coeff_hits() -> usize {
6246 RECT4_COEFF_HITS.with(|c| c.get())
6247}
6248
6249// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6250// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6251// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6252// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6253// asserts the arms it proves separately so a run whose RD only picked one
6254// cannot pass as proof of the others.
6255thread_local! {
6256 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6257}
6258
6259/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6260/// inter frame).
6261pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6262 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6263}
6264
6265// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6266// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6267// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6268// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6269// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6270// arm separately so a run whose RD only picked one cannot pass as proof of
6271// four.
6272thread_local! {
6273 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6274}
6275
6276/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6277/// inter frame).
6278pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6279 AB16_INTER_HITS.with(std::cell::Cell::get)
6280}
6281
6282// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6283// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6284// counts the odd strips that close a 4:2:0 chroma pair
6285// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6286// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6287// the PREVIOUS strip's own mv/ref/filters -- libaom
6288// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6289// through `is_sub8x8_inter` (same file, :54).
6290thread_local! {
6291 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6292 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6293 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6294 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6295}
6296
6297// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6298// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6299// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6300thread_local! {
6301 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6302 const { std::cell::Cell::new([0; 3]) };
6303}
6304
6305/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6306/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6307pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6308 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6309 (v[0], v[1], v[2])
6310}
6311
6312/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6313/// strips, chroma pairs closed, chroma pairs built from two different
6314/// strips' motion vectors)`.
6315pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6316 (
6317 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6318 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6319 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6320 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6321 )
6322}
6323
6324/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6325/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6326/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6327/// that all mean "an ordinary block, chroma of its own".
6328#[derive(Clone, Copy)]
6329pub(crate) struct InterStripChroma {
6330 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6331 /// read and reconstruct NO chroma at all.
6332 has_chroma: bool,
6333 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6334 horz: bool,
6335 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6336 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6337 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6338 pair_mi: (usize, usize),
6339 /// The previous (even) strip's single-reference MC parameters, `None`
6340 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6341 /// and the whole chroma block is predicted from THIS strip's mv.
6342 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6343}
6344
6345/// The single-reference MC parameters of the inter block that decoded
6346/// last -- read by the next 1:4 strip to build its pair's chroma.
6347
6348fn bump_ab16_inter(arm: usize) {
6349 hit_do! {
6350 AB16_INTER_HITS.with(|c| {
6351 let mut v = c.get();
6352 v[arm] += 1;
6353 c.set(v);
6354 });
6355 }
6356}
6357
6358// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6359// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6360// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6361thread_local! {
6362 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6363 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6364 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6365 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6366 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6367 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6368 /// base mi differs from what the strip's own (odd) mi would have said --
6369 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6370 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6371 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6372 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6373 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6374 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6375 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6376 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6377 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6378 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6379 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6380 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6381 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6382 /// block overhanging the frame does NOT code.
6383 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6384 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6385 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6386 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6387 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6388 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6389 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6390 /// hardcoded 4:2:0 span mis-stepped).
6391 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6392 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6393 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6394 /// that replaced the single rect unit).
6395 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6396 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6397 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6398 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6399 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6400 /// units whose libaom-faithful block-relative reach
6401 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6402 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6403 /// no stream reached a rect leaf where the two disagree -- a gate
6404 /// asserting the reach fix must see this nonzero, or the fixture never
6405 /// exercised the fixed path.
6406 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6407}
6408
6409/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6410/// that reconstructed as flat DC before lane-kf1200 r2).
6411pub fn skip_cfl_hits() -> usize {
6412 SKIP_CFL_HITS.with(|c| c.get())
6413}
6414
6415/// How many chroma transform units the frame-edge clip skipped in
6416/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6417/// stream whose lossless blocks never overhang the frame -- a gate asserting
6418/// the clip fired must see this nonzero.
6419pub fn chroma_edge_tu_clip_hits() -> usize {
6420 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6421}
6422
6423/// How many skipped lossless intrabc rect strips had their luma entropy
6424/// bands zeroed per unit (lane-av1-loss64).
6425pub fn skip_lossless_band_reset_hits() -> usize {
6426 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6427}
6428
6429/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6430/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6431/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6432/// must see this nonzero.
6433pub fn rect_split_lossless_chroma444_hits() -> usize {
6434 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6435}
6436
6437/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6438/// per-4x4 inter units (lane-av1-ibc444rect).
6439pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6440 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6441}
6442
6443/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6444/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6445pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6446 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6447}
6448
6449/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6450/// block-relative reach libaom's `has_bottom_left` gives, where the
6451/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6452/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6453pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6454 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6455}
6456
6457/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6458pub fn reset_sub8_chroma444_tu_reach_hits() {
6459 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6460}
6461
6462/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6463pub fn reset_ibc444rect_hits() {
6464 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6465 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6466}
6467
6468/// Gate-side reset for the two lane-av1-loss64 counters above.
6469pub fn reset_loss64_hits() {
6470 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6471 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6472}
6473
6474/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6475/// from the pair's base mi than the strip's own mi would have given.
6476pub fn rect4_16_uv_pair_filt_hits() -> usize {
6477 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6478}
6479
6480/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6481pub fn rect4_16_lossless_chroma_hits() -> usize {
6482 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6483}
6484
6485/// How many 16x4/4x16 strips reconstructed as intra block copy.
6486pub fn rect4_16_intrabc_hits() -> usize {
6487 RECT4_16_INTRABC_HITS.with(|c| c.get())
6488}
6489
6490/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6491pub fn reset_rect4_16_pair_hits() {
6492 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6493 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6494}
6495
6496// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6497// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6498// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6499// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6500// intra-edge filter type must come from the chroma-reference position).
6501thread_local! {
6502 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6503 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6504}
6505
6506/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6507pub fn reelc_chroma_counters() -> (usize, usize) {
6508 (
6509 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6510 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6511 )
6512}
6513
6514/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6515/// strips, chroma-reference strips, strips with a coded residual, strips
6516/// whose luma transform is split)`.
6517pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6518 (
6519 RECT4_16_HORZ_HITS.with(|c| c.get()),
6520 RECT4_16_VERT_HITS.with(|c| c.get()),
6521 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6522 RECT4_16_COEFF_HITS.with(|c| c.get()),
6523 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6524 )
6525}
6526
6527/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6528pub(crate) fn rect4_32_horz_hits() -> usize {
6529 RECT4_32_HORZ_HITS.with(|c| c.get())
6530}
6531
6532/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6533pub(crate) fn rect4_32_vert_hits() -> usize {
6534 RECT4_32_VERT_HITS.with(|c| c.get())
6535}
6536
6537/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6538pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6539 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6540}
6541
6542/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6543pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6544 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6545}
6546
6547/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6548pub(crate) fn inter_sb_horz_hits() -> usize {
6549 INTER_SB_HORZ_HITS.with(|c| c.get())
6550}
6551
6552/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6553pub(crate) fn inter_sb_vert_hits() -> usize {
6554 INTER_SB_VERT_HITS.with(|c| c.get())
6555}
6556
6557/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6558pub(crate) fn inter_sb_horz4_hits() -> usize {
6559 INTER_SB_HORZ4_HITS.with(|c| c.get())
6560}
6561
6562/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6563pub(crate) fn inter_sb_vert4_hits() -> usize {
6564 INTER_SB_VERT4_HITS.with(|c| c.get())
6565}
6566
6567// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6568// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6569// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6570// just inert-compiled. Zero forever on a passing gate means that gate's
6571// stream never carries `delta_q_present=1` through a rect64 block.
6572thread_local! {
6573 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6574 const { std::cell::Cell::new(0) };
6575}
6576
6577/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6578#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6579pub(crate) fn rect64_qidx_drift_hits() -> usize {
6580 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6581}
6582
6583// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6584// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6585// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6586// free-partition gate's proof this round's arms actually fired.
6587thread_local! {
6588 static PARTAB_HITS: std::cell::Cell<usize> =
6589 const { std::cell::Cell::new(0) };
6590}
6591
6592/// Current value of [`PARTAB_HITS`].
6593#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6594pub(crate) fn partab_hits() -> usize {
6595 PARTAB_HITS.with(|c| c.get())
6596}
6597
6598// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6599// one counter per arm rather than one shared total -- the gate hard-asserts
6600// each of these individually nonzero so a recipe that only ever fires
6601// HORZ_A can't silently stand in for the whole set.
6602thread_local! {
6603 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6604 const { std::cell::Cell::new(0) };
6605 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6606 const { std::cell::Cell::new(0) };
6607 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6608 const { std::cell::Cell::new(0) };
6609 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6610 const { std::cell::Cell::new(0) };
6611}
6612
6613/// Current value of [`INTRA_HORZ_A_HITS`].
6614#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6615pub(crate) fn intra_horz_a_hits() -> usize {
6616 INTRA_HORZ_A_HITS.with(|c| c.get())
6617}
6618/// Current value of [`INTRA_HORZ_B_HITS`].
6619#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6620pub(crate) fn intra_horz_b_hits() -> usize {
6621 INTRA_HORZ_B_HITS.with(|c| c.get())
6622}
6623/// Current value of [`INTRA_VERT_A_HITS`].
6624#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6625pub(crate) fn intra_vert_a_hits() -> usize {
6626 INTRA_VERT_A_HITS.with(|c| c.get())
6627}
6628/// Current value of [`INTRA_VERT_B_HITS`].
6629#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6630pub(crate) fn intra_vert_b_hits() -> usize {
6631 INTRA_VERT_B_HITS.with(|c| c.get())
6632}
6633
6634// How many [`read_inter_compound_mode`] reads actually happened
6635// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6636// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6637// mvstack build), not just that `comp_mode` fired. Still refused right
6638// after (no MV assignment or MC wired), so this only counts attempted
6639// reads.
6640thread_local! {
6641 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6642 const { std::cell::Cell::new(0) };
6643}
6644
6645/// Current value of [`COMPOUND_MODE_HITS`].
6646#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6647pub(crate) fn compound_mode_hits() -> usize {
6648 COMPOUND_MODE_HITS.with(|c| c.get())
6649}
6650
6651/// How many query blocks folded in at least one temporal MV candidate
6652/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6653/// temporal-MV gate's own firing counter (lane-av1tmvp).
6654///
6655/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6656/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6657/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6658/// counter compiles and the projection math it counts is unit-tested
6659/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6660/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6661/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6662/// against any real stream today. See the module doc on
6663/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6664#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6665pub(crate) fn tmv_hits() -> usize {
6666 crate::mvstack::tmv_hits()
6667}
6668
6669/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6670/// produced on this thread, the 10-bit inter gate's firing proof.
6671#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6672pub(crate) fn inter_pred_hits() -> usize {
6673 crate::mc::inter_pred_hits()
6674}
6675
6676/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6677/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6678/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6679/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6680/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6681/// needs to turn a query block's own resolved `ref_frame` into
6682/// `TplArgs::cur_offset_0` (spec 7.9.3).
6683pub(crate) struct TplFrameArgs<'a> {
6684 pub field: &'a crate::motion_field::TplField,
6685 pub order_hint_bits: u32,
6686 pub order_hint: u32,
6687 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6688 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6689 /// frame's own `ref_frame_idx` names for each single reference.
6690 pub ref_order_hints: [u32; 7],
6691}
6692
6693/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6694/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6695/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6696/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6697/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6698/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6699/// cell straddles two different blocks' values.
6700#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6701pub(crate) fn build_motion_field(
6702 grid: &MiGrid,
6703 mi_cols: usize,
6704 mi_rows: usize,
6705 order_hint: u32,
6706 order_hint_bits: u32,
6707 ref_order_hints: [u32; 7],
6708 fctx: &FrameCtx,
6709) -> crate::motion_field::MotionField {
6710 let mut field =
6711 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6712 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6713 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6714 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6715 // referencing one stores only its OTHER side's mv. With
6716 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6717 // nothing is skipped.
6718 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6719 // only on the reference frame, so it is 7 table lookups per frame instead
6720 // of two per inter unit.
6721 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6722 let i = rf.wrapping_sub(LAST_FRAME as usize);
6723 order_hint_bits != 0
6724 && i < 7
6725 && (crate::motion_field::get_relative_dist(
6726 order_hint_bits,
6727 ref_order_hints[i],
6728 order_hint,
6729 ) > 0
6730 || ref_order_hints[i] == order_hint)
6731 });
6732 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6733 // capped at 12 bits per component; a longer one is not stored at all.
6734 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6735 let (cols, rows, cells) = field.cells_mut();
6736 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6737 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6738 // `row` writes cell row `row / 2`).
6739 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6740 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6741 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6742 for col in 0..mi_cols {
6743 let Some(info) = grid.get_frame(row, col) else {
6744 continue;
6745 };
6746 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6747 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6748 // so an intra block -- or an inter block whose every slot is on the
6749 // other side / over the limit -- wipes what an earlier block wrote
6750 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6751 // share a cell).
6752 if !info.is_inter {
6753 out[col / 2] = None;
6754 continue;
6755 }
6756 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6757 // qualifying one wins -- a compound block stores its second
6758 // reference's mv, never its first (unless the second is on the
6759 // other side or over the limit). Storing slot 0 unconditionally
6760 // put the wrong (mv, ref_frame_offset) pair in every compound
6761 // block's cell, which a later frame's temporal candidate then
6762 // projected with the wrong reference distance.
6763 let mut saved: Option<crate::motion_field::SavedMv> = None;
6764 for (rf, mv) in [
6765 (info.ref_frame, Some(mv32(info.mv))),
6766 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6767 ] {
6768 let (Some(mv), true) = (mv, rf > 0) else {
6769 continue;
6770 };
6771 if other_side[rf as usize] {
6772 continue;
6773 }
6774 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6775 continue;
6776 }
6777 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6778 }
6779 out[col / 2] = saved;
6780 }
6781 }
6782 };
6783 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6784 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6785 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6786 let bands = crate::par::bands(rows, crate::par::filter_threads());
6787 if bands.len() <= 1 {
6788 fill(0, rows, cells);
6789 } else {
6790 let shared = crate::par::Shared::new(cells);
6791 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6792 // SAFETY: cell rows `r0..r1` are this band's alone.
6793 let cells = unsafe { shared.get() };
6794 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6795 });
6796 }
6797 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6798 eprintln!("EC_TPL_SAVED oh={order_hint}");
6799 for (r, row) in field.occupancy().iter().enumerate() {
6800 eprintln!("EC_TPL_SAVED r{r} {row}");
6801 }
6802 }
6803 field
6804}
6805
6806/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
6807/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
6808#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6809pub(crate) fn ref_hits(ref_frame: i8) -> usize {
6810 let c = match ref_frame {
6811 LAST2_FRAME => &LAST2_HITS,
6812 LAST3_FRAME => &LAST3_HITS,
6813 GOLDEN_FRAME => &GOLDEN_HITS,
6814 BWDREF_FRAME => &BWDREF_HITS,
6815 ALTREF2_FRAME => &ALTREF2_HITS,
6816 ALTREF_FRAME => &ALTREF_HITS,
6817 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
6818 };
6819 c.with(|v| v.get())
6820}
6821
6822/// The sequence header's `enable_intra_edge_filter`, set once per
6823/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
6824/// own read of it, kept off the call stack (see that function's own doc
6825/// comment for why) rather than threaded through every `read_plane`/
6826/// `decode_block`/`decode_leaf8` call between here and there.
6827
6828/// Set [`ENABLE_EDGE_FILTER`] for this thread.
6829///
6830/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
6831/// never did -- so an inter frame's intra blocks read whatever value the last
6832/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
6833/// harmless (its own key frame sets it first), but a caller that decodes an
6834/// inter frame directly, or a test harness running several streams on one
6835/// thread, inherits a foreign sequence's bit: decode stops being a pure
6836/// function of the bitstream. `decode_stream` now calls this once per stream
6837/// from the sequence header, which covers every frame including inter ones.
6838pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
6839 fctx.enable_edge_filter.with(|f| f.set(value));
6840}
6841
6842/// Current value of [`ANGLE_DELTA_HITS`].
6843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6844pub(crate) fn angle_delta_hits() -> usize {
6845 ANGLE_DELTA_HITS.with(|c| c.get())
6846}
6847
6848/// Current value of [`TX_CLASS1_HITS`].
6849#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6850pub(crate) fn tx_class1_hits() -> usize {
6851 TX_CLASS1_HITS.with(|c| c.get())
6852}
6853
6854// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
6855// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
6856// bottom) this thread's decode actually reconstructed -- the same
6857// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
6858// genuinely exercised the sub-8x8 leaf path rather than every attempt
6859// coincidentally landing on `PARTITION_NONE`.
6860thread_local! {
6861 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6862 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
6863 /// sub-blocks (lane-intersub8).
6864 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6865 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
6866 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
6867 /// `[1] = VERT` (two BLOCK_4X8).
6868 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
6869 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
6870 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
6871 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
6872 /// MIXED groups whose chroma reference is INTER while its sibling is
6873 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
6874 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
6875 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
6876 /// so only this cell separates the split arm from the HORZ/VERT one).
6877 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
6878}
6879
6880/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
6881/// mixed groups, split 4x4 leaves)`.
6882pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
6883 SUB8_INTRA_RECT_HITS.with(|c| {
6884 let h = c.get();
6885 (h[0], h[1], h[2], h[3], h[4])
6886 })
6887}
6888
6889/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
6890pub fn sub8_inter_rect_hits() -> (usize, usize) {
6891 SUB8_INTER_RECT_HITS.with(|c| {
6892 let h = c.get();
6893 (h[0], h[1])
6894 })
6895}
6896
6897// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
6898// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
6899// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
6900// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
6901// (b) was 0 for every stream before this round -- the leaf path never touched
6902// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
6903// filtered where libaom skips it. A gate asserts both are non-zero.
6904thread_local! {
6905 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6906 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6907 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
6908 // crosses the cropped frame edge -- the only units for which "clamp at
6909 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
6910 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
6911 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
6912 // whose width or height is not a multiple of 8 is the only shape that
6913 // produces one; the straddling-band gate arms assert it grew.
6914 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6915 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
6916 // (see `Neighbours::skip_written`).
6917 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6918 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
6919 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
6920 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
6921 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
6922 // 8-tall strip pair where only one half is skip must still be FILTERED.
6923 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6924 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6925}
6926
6927/// Current value of `RECT_SKIP_BAND_HITS`.
6928pub fn rect_skip_band_hits() -> usize {
6929 RECT_SKIP_BAND_HITS.with(|c| c.get())
6930}
6931
6932/// Current value of `CDEF_MIXED_SKIP_UNITS`.
6933pub fn cdef_mixed_skip_units() -> usize {
6934 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
6935}
6936
6937/// Current value of `CDEF_SKIPPED_UNITS`.
6938#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6939pub(crate) fn cdef_skipped_units() -> usize {
6940 CDEF_SKIPPED_UNITS.with(|c| c.get())
6941}
6942
6943/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
6944/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
6945pub fn cdef_unwritten_skip_units() -> usize {
6946 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
6947}
6948
6949/// Current value of `INTER8_SKIP_BAND_HITS`.
6950#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6951pub(crate) fn inter8_skip_band_hits() -> usize {
6952 INTER8_SKIP_BAND_HITS.with(|c| c.get())
6953}
6954
6955/// Current value of `CDEF_STRADDLE_UNITS`.
6956#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6957pub(crate) fn cdef_straddle_units() -> usize {
6958 CDEF_STRADDLE_UNITS.with(|c| c.get())
6959}
6960
6961/// Current value of [`SUB8_SPLIT_HITS`].
6962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6963pub(crate) fn sub8_split_hits() -> usize {
6964 SUB8_SPLIT_HITS.with(|c| c.get())
6965}
6966
6967/// Current value of [`SUB8_INTER_SPLIT_HITS`].
6968pub fn sub8_inter_split_hits() -> usize {
6969 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
6970}
6971
6972// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
6973// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
6974// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
6975// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
6976// first sub-block's type is never the one). Reading it off sub-block 0
6977// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
6978// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
6979// see this rule through this counter.
6980thread_local! {
6981 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6982}
6983
6984/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
6985pub fn sub8_chroma_tx_from_ref_hits() -> usize {
6986 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
6987}
6988
6989fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
6990 if coeffs && first_sub != chroma_ref {
6991 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
6992 }
6993}
6994
6995// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
6996// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
6997// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
6998// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
6999// asserts on these two rather than a plain leaf count.
7000thread_local! {
7001 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7002 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7003 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
7004 /// two 4x4 transform units, predicted one after the other. A separate
7005 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
7006 /// the gate can prove THIS path fired.
7007 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7008 /// 16x8/8x16 intra strips whose prediction actually read past the block's
7009 /// own width (above-right) or height (below-left) -- the samples
7010 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
7011 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
7012 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7013 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
7014 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
7015 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7016}
7017
7018/// Current value of [`RECT8_SPLIT_TX_HITS`].
7019#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7020pub(crate) fn rect8_split_tx_hits() -> usize {
7021 RECT8_SPLIT_TX_HITS.with(|c| c.get())
7022}
7023
7024/// Current value of [`RECT_STRIP_PRED_HITS`].
7025#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7026pub(crate) fn rect_strip_pred_hits() -> usize {
7027 RECT_STRIP_PRED_HITS.with(|c| c.get())
7028}
7029
7030/// Current value of [`RECT_STRIP_REACH_HITS`].
7031#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7032pub(crate) fn rect_strip_reach_hits() -> usize {
7033 RECT_STRIP_REACH_HITS.with(|c| c.get())
7034}
7035
7036/// Current value of [`TX4X8_CODED_HITS`].
7037#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7038pub(crate) fn tx4x8_coded_hits() -> usize {
7039 TX4X8_CODED_HITS.with(|c| c.get())
7040}
7041
7042/// Current value of [`TX8X4_CODED_HITS`].
7043#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7044pub(crate) fn tx8x4_coded_hits() -> usize {
7045 TX8X4_CODED_HITS.with(|c| c.get())
7046}
7047
7048// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
7049// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
7050// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
7051// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
7052// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
7053// (`eob_pt_{16,64,128,256}_chroma_class1`).
7054thread_local! {
7055 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
7056 const { std::cell::Cell::new(0) };
7057}
7058
7059/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
7060#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7061pub(crate) fn chroma_eob_class1_hits() -> usize {
7062 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
7063}
7064
7065/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
7066/// `tx_type` put this block's `eob_pt` on the class-1 row.
7067fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
7068 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
7069 hit!(CHROMA_EOB_CLASS1_HITS);
7070 }
7071}
7072
7073// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
7074// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
7075// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
7076// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
7077// looked identical to a same-plane disagreement. Set by `exec_intra` (the
7078// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
7079// by the `EC_PRED` rung, so it cannot change a decode.
7080thread_local! {
7081 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7082}
7083
7084/// The plane index the `EC_PRED` rung prints as `plane=`.
7085fn recon_plane() -> usize {
7086 RECON_PLANE.with(std::cell::Cell::get)
7087}
7088
7089/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
7090/// either of its two early returns.
7091struct PlaneGuard(usize);
7092impl Drop for PlaneGuard {
7093 fn drop(&mut self) {
7094 RECON_PLANE.with(|c| c.set(self.0));
7095 }
7096}
7097
7098const SUB_MI: u32 = 4;
7099const MI: usize = 4;
7100const SB: usize = 64;
7101/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
7102/// (tile start, superblock-row start).
7103///
7104/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
7105/// `av1_get_partition_plane_context` reads its own zero-initialised
7106/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
7107/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
7108/// (64), which reads identically at every level up to 64x64 but sets the bit
7109/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
7110/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
7111/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
7112const NO_NEIGHBOUR_SIDE: usize = 128;
7113const BLOCK: usize = 32;
7114const SUB: usize = 16;
7115const TX32: usize = 32;
7116const TX16: usize = 16;
7117const TX8: usize = 8;
7118const TX4: usize = 4;
7119const DC_PRED: usize = 0;
7120/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7121/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7122/// constant.
7123const V_PRED: usize = 1;
7124const H_PRED: usize = 2;
7125/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7126/// `Fimode_To_Intradir`, libaom `blockd.h`).
7127const D157_PRED: usize = 6;
7128/// The last directional mode, `D67_PRED`.
7129const D67_PRED: usize = 8;
7130/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7131/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7132/// codes anything else, so this decoder never reads anything else either.
7133const ANGLE_DELTA_ZERO: usize = 3;
7134const NUM_BASE_LEVELS: i32 = 2;
7135const COEFF_BASE_RANGE: i32 = 12;
7136const BR_STEP: i32 = 3;
7137const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7138
7139/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7140/// whose probability mass a superblock or block half outside the frame
7141/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7142/// duplicated here (that module is another lane's territory this round) and
7143/// kept in step with it by the byte-exact round-trip tests below rather than
7144/// by sharing code.
7145const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7146const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7147
7148fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7149 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7150 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7151 }
7152}
7153
7154fn element_prob(cdf: &[u16], element: usize) -> u16 {
7155 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7156}
7157
7158/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7159/// with: the mass of `elements` becomes the probability of the one partition
7160/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7161/// (the encoder's non-adapting counterpart to this read).
7162fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7163 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7164 [32768 - split, 32768, 0]
7165}
7166
7167fn unsupported(what: impl Into<String>) -> Error {
7168 Error::unsupported("AV1 tile", what.into())
7169}
7170
7171/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7172/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7173/// same rule.
7174pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7175 match base_q_idx {
7176 0..=20 => 0,
7177 21..=60 => 1,
7178 61..=120 => 2,
7179 _ => 3,
7180 }
7181}
7182
7183/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7184/// [`crate::tile`]'s writer generates its scan tables with.
7185fn default_scan(side: usize) -> &'static [u16] {
7186 // One table per transform side (4/8/16/32), built once: this used to be a
7187 // fresh heap allocation plus the whole anti-diagonal walk on every
7188 // transform block read.
7189 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7190 [
7191 default_scan_gen(4),
7192 default_scan_gen(8),
7193 default_scan_gen(16),
7194 default_scan_gen(32),
7195 ]
7196 });
7197 assert!(
7198 matches!(side, 4 | 8 | 16 | 32),
7199 "no default scan for a {side}-point transform"
7200 );
7201 &SCANS[side.trailing_zeros() as usize - 2]
7202}
7203
7204fn default_scan_gen(side: usize) -> Vec<u16> {
7205 let mut scan = Vec::with_capacity(side * side);
7206 for d in 0..(2 * side - 1) {
7207 let lo = d.saturating_sub(side - 1);
7208 let hi = d.min(side - 1);
7209 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7210 if d % 2 == 0 {
7211 scan.extend(diagonal.rev());
7212 } else {
7213 scan.extend(diagonal);
7214 }
7215 }
7216 scan
7217}
7218
7219/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7220/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7221/// in, instead of the default zigzag. libaom's own tables are keyed by a
7222/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7223/// physically column-major level buffer, but they decompose to the exact
7224/// same (row, col) walk as a flat row-major traversal of *our* row-major
7225/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7226/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7227/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7228/// transposed (column 0 down every row, then column 1, ...).
7229pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7230 class_scan_table_wh(side, side, class)
7231}
7232
7233/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7234/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7235/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7236/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7237/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7238/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7239fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7240 match class {
7241 TxClass::Vert => (0..(w * h) as u16).collect(),
7242 TxClass::Horiz => (0..w)
7243 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7244 .collect(),
7245 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7246 }
7247}
7248
7249fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7250 match scan_idx {
7251 0 => 0,
7252 i if i <= area / 8 => 1,
7253 i if i <= area / 4 => 2,
7254 _ => 3,
7255 }
7256}
7257
7258/// One cell of [`read_coeffs`]'s level buffer.
7259///
7260/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7261/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7262/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7263/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7264/// zero cells instead of needing the `row >= side || col >= side` edge test
7265/// this used to run five times per coefficient. Nothing writes a padding
7266/// cell, so the values are the same zeros the test returned.
7267#[inline]
7268fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7269 grid[row * stride + col] as i32
7270}
7271
7272/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7273/// `txb_common.h`): everything but the two lone-axis-identity types this
7274/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7275#[derive(Clone, Copy, PartialEq, Eq)]
7276pub(crate) enum TxClass {
7277 TwoD,
7278 Horiz,
7279 Vert,
7280}
7281
7282impl TxClass {
7283 pub(crate) fn of(tx_type: TxType) -> Self {
7284 match tx_type {
7285 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7286 // key on axis alone -- FLIPADST is still ADST for this purpose.
7287 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7288 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7289 _ => Self::TwoD,
7290 }
7291 }
7292}
7293
7294/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7295/// table (indexed by the position along the transform's *coded* axis --
7296/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7297/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7298/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7299pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7300 match i {
7301 0 => 26,
7302 1 => 31,
7303 _ => 36,
7304 }
7305}
7306
7307fn base_ctx(
7308 grid: &[u8],
7309 stride: usize,
7310 row: usize,
7311 col: usize,
7312 class: TxClass,
7313 rect_shape: Option<(usize, usize)>,
7314) -> usize {
7315 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7316 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7317 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7318 // position through the full 1D neighbour sum and offset table. Skipping
7319 // that for every class desynced the last (DC) coefficient of a
7320 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7321 // 0, which then read one extra `BR` symbol at the max and forced a
7322 // spurious third Golomb call).
7323 if class == TxClass::TwoD && row == 0 && col == 0 {
7324 return 0;
7325 }
7326 let offsets: [(usize, usize); 5] = match class {
7327 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7328 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7329 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7330 };
7331 let mag: i32 = offsets
7332 .iter()
7333 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7334 .sum();
7335 let ctx = ((mag + 1) >> 1).min(4) as usize;
7336 match class {
7337 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7338 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7339 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7340 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7341 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7342 // strip, which own a genuinely different table from the square one
7343 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7344 // square table vs the real ctx 13 the rect table gives).
7345 TxClass::TwoD => {
7346 // lane-rectsplit r4: apply libaom's GENERATING RULE
7347 // (`txb_common.h:199-209`) directly instead of indexing the
7348 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7349 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7350 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7351 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7352 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7353 // transcriptions are `[col][row]` and this read had them as
7354 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7355 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7356 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7357 // pins the rule against the tables over their whole 5x5 domain.
7358 if let Some((w, h)) = rect_shape {
7359 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7360 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7361 }
7362 if w < h && row < 2 {
7363 return ctx + 11;
7364 }
7365 if w > h && col < 2 {
7366 return ctx + 16;
7367 }
7368 }
7369 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7370 }
7371 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7372 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7373 }
7374}
7375
7376/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7377/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7378/// function of the tx class alone, which is fixed for a whole transform unit,
7379/// so resolving it once per unit takes the class match and the `(dr, dc)`
7380/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7381/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7382/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7383/// original `(dr, dc)` form.
7384fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7385 match class {
7386 TxClass::TwoD => (
7387 [stride, 1, stride + 1, 2 * stride, 2],
7388 [stride, 1, stride + 1],
7389 ),
7390 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7391 TxClass::Vert => (
7392 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7393 [stride, 1, 2 * stride],
7394 ),
7395 }
7396}
7397
7398/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7399/// neighbours) + 1) >> 1`, clamped to 4.
7400#[inline(always)]
7401fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7402 let mut mag = 0u32;
7403 for &t in taps {
7404 mag += u32::from(grid[idx + t]).min(3);
7405 }
7406 (((mag + 1) >> 1) as usize).min(4)
7407}
7408
7409/// [`br_ctx`]'s neighbour sum, off flat taps.
7410#[inline(always)]
7411fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7412 let mut mag = 0u32;
7413 for &t in taps {
7414 mag += u32::from(grid[idx + t]);
7415 }
7416 (((mag + 1) >> 1) as usize).min(6)
7417}
7418
7419/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7420/// origin-offset tail the two coefficient readers state inline; kept as the
7421/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7422/// flat one against.
7423#[cfg(test)]
7424fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7425 let extra = match class {
7426 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7427 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7428 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7429 };
7430 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7431 let mag = (((mag + 1) >> 1).min(6)) as usize;
7432 if row == 0 && col == 0 {
7433 return mag;
7434 }
7435 let near_origin = match class {
7436 TxClass::TwoD => row < 2 && col < 2,
7437 TxClass::Horiz => col == 0,
7438 TxClass::Vert => row == 0,
7439 };
7440 if near_origin { mag + 7 } else { mag + 14 }
7441}
7442
7443/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7444/// transposed from libaom's column-major buffer into this decoder's row-major
7445/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7446/// against the real table). Not the square zigzag formula generalized to
7447/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7448const SCAN_32X16: [u16; 512] = [
7449 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7450 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7451 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7452 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7453 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7454 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7455 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7456 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7457 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7458 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7459 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7460 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7461 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7462 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7463 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7464 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7465 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7466 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7467 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7468 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7469 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7470 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7471 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7472 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7473 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7474 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7475 510, 479, 511,
7476];
7477
7478/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7479/// [`SCAN_32X16`]'s doc comment).
7480const SCAN_16X32: [u16; 512] = [
7481 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,
7482 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7483 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7484 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7485 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7486 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7487 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7488 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7489 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7490 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7491 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7492 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7493 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7494 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7495 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7496 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7497 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7498 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7499 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7500 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7501 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7502 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7503 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7504 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7505 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7506 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7507];
7508
7509/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7510/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7511/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7512/// the same source).
7513const SCAN_4X8: [u16; 32] = [
7514 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,
7515 23, 26, 29, 27, 30, 31,
7516];
7517
7518/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7519const SCAN_8X4: [u16; 32] = [
7520 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,
7521 29, 22, 15, 30, 23, 31,
7522];
7523
7524/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7525/// [`SCAN_32X16`]'s doc comment).
7526const SCAN_16X8: [u16; 128] = [
7527 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,
7528 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7529 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7530 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7531 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7532 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7533];
7534
7535/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7536/// [`SCAN_32X16`]'s doc comment).
7537const SCAN_8X16: [u16; 128] = [
7538 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,
7539 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7540 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7541 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7542 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7543 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7544];
7545
7546/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7547/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7548/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7549/// scans column-major (`p = col * height + row`), so a naive copy of
7550/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7551/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7552/// are byte-identical to this decoder's [`SCAN_8X16`].
7553const SCAN_32X8: [u16; 256] = [
7554 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7555 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7556 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7557 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7558 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7559 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7560 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7561 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7562 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7563 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7564 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7565 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7566 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7567];
7568/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7569/// 16x64 `PARTITION_VERT_4` strip).
7570const SCAN_8X32: [u16; 256] = [
7571 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,
7572 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7573 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7574 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7575 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7576 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7577 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7578 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7579 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7580 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7581 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7582 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7583 239, 246, 253, 247, 254, 255,
7584];
7585/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7586/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7587/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7588/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7589/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7590/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7591/// were emitted -- a naive copy installs the transpose (class
7592/// reference-layout-not-spec).
7593const SCAN_16X4: [u16; 64] = [
7594 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,
7595 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7596 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7597];
7598/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7599/// 8x32 `PARTITION_VERT_4` strip).
7600const SCAN_4X16: [u16; 64] = [
7601 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,
7602 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7603 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7604];
7605
7606/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7607/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7608/// padding already holds.
7609#[inline]
7610fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7611 grid[row * stride + col] as i32
7612}
7613
7614/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7615/// the rect generalization is libaom's own comment in
7616/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7617/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7618/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7619/// [`decode_block_rect`] codes (see that function's own doc comment).
7620fn base_ctx_rect(
7621 grid: &[u8],
7622 stride: usize,
7623 w: usize,
7624 h: usize,
7625 row: usize,
7626 col: usize,
7627 class: TxClass,
7628) -> usize {
7629 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7630 // the 2D class short-circuits the DC position.
7631 if class == TxClass::TwoD && row == 0 && col == 0 {
7632 return 0;
7633 }
7634 let offsets: [(usize, usize); 5] = match class {
7635 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7636 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7637 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7638 };
7639 let mag: i32 = offsets
7640 .iter()
7641 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7642 .sum();
7643 let ctx = ((mag + 1) >> 1).min(4) as usize;
7644 match class {
7645 TxClass::TwoD => {
7646 if w < h && row < 2 {
7647 return ctx + 11;
7648 }
7649 if w > h && col < 2 {
7650 return ctx + 16;
7651 }
7652 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7653 }
7654 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7655 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7656 // position along one axis only).
7657 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7658 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7659 }
7660}
7661
7662/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7663/// neighbour-offset math itself is shape-independent, only the boundary
7664/// clamp needs the real bound in each axis.
7665/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7666/// its body was character-for-character [`br_ctx`]'s, which
7667/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7668#[cfg(test)]
7669fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7670 let extra = match class {
7671 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7672 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7673 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7674 };
7675 let mag = neighbour_rect(grid, stride, row + 1, col)
7676 + neighbour_rect(grid, stride, row, col + 1)
7677 + extra;
7678 let mag = (((mag + 1) >> 1).min(6)) as usize;
7679 if row == 0 && col == 0 {
7680 return mag;
7681 }
7682 let near_origin = match class {
7683 TxClass::TwoD => row < 2 && col < 2,
7684 TxClass::Horiz => col == 0,
7685 TxClass::Vert => row == 0,
7686 };
7687 if near_origin { mag + 7 } else { mag + 14 }
7688}
7689
7690fn dc_vote(dc: Option<bool>) -> i32 {
7691 match dc {
7692 None => 0,
7693 Some(true) => -1,
7694 Some(false) => 1,
7695 }
7696}
7697
7698fn dc_sign_ctx(vote: i32) -> usize {
7699 match vote.signum() {
7700 0 => 0,
7701 -1 => 1,
7702 _ => 2,
7703 }
7704}
7705
7706/// The `tx_type` a CDF symbol names, given the width of the row it was read
7707/// from.
7708///
7709/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7710/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7711/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7712/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7713/// members are a prefix of the five.
7714///
7715/// One function rather than a `match` at each reader, so
7716/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7717/// tests the mapping the readers actually use.
7718pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7719 match cdf_len {
7720 17 => TxType::from_symbol_all16(t),
7721 13 => TxType::from_symbol_set2_12(t),
7722 8 => TxType::from_symbol_set1(t),
7723 _ => TxType::from_symbol(t),
7724 }
7725}
7726
7727/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7728/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7729/// (class `table-and-reader-move-together` -- the writer picks its symbol
7730/// through the reader's own map, so the two cannot drift).
7731pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7732 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7733}
7734
7735/// The remainder of a level the base and base-range syntax could not reach
7736/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7737/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7738pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7739 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7740 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7741 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7742 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7743 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7744 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7745 // stream_can_carry` enumerates that whole value domain.
7746 //
7747 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7748 // earlier desync (class `refusal-hides-a-defect`), and every historical
7749 // instance was closed by fixing that desync -- lane-dgolomb's
7750 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7751 // Raising the cap only trades a clean refusal for silent corruption:
7752 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7753 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7754 // from a refusal into a frame-0 LUMA MISMATCH.
7755 let mut length = 1u32;
7756 while dec.literal(1) == 0 {
7757 length += 1;
7758 if length > 20 {
7759 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7760 }
7761 }
7762 let mut x = 1u32;
7763 for _ in 1..length {
7764 x = (x << 1) | dec.literal(1);
7765 }
7766 Ok(x - 1)
7767}
7768
7769/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7770/// [`crate::tile`]'s `write_eob`.
7771fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7772 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7773 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7774
7775 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7776 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7777 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7778 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7779 // `eob_multi_ctx`). Missing that split desynced the very first
7780 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7781 // against a real aomdec trace).
7782 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7783 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7784 (_, Some(class1)) => class1,
7785 };
7786 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7787 let (range, value) = dec.debug_state();
7788 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7789 }
7790 let group = dec.symbol(eob_pt) + 1;
7791 if trace {
7792 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7793 }
7794 let bits = OFFSET_BITS[group];
7795 let mut offset = 0u32;
7796 if bits > 0 {
7797 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7798 if trace {
7799 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
7800 }
7801 offset = top << (bits - 1);
7802 if bits > 1 {
7803 offset |= dec.literal(bits - 1);
7804 }
7805 }
7806 GROUP_START[group] + offset as usize
7807}
7808
7809/// One transform block's levels, the inverse of [`crate::tile`]'s
7810/// `write_coeffs`, returned as a `side * side` grid in raster order, along
7811/// with the transform type that grid was coded under (`DCT_DCT` when the
7812/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
7813/// 64-point transforms, which never code anything else).
7814///
7815/// # Errors
7816/// Returns an error if the `tx_type` symbol decodes to a value outside its
7817/// CDF's own set (a corrupt or unsupported bitstream) — every value the
7818/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
7819/// produce dispatches to a real inverse transform.
7820/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
7821/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
7822/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
7823/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
7824/// the plane's own predicted mode instead. Every entry this table can
7825/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
7826/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
7827/// table ever names), so unlike the CDF-coded luma path there is no
7828/// ext-tx-set membership check to fall back from here.
7829pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
7830 use crate::intra::{
7831 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
7832 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
7833 };
7834 match mode {
7835 DC_PRED | D45_PRED => TxType::DctDct,
7836 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
7837 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
7838 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
7839 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
7840 }
7841}
7842
7843/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
7844/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
7845/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
7846fn is_smooth_mode(mode: usize) -> bool {
7847 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
7848}
7849
7850/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
7851/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7852/// nine of them inside the base/sign loops pinned nine sets of values in the
7853/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
7854/// traffic). Out of line, the loop keeps its values in registers and the
7855/// trace output is character-for-character what it was.
7856#[cold]
7857#[inline(never)]
7858fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7859 eprintln!(
7860 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
7861 );
7862}
7863
7864#[cold]
7865#[inline(never)]
7866fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7867 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
7868}
7869
7870#[cold]
7871#[inline(never)]
7872fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
7873 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
7874}
7875
7876#[cold]
7877#[inline(never)]
7878fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
7879 let (rng, _) = dec.debug_state();
7880 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
7881}
7882
7883#[cold]
7884#[inline(never)]
7885fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
7886 let (rng, _) = dec.debug_state();
7887 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
7888}
7889
7890#[cold]
7891#[inline(never)]
7892fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
7893 let (rng, _) = dec.debug_state();
7894 eprintln!(
7895 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
7896 negative as i32
7897 );
7898}
7899
7900#[cold]
7901#[inline(never)]
7902fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
7903 let (rng, _) = dec.debug_state();
7904 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
7905}
7906
7907#[cold]
7908#[inline(never)]
7909fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
7910 let (rng, _) = dec.debug_state();
7911 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
7912}
7913
7914// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
7915#[track_caller]
7916fn read_coeffs(
7917 dec: &mut SymbolDecoder,
7918 coding: &mut TxbTables,
7919 scan: &[u16],
7920 skip_ctx: usize,
7921 sign_ctx: usize,
7922 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
7923 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
7924 // nothing at all; `DctDct` for every luma call and every chroma call at
7925 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
7926 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
7927 default_tx_type: TxType,
7928 // `Some((w, h))` with `w != h` when this read is a superblock-level
7929 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
7930 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
7931 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
7932 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
7933 // caller's block genuinely is `side` x `side`.
7934 rect_shape: Option<(usize, usize)>,
7935) -> Result<(Grid, TxType)> {
7936 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7937 let side = coding.side;
7938 // lane-av1readcensus: this unit's own entry state, so the census line
7939 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
7940 // (which prints `r->ec.rng` before the same `txb_skip` read).
7941 let census_entry_rng = dec.debug_state().0;
7942 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
7943 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7944 let (range, value) = dec.debug_state();
7945 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
7946 }
7947 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
7948 let (range, value) = dec.debug_state();
7949 let bit = dec.debug_bitpos();
7950 eprintln!(
7951 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
7952 );
7953 }
7954 let dbg_txbskip = if coeff_trace_on() {
7955 coding.txb_skip[skip_ctx]
7956 } else {
7957 [0; 3]
7958 };
7959 let sq_bit = if coeff_trace_on() {
7960 dec.debug_bitpos()
7961 } else {
7962 0
7963 };
7964 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7965 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
7966 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
7967 // filter on it before pairing anything against the oracle.
7968 if crate::envflags::env_flag!("EC_IBCTX") {
7969 eprintln!(
7970 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
7971 coding.side,
7972 std::panic::Location::caller(),
7973 );
7974 }
7975 if coeff_trace_on() {
7976 let (rng, _) = dec.debug_state();
7977 eprintln!(
7978 "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={}",
7979 coding.side,
7980 all_zero as i32,
7981 dec.debug_bitpos()
7982 );
7983 }
7984 if crate::envflags::env_flag!("EC_AV1_TELL") {
7985 eprintln!(
7986 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
7987 all_zero as u8,
7988 dec.debug_bitpos(),
7989 dec.debug_state().0
7990 );
7991 }
7992 if trace {
7993 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
7994 }
7995 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7996 let (range, value) = dec.debug_state();
7997 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
7998 }
7999 if all_zero {
8000 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
8001 // shared zero grid instead of allocating and zeroing its own.
8002 census_unit(
8003 census_w,
8004 census_h,
8005 TxType::DctDct,
8006 0,
8007 true,
8008 census_entry_rng,
8009 dec,
8010 );
8011 return Ok((Grid::Zero(side * side), TxType::DctDct));
8012 }
8013 let mut grid = vec![0i32; side * side];
8014 let mut tx_type = default_tx_type;
8015 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8016 // The CDF row's own width names its set (lane-cdffwd2: extended
8017 // past the original two-way intra split once wider `reduced_tx_set
8018 // == 0` inter sets joined the table): 17 slots (16 symbols) is
8019 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
8020 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
8021 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
8022 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
8023 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
8024 let len = tx_type_cdf.len();
8025 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
8026 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
8027 }
8028 let t = dec.symbol(tx_type_cdf);
8029 crate::census::tx_type(len, t);
8030 if coeff_trace_on() {
8031 let (rng, _) = dec.debug_state();
8032 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
8033 }
8034 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8035 let (range, value) = dec.debug_state();
8036 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
8037 }
8038 if trace {
8039 eprintln!("TRACE tx_type value={t} len={len}");
8040 }
8041 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8042 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8043 })?;
8044 }
8045
8046 let class = TxClass::of(tx_type);
8047 if class != TxClass::TwoD {
8048 hit!(TX_CLASS1_HITS);
8049 hit!(RECT_CLASS1_HITS);
8050 }
8051 let eob = read_eob(dec, coding, class);
8052 if trace {
8053 eprintln!("TRACE eob value={eob}");
8054 }
8055 let ec_trace_coeff = coeff_trace_on();
8056 if ec_trace_coeff {
8057 let (rng, _) = dec.debug_state();
8058 let cls = match class {
8059 TxClass::TwoD => "2d",
8060 TxClass::Horiz => "horiz",
8061 TxClass::Vert => "vert",
8062 };
8063 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
8064 }
8065 let class_scan;
8066 let scan: &[u16] = if class == TxClass::TwoD {
8067 scan
8068 } else {
8069 class_scan = class_scan_table(side, class);
8070 &class_scan
8071 };
8072 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
8073 // coefficient `pos / side`, `pos % side` was a hardware divide where a
8074 // shift and a mask say the same thing, and the level buffer fits a fixed
8075 // 32x32 frame of stack instead of a heap allocation per transform block.
8076 debug_assert!(side.is_power_of_two() && side <= 32);
8077 let sh = side.trailing_zeros();
8078 let col_mask = side - 1;
8079 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
8080 // `stride = side + 4` columns and four spare rows, so the widest read
8081 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
8082 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
8083 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
8084 let stride = side + 4;
8085 let mut levels_buf = [0u8; 36 * 36];
8086 let levels = &mut levels_buf[..stride * stride];
8087 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
8088 // `pos >> sh` / `& mask` decomposition and load the level back out of the
8089 // padded frame just to skip the zeros. The base pass already knows both,
8090 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
8091 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
8092 // pass walks that list in reverse (the base pass runs in reverse scan
8093 // order, so reversing it is forward scan order: the same coefficients, in
8094 // the same order, with the same `c` the trace prints).
8095 let mut nz_buf = [0u16; 1024];
8096 let mut nz_n = 0usize;
8097 let (base_taps, br_taps) = flat_taps(stride, class);
8098 for scan_idx in (0..eob).rev() {
8099 let pos = scan[scan_idx] as usize;
8100 let (row, col) = (pos >> sh, pos & col_mask);
8101 let idx = row * stride + col;
8102 let level = if scan_idx == eob - 1 {
8103 let ctx = eob_coeff_ctx(scan_idx, side * side);
8104 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8105 if trace {
8106 trace_base_eob(scan_idx, pos, row, col, ctx, v);
8107 }
8108 v
8109 } else {
8110 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
8111 if row == 0 && col == 0 {
8112 0
8113 } else {
8114 base_mag(levels, idx, &base_taps)
8115 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8116 }
8117 } else {
8118 base_ctx(levels, stride, row, col, class, rect_shape)
8119 };
8120 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8121 if ec_trace_coeff {
8122 // `pos` in libaom's column-major `coeff_idx` convention, so
8123 // the ladder lines up with instrumented `aomdec`.
8124 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
8125 }
8126 if trace {
8127 trace_base(scan_idx, pos, row, col, ctx, v);
8128 }
8129 v
8130 };
8131 let level = if level > NUM_BASE_LEVELS {
8132 let ctx = {
8133 let mag = br_mag(levels, idx, &br_taps);
8134 if row == 0 && col == 0 {
8135 mag
8136 } else {
8137 let near_origin = match class {
8138 TxClass::TwoD => row < 2 && col < 2,
8139 TxClass::Horiz => col == 0,
8140 TxClass::Vert => row == 0,
8141 };
8142 if near_origin { mag + 7 } else { mag + 14 }
8143 }
8144 };
8145 let mut level = level;
8146 let mut sent = 0;
8147 loop {
8148 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8149 if ec_trace_coeff {
8150 // lane-leaf8tx r3: the `br` rung was missing from THIS
8151 // path's trace, so the cross-decoder range ladder was
8152 // blind to every base-range symbol and mis-reported the
8153 // first divergence (class [[gate-blind-to-feature]]).
8154 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8155 }
8156 if trace {
8157 trace_br(scan_idx, pos, row, col, ctx, k);
8158 }
8159 level += k;
8160 sent += BR_STEP;
8161 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8162 break;
8163 }
8164 }
8165 level
8166 } else {
8167 level
8168 };
8169 if ec_trace_coeff && scan_idx == eob - 1 {
8170 coeff_step_base_eob_level(dec, level);
8171 }
8172 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8173 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8174 // added in the sign pass below, straight into `grid`), so the context
8175 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8176 // byte gather (lane-coefbuf).
8177 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8178 levels[idx] = level as u8;
8179 if level != 0 {
8180 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8181 nz_n += 1;
8182 }
8183 }
8184 if ec_trace_coeff {
8185 let (rng, _) = dec.debug_state();
8186 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8187 }
8188
8189 for &packed in nz_buf[..nz_n].iter().rev() {
8190 let c = (packed >> 4) as usize;
8191 let pos = scan[c] as usize;
8192 let level = (packed & 15) as i32;
8193 let negative = if pos == 0 {
8194 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8195 if trace {
8196 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8197 }
8198 v
8199 } else {
8200 dec.literal(1) == 1
8201 };
8202 if ec_trace_coeff {
8203 coeff_step_sign(dec, c, negative);
8204 }
8205 let level = if level > MAX_BR_LEVEL {
8206 let g = read_golomb(dec)?;
8207 if trace {
8208 eprintln!("TRACE golomb pos={pos} value={g}");
8209 }
8210 level + g as i32
8211 } else {
8212 level
8213 };
8214 if ec_trace_coeff {
8215 coeff_step_post_golomb(dec, c, level);
8216 }
8217 grid[pos] = if negative { -level } else { level };
8218 }
8219 census_unit(
8220 census_w,
8221 census_h,
8222 tx_type,
8223 eob,
8224 false,
8225 census_entry_rng,
8226 dec,
8227 );
8228 Ok((Grid::Own(grid), tx_type))
8229}
8230
8231/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8232/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8233/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8234/// can ever produce, since every `tx_type` this decoder's rect sets can read
8235/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8236/// rather than guess-decode if a non-2D class ever shows up here, since
8237/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8238/// form for those.
8239
8240// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
8241// of this reader -- the only thing that identifies a unit's route. No plane is
8242// printed here: the plane is the ORACLE's side of the pairing, and a label
8243// here is one more thing that can disagree with it.
8244#[track_caller]
8245fn read_coeffs_rect(
8246 dec: &mut SymbolDecoder,
8247 coding: &mut TxbTables,
8248 scan: &[u16],
8249 w: usize,
8250 h: usize,
8251 skip_ctx: usize,
8252 sign_ctx: usize,
8253 default_tx_type: TxType,
8254 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8255 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8256 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8257 // independent lane reports.
8258 plane: usize,
8259) -> Result<(Grid, TxType)> {
8260 let rect_trace = coeff_trace_on();
8261 let entry_rng = dec.debug_state().0;
8262 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8263 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8264 // plane itself rather than inheriting whichever reader did last. The
8265 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8266 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8267 // value -- and the other plane-owning readers stamp on entry.
8268 set_census_plane(plane);
8269 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
8270 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
8271 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8272 if rect_trace {
8273 eprintln!(
8274 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
8275 all_zero as i32,
8276 dec.debug_state().0,
8277 dec.debug_bitpos()
8278 );
8279 }
8280 if ibctx_on {
8281 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
8282 // range: the only collision-free key for pairing this unit against the
8283 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
8284 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
8285 // either way, which is exactly the artifact that made an earlier
8286 // round of this lane claim a false exactness.
8287 eprintln!(
8288 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
8289 dec.debug_bitpos(),
8290 std::panic::Location::caller(),
8291 );
8292 }
8293 if all_zero {
8294 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8295 return Ok((Grid::Zero(w * h), TxType::DctDct));
8296 }
8297 let mut grid = vec![0i32; w * h];
8298 hit!(RECT_COEFF_TU_HITS);
8299 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8300 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8301 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8302 // context offsets -- both of which now have rect forms
8303 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8304 // The rect sets that carry no symbol at all still pass `None` here.
8305 let mut tx_type = default_tx_type;
8306 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8307 let len = tx_type_cdf.len();
8308 let t = dec.symbol(tx_type_cdf);
8309 crate::census::tx_type(len, t);
8310 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8311 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8312 })?;
8313 if rect_trace {
8314 eprintln!(
8315 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8316 dec.debug_state().0
8317 );
8318 }
8319 }
8320 let class = TxClass::of(tx_type);
8321 if class != TxClass::TwoD {
8322 hit!(TX_CLASS1_HITS);
8323 }
8324 let eob = read_eob(dec, coding, class);
8325 if rect_trace {
8326 eprintln!(
8327 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8328 dec.debug_state().0
8329 );
8330 }
8331 let class_scan;
8332 let scan: &[u16] = if class == TxClass::TwoD {
8333 scan
8334 } else {
8335 class_scan = class_scan_table_wh(w, h, class);
8336 &class_scan
8337 };
8338 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8339 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8340 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8341 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8342 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8343 // mask rather than a hardware divide.
8344 let stride = w + 4;
8345 let n = stride * (h + 4);
8346 if !(w.is_power_of_two() && n <= 36 * 36) {
8347 panic!("rect coeff scratch w={w} h={h} n={n}");
8348 }
8349 let (mut b96, mut b256, mut b768);
8350 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8351 let levels: &mut [u8] = if n <= 96 {
8352 b96 = [0u8; 96];
8353 &mut b96[..n]
8354 } else if n <= 256 {
8355 b256 = [0u8; 256];
8356 &mut b256[..n]
8357 } else {
8358 b768 = [0u8; 768];
8359 &mut b768[..n]
8360 };
8361 let wsh = w.trailing_zeros();
8362 let wmask = w - 1;
8363 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8364 let mut nz_buf = [0u16; 1024];
8365 let mut nz_n = 0usize;
8366 let (base_taps, br_taps) = flat_taps(stride, class);
8367 let (wlt, wgt) = (w < h, w > h);
8368 for scan_idx in (0..eob).rev() {
8369 let pos = scan[scan_idx] as usize;
8370 let (row, col) = (pos >> wsh, pos & wmask);
8371 let idx = row * stride + col;
8372 // libaom's column-major `coeff_idx`, for ladder comparison.
8373 let _apos = col * h + row;
8374 let level = if scan_idx == eob - 1 {
8375 let ctx = eob_coeff_ctx(scan_idx, w * h);
8376 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8377 if rect_trace {
8378 eprintln!(
8379 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8380 dec.debug_state().0
8381 );
8382 }
8383 v
8384 } else {
8385 let ctx = if class == TxClass::TwoD {
8386 if row == 0 && col == 0 {
8387 0
8388 } else {
8389 let m = base_mag(levels, idx, &base_taps);
8390 if wlt && row < 2 {
8391 m + 11
8392 } else if wgt && col < 2 {
8393 m + 16
8394 } else {
8395 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8396 }
8397 }
8398 } else {
8399 base_ctx_rect(levels, stride, w, h, row, col, class)
8400 };
8401 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8402 if rect_trace {
8403 eprintln!(
8404 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8405 dec.debug_state().0
8406 );
8407 }
8408 v
8409 };
8410 let level = if level > NUM_BASE_LEVELS {
8411 let ctx = {
8412 let mag = br_mag(levels, idx, &br_taps);
8413 if row == 0 && col == 0 {
8414 mag
8415 } else {
8416 let near_origin = match class {
8417 TxClass::TwoD => row < 2 && col < 2,
8418 TxClass::Horiz => col == 0,
8419 TxClass::Vert => row == 0,
8420 };
8421 if near_origin { mag + 7 } else { mag + 14 }
8422 }
8423 };
8424 let mut level = level;
8425 let mut sent = 0;
8426 loop {
8427 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8428 if rect_trace {
8429 eprintln!(
8430 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8431 dec.debug_state().0
8432 );
8433 }
8434 level += k;
8435 sent += BR_STEP;
8436 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8437 break;
8438 }
8439 }
8440 level
8441 } else {
8442 level
8443 };
8444 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8445 levels[idx] = level as u8;
8446 if level != 0 {
8447 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8448 nz_n += 1;
8449 }
8450 if rect_trace {
8451 let (rng, _) = dec.debug_state();
8452 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
8453 }
8454 }
8455 if rect_trace {
8456 let (rng, _) = dec.debug_state();
8457 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8458 }
8459 for &packed in nz_buf[..nz_n].iter().rev() {
8460 let pos = scan[(packed >> 4) as usize] as usize;
8461 let level = (packed & 15) as i32;
8462 let negative = if pos == 0 {
8463 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8464 } else {
8465 dec.literal(1) == 1
8466 };
8467 if rect_trace {
8468 let (rng, _) = dec.debug_state();
8469 eprintln!(
8470 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8471 u8::from(negative)
8472 );
8473 }
8474 let level = if level > MAX_BR_LEVEL {
8475 let g = read_golomb(dec)?;
8476 level + g as i32
8477 } else {
8478 level
8479 };
8480 grid[pos] = if negative { -level } else { level };
8481 }
8482 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8483 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8484 // grids differ is a reader defect, one whose grids agree is a transform
8485 // defect.
8486 if crate::envflags::env_flag!("EC_DQCOEFF") {
8487 let nz: Vec<String> = grid
8488 .iter()
8489 .enumerate()
8490 .filter(|&(_, &v)| v != 0)
8491 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8492 .collect();
8493 eprintln!(
8494 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8495 nz.join(",")
8496 );
8497 }
8498 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8499 Ok((Grid::Own(grid), tx_type))
8500}
8501
8502/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8503/// [`read_plane`] family already has.
8504///
8505/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8506/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8507/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8508/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8509/// enforces that for every strip that reads its chroma through it, but the rect
8510/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8511/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8512/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8513/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8514/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8515/// symbol -- and therefore every later pixel -- is decoded from the wrong
8516/// place, without ever tripping a refusal (the desynced values stay inside
8517/// every coded alphabet).
8518fn read_chroma_coeffs_rect(
8519 dec: &mut SymbolDecoder,
8520 coding: &mut TxbTables,
8521 scan: &[u16],
8522 w: usize,
8523 h: usize,
8524 skip_ctx: usize,
8525 sign_ctx: usize,
8526 default_tx_type: TxType,
8527 fctx: &crate::decode::FrameCtx,
8528 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8529 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8530 // V-plane read was indistinguishable from a luma one in the log).
8531 plane: usize,
8532) -> Result<(Grid, TxType)> {
8533 if mono(fctx) {
8534 return Ok((Grid::Zero(w * h), TxType::DctDct));
8535 }
8536 read_coeffs_rect(
8537 dec,
8538 coding,
8539 scan,
8540 w,
8541 h,
8542 skip_ctx,
8543 sign_ctx,
8544 default_tx_type,
8545 plane,
8546 )
8547}
8548
8549/// What one coded block leaves behind for the blocks that read it as a
8550/// neighbour: whether it coded anything at all, and the sign of its DC —
8551/// [`crate::tile`]'s own private `Neighbour`.
8552#[derive(Clone, Copy, Default)]
8553struct Neighbour {
8554 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8555 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8556 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8557 /// boolean (`level != 0`) is enough for every context this decoder read
8558 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8559 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8560 /// needs the actual magnitude tier of its above/left neighbours, not
8561 /// just whether they coded anything.
8562 level: u8,
8563 dc: Option<bool>,
8564}
8565
8566/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8567/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8568/// grid is dropped, never a panic. One `memset` per grid row instead of a
8569/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8570/// is contiguous, so this writes exactly the cells the cell loop did,
8571/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8572/// next row.
8573#[inline]
8574fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8575 let end = (start + n).min(dst.len());
8576 if start < end {
8577 dst[start..end].fill(v);
8578 }
8579}
8580
8581fn neighbour_state(grid: &[i32]) -> Neighbour {
8582 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8583 // sum has no early exit, so the 60% of units that code nothing used to
8584 // walk their whole grid here.
8585 if is_zero_grid(grid) {
8586 return Neighbour::default();
8587 }
8588 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8589 Neighbour {
8590 level: cul.min(7) as u8,
8591 dc: (grid[0] != 0).then_some(grid[0] < 0),
8592 }
8593}
8594
8595/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8596/// transform unit smaller than the block it sits in): `top`/`left` are the
8597/// above/left neighbours' magnitude tiers, each already clamped to 4.
8598pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8599 [1, 2, 2, 2, 3],
8600 [2, 4, 4, 4, 5],
8601 [2, 4, 4, 4, 5],
8602 [2, 4, 4, 4, 5],
8603 [3, 5, 5, 5, 6],
8604];
8605
8606/// The `skip` flag, its written-instrument bit, and the covering coded
8607/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8608/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8609/// nothing else, so a block's row is one fill instead of four, and the
8610/// deblocker's `pu_edge` reads origin and dims off one cache line.
8611#[derive(Clone, Copy)]
8612struct BlkCell {
8613 skip: bool,
8614 written: bool,
8615 org: [u16; 2],
8616 dim: [u8; 2],
8617}
8618
8619/// The neighbour state a block's contexts are read from — a duplicate of
8620/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8621/// territory this round), kept at the same two granularities the real writer
8622/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8623/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8624/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8625/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8626/// chroma transform straddling the true, odd-sized frame edge see its
8627/// neighbour's state clamped at its own subsampled edge rather than luma's.
8628#[derive(Clone)]
8629struct Neighbours {
8630 above: Vec<[Neighbour; 3]>,
8631 left: Vec<[Neighbour; 3]>,
8632 above_mode: Vec<usize>,
8633 left_mode: Vec<usize>,
8634 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8635 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8636 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8637 /// luma one -- the same block can (and often does) code a different
8638 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8639 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8640 /// within-block neighbour finer than this grid) is luma-only -- a known,
8641 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8642 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8643 above_uv_mode: Vec<usize>,
8644 left_uv_mode: Vec<usize>,
8645 above_side: Vec<usize>,
8646 left_side: Vec<usize>,
8647 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8648 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8649 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8650 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8651 /// array cannot tell the second leaf's partition symbol that the first
8652 /// one was coded at 8x8.
8653 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8654 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8655 above_side_mi: Vec<u8>,
8656 left_side_mi: Vec<u8>,
8657 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8658 /// / row, with the mi position it was written at
8659 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8660 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8661 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8662 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8663 /// leaf whose neighbour is another split group needs that group's leaf 3
8664 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8665 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8666 /// fall back to the coarse slot whenever the real neighbour was a block
8667 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8668 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8669 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8670 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8671 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8672 /// frame is 65536 px = 16384 mi).
8673 sub8_mode_col: Vec<(u16, u8)>,
8674 sub8_mode_row: Vec<(u16, u8)>,
8675 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8676 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8677 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8678 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8679 /// the leaf above writes the same row slot the block to the left owns.
8680 uv_mode_col: Vec<(u16, u8)>,
8681 uv_mode_row: Vec<(u16, u8)>,
8682 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8683 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8684 /// blockd.h). lane-t900 r12: the one-slot-per-column
8685 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8686 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8687 /// overwrote the row the pair's chroma-ref half then wanted to read --
8688 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8689 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8690 uv_mode_grid: Vec<u8>,
8691 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8692 /// every other band here).
8693 uv_grid_cols: usize,
8694 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
8695 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
8696 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
8697 /// the `+ss_y` read compares written by the same block?", which is the
8698 /// whole question the `+ss_y` term turns on: the term is only observable
8699 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
8700 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
8701 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
8702 /// in this tile can never be mistaken for a written one.
8703 uv_owner: Vec<u32>,
8704 /// Whether the block above/left of this column/row was coded `skip` --
8705 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8706 /// key-frame writer never tracks (its skip context is always zero); a
8707 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8708 /// `left_skip`.
8709 above_skip: Vec<bool>,
8710 left_skip: Vec<bool>,
8711 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8712 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8713 /// pixels last written over each unit by `set_txfm_ctxs`/
8714 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8715 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8716 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8717 /// array is exactly libaom's per-superblock-row reset, since each mi row
8718 /// is only ever visited inside one superblock row.
8719 above_txfm: Vec<u8>,
8720 left_txfm: Vec<u8>,
8721 /// Whether the block above/left of this column/row coded `skip_mode`
8722 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8723 /// lane-av1comp round 14.
8724 above_skip_mode: Vec<bool>,
8725 left_skip_mode: Vec<bool>,
8726 /// Whether the block above/left was coded inter -- the `is_inter`
8727 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8728 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8729 above_inter: Vec<bool>,
8730 left_inter: Vec<bool>,
8731 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8732 /// alphabet) the block above/left of this column/row coded, or `-1` for
8733 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8734 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8735 /// just "was it inter" (lane-av1refs: every inter block used to be
8736 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8737 /// enough).
8738 above_ref: Vec<i8>,
8739 left_ref: Vec<i8>,
8740 /// The block above/left's *second* reference frame when it was coded
8741 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8742 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8743 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8744 /// `i8`, once a compound `read_ref_frames` lands.
8745 /// lane-publish2 audit: the "always `None` today" note this doc used to
8746 /// carry is long stale -- compound blocks do occur, and
8747 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8748 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8749 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8750 /// [`crate::mvstack::NeighbourRef`] construction (class
8751 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8752 above_ref1: Vec<Option<i8>>,
8753 left_ref1: Vec<Option<i8>>,
8754 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8755 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8756 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8757 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8758 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8759 above_comp_group_idx: Vec<u8>,
8760 left_comp_group_idx: Vec<u8>,
8761 above_compound_idx: Vec<u8>,
8762 left_compound_idx: Vec<u8>,
8763 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8764 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8765 /// block above/left of this column/row -- spec
8766 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8767 above_filter: Vec<[u8; 2]>,
8768 left_filter: Vec<[u8; 2]>,
8769 mi_cols: usize,
8770 mi_rows: usize,
8771 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8772 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8773 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8774 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8775 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8776 /// granularity by [`apply_cdef`] since `skip` is constant across every
8777 /// mi cell one coded block covers.
8778 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8779 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8780 /// the `skip` bit at this mi cell during this frame. A fresh
8781 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8782 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8783 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
8784 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
8785 /// unobservable from the pixels alone. Counted by
8786 /// [`cdef_unwritten_skip_units`].
8787 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
8788 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
8789 /// which re-enables the loop filter at a prediction boundary between two
8790 /// skipped inter blocks (lane-mergefix r4). Written by
8791 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
8792 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
8793 /// that cell -- the other half of `pu_edge`: libaom tests the edge
8794 /// coordinate against the block's size in the FILTERED plane's own
8795 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
8796 blk_grid: Vec<BlkCell>,
8797 skip_grid_cols_mi: usize,
8798 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
8799 /// never splits a coded block's transform below its own size (round 2:
8800 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
8801 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
8802 /// edge-length lookup (`apply_deblock`).
8803 tx_grid: Vec<u8>,
8804 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
8805 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
8806 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
8807 tx_h_grid: Vec<u8>,
8808 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
8809 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
8810 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
8811 /// does NOT follow luma's `tx_depth` split, so deriving it as
8812 /// `tx_grid / 2` invented chroma transform edges the deblocker then
8813 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
8814 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
8815 /// every caller routes through.
8816 uv_tx_grid: Vec<u8>,
8817 uv_tx_h_grid: Vec<u8>,
8818 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
8819 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
8820 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
8821 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
8822 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
8823 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
8824 /// reference onto `LAST_FRAME`'s own delta).
8825 ref_grid: Vec<i8>,
8826 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
8827 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
8828 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
8829 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
8830 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
8831 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
8832 /// to know which mode produced the value.
8833 delta_lf_grid: Vec<[i8; 4]>,
8834 /// The block above/left's own palette-Y size (0 = not a palette block)
8835 /// and its base colours -- `av1_get_palette_mode_ctx`/
8836 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
8837 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
8838 above_palette_size: Vec<u8>,
8839 left_palette_size: Vec<u8>,
8840 above_palette_colors: Vec<[u16; 8]>,
8841 left_palette_colors: Vec<[u16; 8]>,
8842 /// As the four fields above, for the neighbour's own chroma (U-channel
8843 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
8844 /// palette size/colours (lane-palette2 r1).
8845 above_palette_uv_size: Vec<u8>,
8846 left_palette_uv_size: Vec<u8>,
8847 above_palette_uv_colors: Vec<[u16; 8]>,
8848 left_palette_uv_colors: Vec<[u16; 8]>,
8849 /// This tile's own top-left corner, in 4x4 mode-info units (spec
8850 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
8851 /// neighbour" check compares against this instead of literal `0`, since a
8852 /// block at the tile's own top/left edge has no usable neighbour even
8853 /// though a decoded block sits there in the picture (spec `decode_tile`'s
8854 /// per-tile `clear_above_context`/`left_available`/`up_available`).
8855 /// `0` for a single-tile frame, matching every existing caller exactly.
8856 tile_row0_mi: usize,
8857 tile_col0_mi: usize,
8858}
8859
8860#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8861impl Neighbours {
8862 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
8863 /// true (unpadded) size in 4x4 mode-info units.
8864 fn new(
8865 cols: usize,
8866 rows: usize,
8867 mi_cols: usize,
8868 mi_rows: usize,
8869 fctx: &crate::decode::FrameCtx,
8870 ) -> Self {
8871 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
8872 // neighbour state over the whole 64-row extent, past the frame's last
8873 // mi row (mi_rows 198, block rows 192..208). libaom's own context
8874 // buffers are superblock-aligned for exactly that reason
8875 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
8876 // side arrays to a superblock multiple and leave those cells unread --
8877 // every availability check uses the true `mi_rows`/`mi_cols` below.
8878 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
8879 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
8880 Self {
8881 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
8882 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
8883 above_mode: vec![DC_PRED; cols],
8884 left_mode: vec![DC_PRED; rows],
8885 above_uv_mode: vec![DC_PRED; cols],
8886 left_uv_mode: vec![DC_PRED; rows],
8887 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
8888 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
8889 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
8890 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
8891 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8892 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8893 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8894 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8895 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
8896 uv_grid_cols: cols * (SUB / MI),
8897 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
8898 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
8899 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
8900 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
8901 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
8902 // 16x16 block beside it, which a SUB-grid slot cannot name
8903 // (class context-read-from-one-cell).
8904 above_skip: vec![false; cols * (SUB / MI)],
8905 left_skip: vec![false; rows * (SUB / MI)],
8906 above_skip_mode: vec![false; cols * (SUB / MI)],
8907 left_skip_mode: vec![false; rows * (SUB / MI)],
8908 above_inter: vec![false; cols * (SUB / MI)],
8909 left_inter: vec![false; rows * (SUB / MI)],
8910 above_ref: vec![-1; cols * (SUB / MI)],
8911 left_ref: vec![-1; rows * (SUB / MI)],
8912 above_ref1: vec![None; cols * (SUB / MI)],
8913 left_ref1: vec![None; rows * (SUB / MI)],
8914 above_comp_group_idx: vec![0; cols * (SUB / MI)],
8915 left_comp_group_idx: vec![0; rows * (SUB / MI)],
8916 above_compound_idx: vec![0; cols * (SUB / MI)],
8917 left_compound_idx: vec![0; rows * (SUB / MI)],
8918 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
8919 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
8920 mi_cols,
8921 mi_rows,
8922 blk_grid: vec![
8923 BlkCell {
8924 skip: false,
8925 written: false,
8926 org: [0; 2],
8927 dim: [1; 2]
8928 };
8929 cols * (SUB / MI) * rows * (SUB / MI)
8930 ],
8931 skip_grid_cols_mi: cols * (SUB / MI),
8932 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8933 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8934 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8935 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8936 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
8937 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
8938 above_palette_size: vec![0; cols * (SUB / MI)],
8939 left_palette_size: vec![0; rows * (SUB / MI)],
8940 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8941 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8942 above_palette_uv_size: vec![0; cols * (SUB / MI)],
8943 left_palette_uv_size: vec![0; rows * (SUB / MI)],
8944 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8945 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8946 tile_row0_mi: 0,
8947 tile_col0_mi: 0,
8948 }
8949 }
8950
8951 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
8952 /// tile's own column span (`col1_mi` exclusive), plus recording
8953 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
8954 /// availability check below. Left context resets every superblock row
8955 /// regardless of tile ([`Self::start_row`], already called once per SB
8956 /// row by every caller) so it needs no tile-specific reset here.
8957 fn start_tile(
8958 &mut self,
8959 row0_mi: usize,
8960 col0_mi: usize,
8961 col1_mi: usize,
8962 fctx: &crate::decode::FrameCtx,
8963 ) {
8964 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
8965 // are tile-relative, same as every other neighbour lookup here.
8966 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
8967 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
8968 // tile writes, so the `+ss_y` read's "different block?" probe never
8969 // compares against a cell a previous tile left behind.
8970 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
8971 self.tile_row0_mi = row0_mi;
8972 self.tile_col0_mi = col0_mi;
8973 let end = col1_mi.min(self.above.len());
8974 for i in col0_mi.min(end)..end {
8975 self.above[i] = Default::default();
8976 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
8977 }
8978 let (sc0, sc1) = (
8979 col0_mi / (SUB / MI),
8980 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
8981 );
8982 for i in sc0.min(sc1)..sc1 {
8983 self.above_mode[i] = DC_PRED;
8984 self.above_side[i] = NO_NEIGHBOUR_SIDE;
8985 }
8986 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
8987 // the tile's own mi column span directly.
8988 let mend = col1_mi.min(self.above_skip.len());
8989 for i in col0_mi.min(mend)..mend {
8990 self.above_skip[i] = false;
8991 self.above_skip_mode[i] = false;
8992 self.above_inter[i] = false;
8993 self.above_ref[i] = -1;
8994 self.above_ref1[i] = None;
8995 self.above_comp_group_idx[i] = 0;
8996 self.above_compound_idx[i] = 0;
8997 self.above_filter[i] = [3u8; 2];
8998 }
8999 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
9000 // stale `(row, mode)` from the tile to the LEFT names an mi row this
9001 // tile's first block would read as its own above neighbour.
9002 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
9003 for i in col0_mi.min(mcol_end)..mcol_end {
9004 self.sub8_mode_col[i] = (u16::MAX, 0);
9005 self.uv_mode_col[i] = (u16::MAX, 0);
9006 }
9007 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
9008 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
9009 // not zero) -- without it a second tile column reads the first one's
9010 // resolved transform sizes as its own above context.
9011 let tend = col1_mi.min(self.above_txfm.len());
9012 for i in col0_mi.min(tend)..tend {
9013 self.above_txfm[i] = TXFM_CTX_INIT;
9014 }
9015 }
9016
9017 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
9018 /// for a non-palette block, clearing any stale neighbour state) into every
9019 /// [`SUB`]-grid cell it covers on both the above and left edges --
9020 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
9021 /// call sites are all square blocks).
9022 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
9023 self.record_palette_y_rect(
9024 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9025 side,
9026 side,
9027 size,
9028 colors,
9029 );
9030 }
9031
9032 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
9033 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
9034 /// [`Self::record`]): a true rect strip's above/left neighbour spans
9035 /// differ.
9036 fn record_palette_y_rect(
9037 &mut self,
9038 mi: (usize, usize),
9039 w: usize,
9040 h: usize,
9041 size: usize,
9042 colors: [u16; 8],
9043 ) {
9044 let (r, c) = mi;
9045 if crate::envflags::env_flag!("EC_PALPUB") {
9046 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
9047 }
9048 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
9049 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
9050 // cell immediately left of the block, not its 16px [`SUB`] cell. The
9051 // old SUB grid let a 16x8 strip pair share one slot, so the second
9052 // strip of mi(0,8) read the FIRST strip's palette size and the colour
9053 // cache came out one entry short (class [[context-read-from-one-cell]]).
9054 for cell in 0..(w / MI).max(1) {
9055 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
9056 *e = size as u8;
9057 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
9058 // neighbour's colours only where its palette size > 0, so a
9059 // non-palette block need not stamp 16 bytes of zeroes here.
9060 if size > 0 {
9061 self.above_palette_colors[c + cell] = colors;
9062 }
9063 }
9064 }
9065 for cell in 0..(h / MI).max(1) {
9066 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
9067 *e = size as u8;
9068 if size > 0 {
9069 self.left_palette_colors[r + cell] = colors;
9070 }
9071 }
9072 }
9073 }
9074
9075 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
9076 /// neighbours that are themselves a palette-Y block, plus
9077 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
9078 /// cache (pred_common.c:73).
9079 ///
9080 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
9081 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
9082 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
9083 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
9084 /// the ctx too made every superblock in the frame's second SB row read
9085 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
9086 /// palette block decoded as "no palette" and the tile desynced from
9087 /// there (class [[cdf-row-held-constant]]).
9088 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
9089 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9090 }
9091
9092 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
9093 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
9094 /// drops the above neighbour on a 64-px superblock boundary
9095 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
9096 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
9097 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
9098 /// every strip in an SB's top cell row, which libaom does not do.
9099 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
9100 let (r, c) = mi;
9101 let above_ok = r % 16 != 0;
9102 // `xd->above_mbmi` exists for every row but the tile's own first.
9103 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
9104 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
9105 (
9106 usize::from(self.above_palette_size[c]),
9107 self.above_palette_colors[c],
9108 )
9109 } else {
9110 (0, [0u16; 8])
9111 };
9112 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
9113 // is NULL whenever the block sits at its TILE's own left column
9114 // (`left_available`), not the frame's -- without this guard a second
9115 // tile column reads the previous tile's palette colours into its cache
9116 // and its `palette_y_mode` ctx.
9117 let left_ok = c > self.tile_col0_mi;
9118 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
9119 (
9120 usize::from(self.left_palette_size[r]),
9121 self.left_palette_colors[r],
9122 )
9123 } else {
9124 (0, [0u16; 8])
9125 };
9126 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
9127 let mut cache = Vec::with_capacity(16);
9128 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9129 if cache.last() != Some(&v) {
9130 cache.push(v);
9131 }
9132 };
9133 let (mut ai, mut li) = (0usize, 0usize);
9134 while ai < above_n && li < left_n {
9135 let (va, vl) = (above_colors[ai], left_colors[li]);
9136 if vl < va {
9137 push_dedup(&mut cache, vl);
9138 li += 1;
9139 } else {
9140 push_dedup(&mut cache, va);
9141 ai += 1;
9142 if vl == va {
9143 li += 1;
9144 }
9145 }
9146 }
9147 while ai < above_n {
9148 push_dedup(&mut cache, above_colors[ai]);
9149 ai += 1;
9150 }
9151 while li < left_n {
9152 push_dedup(&mut cache, left_colors[li]);
9153 li += 1;
9154 }
9155 (ctx, cache)
9156 }
9157
9158 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
9159 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9160 /// same way (lane-palette2 r1).
9161 fn record_palette_uv(
9162 &mut self,
9163 at: (usize, usize),
9164 side: usize,
9165 size: usize,
9166 colors: [u16; 8],
9167 ) {
9168 self.record_palette_uv_rect(
9169 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9170 side,
9171 side,
9172 size,
9173 colors,
9174 );
9175 }
9176
9177 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9178 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9179 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9180 /// luma resolution regardless of which plane the recorded state is for).
9181 fn record_palette_uv_rect(
9182 &mut self,
9183 mi: (usize, usize),
9184 w: usize,
9185 h: usize,
9186 size: usize,
9187 colors: [u16; 8],
9188 ) {
9189 let (r, c) = mi;
9190 // mi granularity, see [`Self::record_palette_y_rect`].
9191 for cell in 0..(w / MI).max(1) {
9192 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9193 *e = size as u8;
9194 if size > 0 {
9195 self.above_palette_uv_colors[c + cell] = colors;
9196 }
9197 }
9198 }
9199 for cell in 0..(h / MI).max(1) {
9200 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9201 *e = size as u8;
9202 if size > 0 {
9203 self.left_palette_uv_colors[r + cell] = colors;
9204 }
9205 }
9206 }
9207 }
9208
9209 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9210 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9211 /// no neighbour lookup at all (it is this block's own just-decided Y
9212 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9213 /// so only the cache is wanted here.
9214 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9215 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9216 }
9217
9218 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9219 /// [`Self::palette_ctx_and_cache_mi`].
9220 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9221 let (r, c) = mi;
9222 let above_ok = r % 16 != 0;
9223 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9224 (
9225 usize::from(self.above_palette_uv_size[c]),
9226 self.above_palette_uv_colors[c],
9227 )
9228 } else {
9229 (0, [0u16; 8])
9230 };
9231 // Same tile-relative left availability as the luma cache above.
9232 let left_ok = c > self.tile_col0_mi;
9233 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9234 (
9235 usize::from(self.left_palette_uv_size[r]),
9236 self.left_palette_uv_colors[r],
9237 )
9238 } else {
9239 (0, [0u16; 8])
9240 };
9241 let mut cache = Vec::with_capacity(16);
9242 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9243 if cache.last() != Some(&v) {
9244 cache.push(v);
9245 }
9246 };
9247 let (mut ai, mut li) = (0usize, 0usize);
9248 while ai < above_n && li < left_n {
9249 let (va, vl) = (above_colors[ai], left_colors[li]);
9250 if vl < va {
9251 push_dedup(&mut cache, vl);
9252 li += 1;
9253 } else {
9254 push_dedup(&mut cache, va);
9255 ai += 1;
9256 if vl == va {
9257 li += 1;
9258 }
9259 }
9260 }
9261 while ai < above_n {
9262 push_dedup(&mut cache, above_colors[ai]);
9263 ai += 1;
9264 }
9265 while li < left_n {
9266 push_dedup(&mut cache, left_colors[li]);
9267 li += 1;
9268 }
9269 cache
9270 }
9271
9272 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9273 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9274 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9275 /// units as [`Self::fill_skip_grid`].
9276 fn fill_lf_grid(
9277 &mut self,
9278 at_mi: (usize, usize),
9279 side_mi: usize,
9280 tx_px: u8,
9281 ref_frame: i8,
9282 fctx: &crate::decode::FrameCtx,
9283 ) {
9284 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9285 }
9286
9287 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9288 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9289 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9290 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9291 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9292 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9293 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9294 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9295 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9296 /// block's published transform extent to its own size is exactly that
9297 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9298 /// that needs it is the 128 root, whose chroma extent is the one
9299 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9300 /// never suppressed (libaom's `is_inter_block` term), so this is called
9301 /// only from the skipped-inter branch.
9302 ///
9303 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
9304 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
9305 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
9306 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
9307 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
9308 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
9309 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
9310 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
9311 /// no format guard was possible inside this method until now.
9312 ///
9313 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
9314 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
9315 /// every edge it lets through then meets the SAME libaom rule applied at
9316 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
9317 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
9318 /// skip_at && skip_at`. Inside one skipped block both cells are that same
9319 /// block, so all four terms hold and the edge dies there too. The masking
9320 /// is TOTAL, not incidental: this method is only ever called for a block
9321 /// that is itself skipped, so no input exists on which one side of an
9322 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
9323 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
9324 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
9325 /// differ from each other in not one sample. The gate for this value is
9326 /// therefore a source scan, not a pixel gate --
9327 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
9328 fn suppress_internal_lf_edges(
9329 &mut self,
9330 at_mi: (usize, usize),
9331 w_mi: usize,
9332 h_mi: usize,
9333 fctx: &FrameCtx,
9334 ) {
9335 let (mi_r, mi_c) = at_mi;
9336 let (uv_w, uv_h) = (
9337 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
9338 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
9339 );
9340 for rr in 0..h_mi {
9341 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9342 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9343 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9344 }
9345 }
9346
9347 fn fill_lf_grid_rect(
9348 &mut self,
9349 at_mi: (usize, usize),
9350 w_mi: usize,
9351 h_mi: usize,
9352 tx_px: u8,
9353 tx_h_px: u8,
9354 ref_frame: i8,
9355 fctx: &crate::decode::FrameCtx,
9356 ) {
9357 let (mi_r, mi_c) = at_mi;
9358 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9359 // half its luma one (min 4 px, the smallest transform), capped at
9360 // TX_32X32 -- independent of this block's luma `tx_depth`.
9361 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9362 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9363 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9364 eprintln!(
9365 "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}"
9366 );
9367 }
9368 crate::census::tx(tx_px, tx_h_px);
9369 let cur = fctx.current_delta_lf.with(|c| c.get());
9370 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9371 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9372 } else {
9373 [cur[0].clamp(-63, 63) as i8; 4]
9374 };
9375 for rr in 0..h_mi {
9376 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9377 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9378 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9379 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9380 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9381 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9382 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9383 }
9384 if fctx.intra_only.with(std::cell::Cell::get) {
9385 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9386 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9387 // xd)` for EVERY block, an intra-only frame's included, and
9388 // `get_tx_size_context` / `txfm_partition_context` read those two
9389 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9390 // over the same footprint, so the publish is this write: the
9391 // `skip && is_inter` term is 0 for every intra-only block that is
9392 // not an intrabc one, and the bodies that can code an intrabc
9393 // block publish their own (the term is then the BLOCK size, a value
9394 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9395 // Inter frames publish at their own sites and are excluded here
9396 // because their skipped-block term needs the block size too.
9397 txfm_partition_update_rect(
9398 self,
9399 at_mi,
9400 (tx_px as usize, tx_h_px as usize),
9401 (w_mi * MI, h_mi * MI),
9402 );
9403 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9404 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9405 // instead of its transform band. Every block stamps its own cells
9406 // here; the intrabc bodies re-stamp theirs `true` afterwards
9407 // (`record_intrabc_inter_bands`).
9408 for i in 0..w_mi {
9409 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9410 *cell = false;
9411 }
9412 }
9413 for i in 0..h_mi {
9414 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9415 *cell = false;
9416 }
9417 }
9418 }
9419 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9420 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9421 // not just the intrabc ones. A later intrabc block's DV predictor is
9422 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9423 // `MB_MODE_INFO` for EVERY block and steps by
9424 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9425 // non-intrabc neighbour reads as uncovered and the scan advances it
9426 // by one cell instead of by its real width.
9427 fctx.intrabc_mi_grid.with(|g| {
9428 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9429 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9430 }
9431 });
9432 }
9433
9434 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9435 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9436 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9437 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9438 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9439 /// dims from the LEAF span and so invented chroma transform edges the
9440 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9441 /// are already correct from the block's own fill over the same span.
9442 fn fill_lf_grid_leaf_luma(
9443 &mut self,
9444 at_mi: (usize, usize),
9445 w_mi: usize,
9446 h_mi: usize,
9447 tx_px: u8,
9448 tx_h_px: u8,
9449 ) {
9450 let (mi_r, mi_c) = at_mi;
9451 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9452 eprintln!(
9453 "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}"
9454 );
9455 }
9456 for rr in 0..h_mi {
9457 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9458 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9459 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9460 }
9461 }
9462
9463 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9464 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9465 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9466 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9467 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9468 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9469 }
9470
9471 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9472 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9473 let (mi_r, mi_c) = at_mi;
9474 if skip && w_mi != h_mi {
9475 hit!(RECT_SKIP_BAND_HITS);
9476 }
9477 // lane-census: an INTRA frame's blocks never reach the inter
9478 // publisher, and this one is what every coded block writes.
9479 crate::census::block_intra_frame(w_mi, h_mi, skip);
9480 for rr in 0..h_mi {
9481 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9482 fill_span(
9483 &mut self.blk_grid,
9484 start,
9485 w_mi,
9486 BlkCell {
9487 skip,
9488 written: true,
9489 org: [mi_r as u16, mi_c as u16],
9490 dim: [w_mi as u8, h_mi as u8],
9491 },
9492 );
9493 }
9494 }
9495
9496 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
9497 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
9498 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
9499 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
9500 /// straddle the region with a mix of skip/non-skip blocks).
9501 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
9502 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
9503 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
9504 /// filtered edge's two sides are each exactly one coded block wide.
9505 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
9506 self.blk_grid
9507 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9508 .is_some_and(|c| c.skip)
9509 }
9510
9511 /// The `skip_txfm` context of a block whose top-left mi cell is
9512 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
9513 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
9514 /// with an absent neighbour contributing 0. The mi grid is per tile, so
9515 /// row/column 0 is a tile edge and has no neighbour on that axis.
9516 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
9517 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
9518 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
9519 }
9520
9521 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
9522 (0..2).all(|rr| {
9523 (0..2).all(|cc| {
9524 self.blk_grid
9525 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
9526 .is_some_and(|c| c.skip)
9527 })
9528 })
9529 }
9530
9531 fn start_row(&mut self) {
9532 self.left.iter_mut().for_each(|l| *l = Default::default());
9533 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
9534 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
9535 self.left_side
9536 .iter_mut()
9537 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
9538 self.left_side_mi
9539 .iter_mut()
9540 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
9541 self.left_skip.iter_mut().for_each(|s| *s = false);
9542 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
9543 self.left_inter.iter_mut().for_each(|i| *i = false);
9544 self.left_ref.iter_mut().for_each(|r| *r = -1);
9545 self.left_ref1.iter_mut().for_each(|r| *r = None);
9546 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
9547 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9548 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
9549 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
9550 // context (a tile/SB-row boundary has no left neighbour).
9551 self.sub8_mode_row
9552 .iter_mut()
9553 .for_each(|s| *s = (u16::MAX, 0));
9554 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
9555 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
9556 // are per-mi maps like every other one here, so they reset with the
9557 // row too -- the left guard above is what actually stops a cross-tile
9558 // read, this keeps a stale colour out of the arrays at all.
9559 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
9560 self.left_palette_colors
9561 .iter_mut()
9562 .for_each(|c| *c = [0u16; 8]);
9563 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
9564 self.left_palette_uv_colors
9565 .iter_mut()
9566 .for_each(|c| *c = [0u16; 8]);
9567 // lane-mergefix r2: `av1_zero_left_context` memsets
9568 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
9569 // every superblock row of every tile -- the var-tx left context does
9570 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
9571 // previous tile column's last block otherwise).
9572 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9573 }
9574
9575 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
9576 /// block that reads it as a neighbour -- [`crate::tile`]'s
9577 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9578 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9579 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9580 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9581 /// the real value, not just `is_inter`).
9582 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9583 fn record_inter(
9584 &mut self,
9585 at: (usize, usize),
9586 side: usize,
9587 skip: bool,
9588 is_inter: bool,
9589 ref_frame: i8,
9590 filter: [u8; 2],
9591 skip_mode: bool,
9592 ) {
9593 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9594 }
9595
9596 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9597 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9598 /// r1: a true rectangular strip's above-context span (its own width) and
9599 /// left-context span (its own height) differ, unlike every caller before
9600 /// this round (class neighbour-votes-all-its-fields).
9601 #[allow(clippy::too_many_arguments)]
9602 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9603 fn record_inter_rect(
9604 &mut self,
9605 at: (usize, usize),
9606 w_sub: usize,
9607 h_sub: usize,
9608 skip: bool,
9609 is_inter: bool,
9610 ref_frame: i8,
9611 filter: [u8; 2],
9612 skip_mode: bool,
9613 ) {
9614 let (r, c) = at;
9615 self.record_inter_rect_mi(
9616 (r * (SUB / MI), c * (SUB / MI)),
9617 w_sub / MI,
9618 h_sub / MI,
9619 skip,
9620 is_inter,
9621 ref_frame,
9622 filter,
9623 skip_mode,
9624 );
9625 }
9626
9627 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9628 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9629 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9630 /// routes through the wrapper above.
9631 #[allow(clippy::too_many_arguments)]
9632 fn record_inter_rect_mi(
9633 &mut self,
9634 at_mi: (usize, usize),
9635 w_mi: usize,
9636 h_mi: usize,
9637 skip: bool,
9638 is_inter: bool,
9639 ref_frame: i8,
9640 filter: [u8; 2],
9641 skip_mode: bool,
9642 ) {
9643 let (r, c) = at_mi;
9644 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9645 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9646 // writes for a whole block class): an INTER block left the luma mode
9647 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9648 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9649 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9650 // block in that pixel row -- the directional edge filter then ran at
9651 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9652 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9653 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9654 // already stamped it).
9655 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9656 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9657 // uv map must read DC_PRED over an inter block's cells too.
9658 if is_inter {
9659 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9660 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9661 }
9662 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9663 self.above_skip[c..c + w_mi].fill(skip);
9664 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9665 self.above_inter[c..c + w_mi].fill(is_inter);
9666 self.above_ref[c..c + w_mi].fill(ref_frame);
9667 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9668 // this with the block's real second reference for a compound block,
9669 // called right after this one (lane-publish2 audit).
9670 self.above_ref1[c..c + w_mi].fill(None);
9671 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9672 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9673 // as `3`/`1` even though this block has no second reference.
9674 // `record_compound_ctx` overwrites this with the real bit for an
9675 // actual compound block's cells, called right after this one.
9676 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9677 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9678 self.above_filter[c..c + w_mi].fill(filter);
9679 self.left_skip[r..r + h_mi].fill(skip);
9680 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9681 self.left_inter[r..r + h_mi].fill(is_inter);
9682 self.left_ref[r..r + h_mi].fill(ref_frame);
9683 self.left_ref1[r..r + h_mi].fill(None);
9684 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9685 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9686 self.left_filter[r..r + h_mi].fill(filter);
9687 }
9688
9689 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9690 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9691 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9692 /// `get_comp_index_context`) -- called right after `record_inter` for
9693 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9694 /// stamps `above_ref1`/`left_ref1` with the block's real second
9695 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9696 /// this is the one caller that actually knows it) -- so the next block's
9697 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9698 /// neighbour instead of `record_inter`'s single-ref default.
9699 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9700 fn record_compound_ctx(
9701 &mut self,
9702 at: (usize, usize),
9703 side: usize,
9704 ref1: i8,
9705 comp_group_idx: u8,
9706 compound_idx: u8,
9707 ) {
9708 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
9709 }
9710
9711 /// [`Self::record_compound_ctx`] with independent above/left extents,
9712 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
9713 #[allow(clippy::too_many_arguments)]
9714 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9715 fn record_compound_ctx_rect(
9716 &mut self,
9717 at: (usize, usize),
9718 w_sub: usize,
9719 h_sub: usize,
9720 ref1: i8,
9721 comp_group_idx: u8,
9722 compound_idx: u8,
9723 ) {
9724 let (r, c) = at;
9725 self.record_compound_ctx_rect_mi(
9726 (r * (SUB / MI), c * (SUB / MI)),
9727 w_sub / MI,
9728 h_sub / MI,
9729 ref1,
9730 comp_group_idx,
9731 compound_idx,
9732 );
9733 }
9734
9735 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
9736 /// [`Self::record_inter_rect_mi`]).
9737 fn record_compound_ctx_rect_mi(
9738 &mut self,
9739 at_mi: (usize, usize),
9740 w_mi: usize,
9741 h_mi: usize,
9742 ref1: i8,
9743 comp_group_idx: u8,
9744 compound_idx: u8,
9745 ) {
9746 let (r, c) = at_mi;
9747 crate::census::compound();
9748 for cell in 0..w_mi {
9749 self.above_ref1[c + cell] = Some(ref1);
9750 self.above_comp_group_idx[c + cell] = comp_group_idx;
9751 self.above_compound_idx[c + cell] = compound_idx;
9752 }
9753 for cell in 0..h_mi {
9754 self.left_ref1[r + cell] = Some(ref1);
9755 self.left_comp_group_idx[r + cell] = comp_group_idx;
9756 self.left_compound_idx[r + cell] = compound_idx;
9757 }
9758 }
9759
9760 /// The context of a block's partition symbol: delegates to the mi-precise
9761 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9762 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
9763 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
9764 /// only touches the finer mi arrays -- leaves them stale for the *next*
9765 /// sibling's own partition symbol.
9766 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
9767 let (r, c) = at;
9768 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
9769 }
9770
9771 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
9772 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
9773 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
9774 /// than the enclosing 16x16 slot's stale, shared state.
9775 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9776 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
9777 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
9778 }
9779
9780 /// The gathered coded/DC-sign state of the blocks above and to the left
9781 /// of a block `side` samples across, per plane.
9782 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9783 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
9784 }
9785
9786 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
9787 /// units, for the same reason [`Self::record_mi`] does.
9788 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9789 let side_mi = side / MI;
9790 // One pass over the cells accumulating all three planes, not one pass
9791 // per plane: the three planes of a cell live in the same
9792 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
9793 // cache lines three times (lane-publish). Clamp each edge to the true
9794 // frame extent: a block at the right/bottom edge may be padded beyond
9795 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
9796 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
9797 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
9798 let mut out = [(false, false, 0i32); 3];
9799 for cell in 0..above_mi {
9800 let above = &self.above[mi_c + cell];
9801 for (plane, o) in out.iter_mut().enumerate() {
9802 o.0 |= above[plane].level != 0;
9803 o.2 += dc_vote(above[plane].dc);
9804 }
9805 }
9806 for cell in 0..left_mi {
9807 let left = &self.left[mi_r + cell];
9808 for (plane, o) in out.iter_mut().enumerate() {
9809 o.1 |= left[plane].level != 0;
9810 o.2 += dc_vote(left[plane].dc);
9811 }
9812 }
9813 out
9814 }
9815
9816 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
9817 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
9818 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
9819 /// spans TWO luma mi columns. Both cells of a column carry the covering
9820 /// unit's whole-unit dc sign (the same value libaom stores), so the
9821 /// per-luma-mi sum counts each chroma column twice -- and
9822 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
9823 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
9824 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
9825 /// Sampling every second above cell counts each chroma column once,
9826 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
9827 /// its per-mi cells already line up one-to-one. The level booleans are
9828 /// ORs over duplicated cells, so the sampling cannot change them.
9829 fn around_mi_422_chroma(
9830 &self,
9831 (mi_r, mi_c): (usize, usize),
9832 w: usize,
9833 h: usize,
9834 ) -> [(bool, bool, i32); 3] {
9835 let (w_mi, h_mi) = (w / MI, h / MI);
9836 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9837 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9838 let mut out = [(false, false, 0i32); 3];
9839 for cell in (0..above_mi).step_by(2) {
9840 let above = &self.above[mi_c + cell];
9841 for (plane, o) in out.iter_mut().enumerate() {
9842 o.0 |= above[plane].level != 0;
9843 o.2 += dc_vote(above[plane].dc);
9844 }
9845 }
9846 for cell in 0..left_mi {
9847 let left = &self.left[mi_r + cell];
9848 for (plane, o) in out.iter_mut().enumerate() {
9849 o.1 |= left[plane].level != 0;
9850 o.2 += dc_vote(left[plane].dc);
9851 }
9852 }
9853 if crate::envflags::env_flag!("EC_DCDUMP") {
9854 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
9855 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
9856 // The above rows are the SAMPLED (every-second) cells.
9857 for (plane, o) in out.iter().enumerate() {
9858 let vote = o.2;
9859 let ab: Vec<String> = (0..above_mi)
9860 .step_by(2)
9861 .map(|k| {
9862 format!(
9863 "{:?}/{}",
9864 self.above[mi_c + k][plane].dc,
9865 self.above[mi_c + k][plane].level
9866 )
9867 })
9868 .collect();
9869 let lf: Vec<String> = (0..left_mi)
9870 .map(|k| {
9871 format!(
9872 "{:?}/{}",
9873 self.left[mi_r + k][plane].dc,
9874 self.left[mi_r + k][plane].level
9875 )
9876 })
9877 .collect();
9878 eprintln!(
9879 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9880 ab.join(","),
9881 lf.join(",")
9882 );
9883 }
9884 }
9885 out
9886 }
9887
9888 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
9889 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
9890 /// extent pattern for a true rectangular strip's own coefficient context.
9891 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
9892 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
9893 }
9894
9895 /// [`Self::around_rect`] taking the block's position directly in 4x4
9896 /// mode-info units, mirroring [`Self::around_mi`].
9897 fn around_mi_rect(
9898 &self,
9899 (mi_r, mi_c): (usize, usize),
9900 w: usize,
9901 h: usize,
9902 ) -> [(bool, bool, i32); 3] {
9903 let (w_mi, h_mi) = (w / MI, h / MI);
9904 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9905 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9906 // [`Self::around_mi`]'s single pass, with the two extents split.
9907 let mut out = [(false, false, 0i32); 3];
9908 for cell in 0..above_mi {
9909 let above = &self.above[mi_c + cell];
9910 for (plane, o) in out.iter_mut().enumerate() {
9911 o.0 |= above[plane].level != 0;
9912 o.2 += dc_vote(above[plane].dc);
9913 }
9914 }
9915 for cell in 0..left_mi {
9916 let left = &self.left[mi_r + cell];
9917 for (plane, o) in out.iter_mut().enumerate() {
9918 o.1 |= left[plane].level != 0;
9919 o.2 += dc_vote(left[plane].dc);
9920 }
9921 }
9922 if crate::envflags::env_flag!("EC_DCDUMP") {
9923 for (plane, o) in out.iter().enumerate() {
9924 let vote = o.2;
9925 let ab: Vec<String> = (0..above_mi)
9926 .map(|k| {
9927 format!(
9928 "{:?}/{}",
9929 self.above[mi_c + k][plane].dc,
9930 self.above[mi_c + k][plane].level
9931 )
9932 })
9933 .collect();
9934 let lf: Vec<String> = (0..left_mi)
9935 .map(|k| {
9936 format!(
9937 "{:?}/{}",
9938 self.left[mi_r + k][plane].dc,
9939 self.left[mi_r + k][plane].level
9940 )
9941 })
9942 .collect();
9943 eprintln!(
9944 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9945 ab.join(","),
9946 lf.join(",")
9947 );
9948 }
9949 }
9950 out
9951 }
9952
9953 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
9954 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
9955 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
9956 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
9957 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
9958 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
9959 /// is always 0, spec's `plane_bsize == tx_size` branch).
9960 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
9961 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
9962 }
9963
9964 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
9965 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
9966 /// context over `tx_size_wide` and the left one over `tx_size_high`.
9967 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
9968 let side_mi = w_mi;
9969 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9970 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9971 let mut top = 0u8;
9972 let mut left = 0u8;
9973 for cell in 0..above_mi {
9974 top |= self.above[mi_c + cell][0].level;
9975 }
9976 for cell in 0..left_mi {
9977 left |= self.left[mi_r + cell][0].level;
9978 }
9979 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
9980 if crate::envflags::env_flag!("EC_ECDUMP") {
9981 let ab: Vec<String> = (0..above_mi)
9982 .map(|k| self.above[mi_c + k][0].level.to_string())
9983 .collect();
9984 let lf: Vec<String> = (0..left_mi)
9985 .map(|k| self.left[mi_r + k][0].level.to_string())
9986 .collect();
9987 // lane-av1mix: the last few msac register states, so the
9988 // byte-position of the `all_zero` read can be matched against
9989 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
9990 // second run.
9991 let recent = crate::msac::symtrace::ecdump_recent(4)
9992 .iter()
9993 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
9994 .collect::<Vec<_>>()
9995 .join(" ");
9996 eprintln!(
9997 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
9998 ab.join(","),
9999 lf.join(","),
10000 recent
10001 );
10002 }
10003 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10004 eprintln!(
10005 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
10006 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
10007 );
10008 }
10009 ctx
10010 }
10011
10012 /// Writes one coded block into every cell it covers, on both grids: the
10013 /// mode/side arrays up to `side`'s own width, and the coefficient-context
10014 /// arrays up to the true frame edge — the units past it are left at their
10015 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
10016 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
10017 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
10018 /// not from this block's own side).
10019 fn record(
10020 &mut self,
10021 at: (usize, usize),
10022 side: usize,
10023 mode: usize,
10024 uv_mode: usize,
10025 grids: &[&[i32]; 3],
10026 ) {
10027 self.record_rect(at, side, side, mode, uv_mode, grids);
10028 }
10029
10030 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
10031 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
10032 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
10033 /// spec's per-edge partition-context rule, so a true rectangular block
10034 /// naturally wants two different values here rather than one.
10035 /// Writes this block's luma `mode` into the mi-granular
10036 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
10037 /// position a *later* neighbour would read it from: the block's LAST mi
10038 /// row for every column it spans (what the block below reads via
10039 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
10040 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
10041 /// read these back, and only when the recorded position is exactly their
10042 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
10043 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
10044 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
10045 let mode = mode as u8;
10046 for cell in 0..mi_w {
10047 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
10048 *slot = (last_r, mode);
10049 }
10050 }
10051 for cell in 0..mi_h {
10052 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
10053 *slot = (last_c, mode);
10054 }
10055 }
10056 }
10057
10058 /// The mi-exact above/left neighbour luma mode for a block whose top-left
10059 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
10060 /// mi position (then the coarse [`SUB`]-grid slot is right by
10061 /// construction). See [`Self::record_mode_mi`].
10062 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10063 match self.sub8_mode_col.get(mi_c) {
10064 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
10065 Some(usize::from(m))
10066 }
10067 _ => None,
10068 }
10069 }
10070
10071 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10072 match self.sub8_mode_row.get(mi_r) {
10073 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
10074 Some(usize::from(m))
10075 }
10076 _ => None,
10077 }
10078 }
10079
10080 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
10081 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
10082 fn record_uv_mode_mi(
10083 &mut self,
10084 mi_r: usize,
10085 mi_c: usize,
10086 mi_w: usize,
10087 mi_h: usize,
10088 uv_mode: usize,
10089 ) {
10090 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
10091 fill_span(
10092 &mut self.uv_mode_col,
10093 mi_c,
10094 mi_w,
10095 (last_r as u16, uv_mode as u8),
10096 );
10097 fill_span(
10098 &mut self.uv_mode_row,
10099 mi_r,
10100 mi_h,
10101 (last_c as u16, uv_mode as u8),
10102 );
10103 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
10104 // covers, so the chroma neighbour read below is a plain grid read.
10105 let stride = self.uv_grid_cols;
10106 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
10107 for row in mi_r..=last_r {
10108 fill_span(
10109 &mut self.uv_mode_grid,
10110 row * stride + mi_c,
10111 n,
10112 uv_mode as u8,
10113 );
10114 }
10115 // lane-av1leftwit: stamp the writing block's own mi over its extent,
10116 // the same cells and the same clipping as `uv_mode_grid` above.
10117 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
10118 for row in mi_r..=last_r {
10119 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
10120 }
10121 if crate::envflags::env_flag!("EC_LEFTSSY") {
10122 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
10123 }
10124 }
10125
10126 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
10127 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
10128 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
10129 /// block has recorded the exact neighbouring mi.
10130 fn smooth_uv_neighbour(
10131 &self,
10132 mi_r: usize,
10133 mi_c: usize,
10134 r: usize,
10135 c: usize,
10136 fctx: &crate::decode::FrameCtx,
10137 ) -> bool {
10138 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
10139 // REFERENCE block, not off the mi that carries the chroma syntax.
10140 // `set_mi_row_col` (`blockd.h`) takes
10141 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
10142 // only then `chroma_above_mbmi = base_mi[-stride]` /
10143 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
10144 // the ODD mi, so without the snap we looked one mi row/column too far
10145 // down/right -- the mi-exact slot never matched and the coarse
10146 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
10147 // 8x4 at (688, 100) = mi (51, 344): libaom's
10148 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
10149 // `UV_SMOOTH_PRED`), ours was 0, which flips
10150 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
10151 // false for type 1, TRUE for type 0) and upsampled an edge libaom
10152 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
10153 // predicting from it (class `context-read-from-one-cell`).
10154 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
10155 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
10156 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
10157 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
10158 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
10159 let snap_y = (1usize << ss_y(fctx)) - 1;
10160 let snap_x = (1usize << ss_x(fctx)) - 1;
10161 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
10162 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
10163 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
10164 // the two chroma-reference offsets on top of it -- see its own comment
10165 // for which axis each one moves.
10166 self.smooth_uv_neighbour_unsnapped(
10167 mi_r & !snap_y,
10168 mi_c & !snap_x,
10169 r,
10170 c,
10171 ss_x(fctx),
10172 ss_y(fctx),
10173 true,
10174 )
10175 }
10176
10177 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
10178 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
10179 /// counter wants this: it measures how often the snap CHANGES the answer,
10180 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
10181 /// decode path uses the snapping form.
10182 /// `decode_path` is `true` only for the snapping form every decode call
10183 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
10184 /// `+ss_y` counters measure a read that actually filters a chroma edge and
10185 /// not the counter-only one.
10186 ///
10187 /// lane-av1leftwit: the mirror's justification used to be "no committed
10188 /// fixture reaches the shape on the decode path", and that was false --
10189 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
10190 /// counter-only mirror at an ODD mi row is still not a decode-path read,
10191 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
10192 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
10193 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
10194 fn smooth_uv_neighbour_unsnapped(
10195 &self,
10196 mi_r: usize,
10197 mi_c: usize,
10198 r: usize,
10199 c: usize,
10200 ss_x: usize,
10201 ss_y: usize,
10202 decode_path: bool,
10203 ) -> bool {
10204 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10205 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10206 // array that `start_tile` does not clear, so a block on a tile's first
10207 // mi row used to read the uv_mode of the block above it in the tile
10208 // ABOVE and filter its chroma edge at that neighbour's strength
10209 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10210 // at chroma (120, 32), the top-right tile's first block).
10211 let have_above = mi_r > self.tile_row0_mi;
10212 let have_left = mi_c > self.tile_col0_mi;
10213 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10214 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10215 {
10216 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10217 }
10218 // The mi grid is libaom's own read; the two maps below stay as the
10219 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10220 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10221 (col < self.uv_grid_cols)
10222 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10223 .flatten()
10224 .filter(|&m| m != u8::MAX)
10225 .map(usize::from)
10226 };
10227 // libaom's two chroma-reference mi, from `set_mi_row_col`
10228 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10229 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10230 // snap -- i.e. already libaom's `base_mi`:
10231 //
10232 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10233 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10234 //
10235 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10236 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10237 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10238 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10239 // boolean it feeds is simply not exercised differently by that stream
10240 // at its blocks. One chroma column spans two luma mi columns, so the
10241 // chroma edge reaches into the right-hand luma block, and that is where
10242 // its reference lives.
10243 //
10244 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10245 // last open item lane-av1422warp carried. libaom puts the left
10246 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10247 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10248 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10249 // read (the above) and regressed the byte-exact 4:2:0 control, which
10250 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10251 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10252 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10253 // measured. Measured over all 48 committed fixtures that decode
10254 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10255 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10256 // put a 1-mi-tall left neighbour in front of a decode-path read at
10257 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10258 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10259 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10260 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10261 // changing is what is still unwitnessed.
10262 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10263 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10264 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10265 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10266 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10267 // row at every subsampling. The term is only observable when the two
10268 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10269 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10270 // and only libaom's is the chroma reference. Three counters measure
10271 // that, and the third is the one the other two need: a read can only
10272 // differ if the two cells are written by DIFFERENT blocks, which
10273 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10274 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10275 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10276 // reads > 0 is the term being unobservable on real material, not
10277 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10278 // whether the mode value, and the boolean this feeds
10279 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10280 // edge filter), actually moved.
10281 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10282 let read_left = |row: usize| -> usize {
10283 match self.uv_mode_row.get(row) {
10284 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10285 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10286 _ if have_left => self.left_uv_mode[r],
10287 _ => DC_PRED,
10288 }
10289 };
10290 let above = match self.uv_mode_col.get(above_mi.1) {
10291 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10292 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10293 _ if have_above => self.above_uv_mode[c],
10294 _ => DC_PRED,
10295 };
10296 let left = read_left(left_mi.0);
10297 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10298 // how many chroma edge-filter-type reads took this path at all, so a
10299 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10300 // term did not change the answer". The two DIFF buckets compare
10301 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10302 // every committed fixture and every one of the ~1000 encodes swept in
10303 // `lanes/av1leftref.report.md`, which is what makes the read change a
10304 // proven no-op on today's material rather than an unmeasured guess.
10305 if decode_path && have_left && ss_y > 0 {
10306 hit!(UV_LEFT_SS_Y_READS);
10307 // The pre-lane read, kept as the counter's own-row arm: it is what
10308 // this decoder answered before the `+ss_y` term landed, and
10309 // comparing against it is what proves the term is load-bearing.
10310 let own_row = read_left(mi_r);
10311 if own_row != left {
10312 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10313 }
10314 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10315 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10316 }
10317 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10318 // cells are one left mi column apart, so they are two different
10319 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10320 let col = left_mi.1;
10321 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10322 let own = (col < self.uv_grid_cols)
10323 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10324 .flatten()
10325 .filter(|o| o & 0xff00_0000 == epoch)
10326 .unwrap_or(0);
10327 let down = self
10328 .uv_owner
10329 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10330 .copied()
10331 .filter(|o| o & 0xff00_0000 == epoch)
10332 .unwrap_or(0);
10333 if own != 0 && down != 0 && own != down {
10334 hit!(UV_LEFT_1MI_SPLIT_HITS);
10335 if crate::envflags::env_flag!("EC_LEFTSSY") {
10336 eprintln!(
10337 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10338 owners=({},{})->({},{}) modes={own_row}/{left}",
10339 epoch >> 24,
10340 own >> 12 & 0xfff,
10341 own & 0xfff,
10342 down >> 12 & 0xfff,
10343 down & 0xfff,
10344 );
10345 }
10346 }
10347 }
10348 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10349 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10350 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10351 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10352 }) {
10353 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10354 }
10355 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10356 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10357 // have been filtered at the wrong strength by the coarse map alone.
10358 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10359 hit!(UV_MODE_MI_OVERRIDE_HITS);
10360 }
10361 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10362 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10363 {
10364 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10365 }
10366 is_smooth_mode(above) || is_smooth_mode(left)
10367 }
10368
10369 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10370 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10371 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10372 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10373 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10374 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10375 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10376 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10377 /// a different CDF for the same mode value).
10378 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10379 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10380 /// only when `up_available` and `left_mbmi` only when `left_available`;
10381 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10382 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10383 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10384 /// strip's mode as its "left neighbour" (measured on the band fixture at
10385 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10386 fn modes_above_left_mi(
10387 &self,
10388 mi_r: usize,
10389 mi_c: usize,
10390 fallback: (usize, usize),
10391 ) -> (usize, usize) {
10392 let above = if mi_r > self.tile_row0_mi {
10393 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10394 } else {
10395 DC_PRED
10396 };
10397 let left = if mi_c > self.tile_col0_mi {
10398 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10399 } else {
10400 DC_PRED
10401 };
10402 (above, left)
10403 }
10404
10405 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10406 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10407 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10408 /// per superblock row and never per tile, so the first block column of
10409 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10410 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10411 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10412 /// `up_available`/`left_available` and uses DC_PRED otherwise
10413 /// ([`Self::modes_above_left_mi`]).
10414 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10415 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10416 let (above, left) =
10417 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10418 if above != self.above_mode[c] || left != self.left_mode[r] {
10419 hit!(MODE_MI_OVERRIDE_HITS);
10420 }
10421 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10422 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10423 {
10424 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10425 }
10426 // A neighbour the coarse band offered where the tile edge makes it
10427 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10428 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10429 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10430 {
10431 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10432 }
10433 (above, left)
10434 }
10435
10436 fn record_rect(
10437 &mut self,
10438 at: (usize, usize),
10439 w: usize,
10440 h: usize,
10441 mode: usize,
10442 uv_mode: usize,
10443 grids: &[&[i32]; 3],
10444 ) {
10445 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10446 }
10447
10448 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10449 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10450 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10451 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10452 /// the [`SUB`]-unit path does).
10453 fn record_rect_mi(
10454 &mut self,
10455 at_mi: (usize, usize),
10456 w: usize,
10457 h: usize,
10458 mode: usize,
10459 uv_mode: usize,
10460 grids: &[&[i32]; 3],
10461 ) {
10462 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10463 self.record_mi_rect(at_mi, w, h, grids);
10464 }
10465
10466 /// [`Self::record_rect_mi`]'s mode and transform-size half, without the
10467 /// coefficient-context stamp.
10468 fn record_rect_mi_modes(
10469 &mut self,
10470 at_mi: (usize, usize),
10471 w: usize,
10472 h: usize,
10473 mode: usize,
10474 uv_mode: usize,
10475 ) {
10476 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
10477 // lane-inter4 r2: a strip whose own footprint runs past the frame's
10478 // last 16-px column/row stamps only the cells that exist (libaom's
10479 // arrays are padded past the frame and those cells are never read).
10480 for cell in 0..w / SUB {
10481 if c + cell >= self.above_mode.len() {
10482 break;
10483 }
10484 self.above_mode[c + cell] = mode;
10485 self.above_uv_mode[c + cell] = uv_mode;
10486 self.above_side[c + cell] = w;
10487 }
10488 for cell in 0..h / SUB {
10489 if r + cell >= self.left_mode.len() {
10490 break;
10491 }
10492 self.left_mode[r + cell] = mode;
10493 self.left_uv_mode[r + cell] = uv_mode;
10494 self.left_side[r + cell] = h;
10495 }
10496 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
10497 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
10498 }
10499
10500 /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv
10501 /// plane block is SEVERAL transform units, each of which stamped its own
10502 /// span through [`Self::record_mi_chroma`]. Writing one whole-block state
10503 /// over them is the `override-slot-on-one-arm` class: libaom keeps the
10504 /// per-unit above/left contexts distinct, and the next block's first
10505 /// unit reads them. The luma plane has one unit here, so it is stamped
10506 /// exactly as the whole-block record stamps it.
10507 fn record_rect_mi_luma_only(
10508 &mut self,
10509 at_mi: (usize, usize),
10510 w: usize,
10511 h: usize,
10512 mode: usize,
10513 uv_mode: usize,
10514 luma_grid: &[i32],
10515 ) {
10516 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10517 fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8);
10518 fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8);
10519 self.record_mi_luma_rect(at_mi, w, h, luma_grid);
10520 }
10521
10522 /// The coefficient-context half of [`Self::record`], taking the block's
10523 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
10524 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
10525 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
10526 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
10527 self.record_mi_rect(at_mi, side, side, grids);
10528 }
10529
10530 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
10531 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
10532 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
10533 let (mi_r, mi_c) = at_mi;
10534 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
10535 let (w_mi, h_mi) = (w / MI, h / MI);
10536 if crate::envflags::env_flag!("EC_ECPUB") {
10537 eprintln!(
10538 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
10539 states[0].level
10540 );
10541 }
10542 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10543 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10544 // A chroma 4x4 unit straddling the true luma edge is still whole in
10545 // chroma's own halved grid, so libaom rounds the luma bound up to the
10546 // plane's own 4x4 unit before clamping a subsampled plane
10547 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
10548 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10549 let bound_h = [
10550 self.mi_rows,
10551 round_up_even(self.mi_rows),
10552 round_up_even(self.mi_rows),
10553 ];
10554 let bound_w = [
10555 self.mi_cols,
10556 round_up_even(self.mi_cols),
10557 round_up_even(self.mi_cols),
10558 ];
10559 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
10560 // past the padded side arrays (mi_rows 198, block rows 192..208);
10561 // libaom's own arrays are superblock-sized, so those cells simply
10562 // have no reader -- [`fill_span`] drops them, as the `break` did.
10563 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
10564 // predicate is three contiguous runs: all planes, chroma only, none
10565 // (lane-mi).
10566 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
10567 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
10568 let uv_only = [Neighbour::default(), states[1], states[2]];
10569 fill_span(&mut self.left, mi_r, luma_h, states);
10570 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
10571 fill_span(
10572 &mut self.left,
10573 mi_r + chroma_h,
10574 h_mi - chroma_h,
10575 [Neighbour::default(); 3],
10576 );
10577 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
10578 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
10579 let uv_only_w = [Neighbour::default(), states[1], states[2]];
10580 fill_span(&mut self.above, mi_c, luma_w, states);
10581 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
10582 fill_span(
10583 &mut self.above,
10584 mi_c + chroma_w,
10585 w_mi - chroma_w,
10586 [Neighbour::default(); 3],
10587 );
10588 }
10589
10590 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
10591 /// inside a coded block whose luma transform is smaller than its own
10592 /// side (`TxMode::Select`): the real per-transform-unit coefficient
10593 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
10594 /// coarse per-block `tx_grid`/`fill_lf_grid` state
10595 /// [`Self::record_split_luma`] still writes once for the whole block.
10596 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
10597 /// the caller's own [`Self::record_split_luma`] call sets those once,
10598 /// at the block's own true side, not this TU's.
10599 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
10600 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
10601 }
10602
10603 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
10604 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
10605 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
10606 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
10607 /// coefficient-context arrays are indexed by luma mi, the convention
10608 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
10609 /// clamp included.
10610 fn record_mi_chroma(
10611 &mut self,
10612 (mi_r, mi_c): (usize, usize),
10613 w_px: usize,
10614 h_px: usize,
10615 plane: usize,
10616 grid: &[i32],
10617 ) {
10618 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10619 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10620 let state = neighbour_state(grid);
10621 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
10622 eprintln!(
10623 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
10624 state.level,
10625 state.dc.map_or(-1, |s| i32::from(s))
10626 );
10627 }
10628 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
10629 self.left[mi_r + cell][plane] = state;
10630 }
10631 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
10632 self.above[mi_c + cell][plane] = state;
10633 }
10634 }
10635
10636 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
10637 /// r1): the above context spans the unit's width, the left context its
10638 /// height, which for a square unit is the same loop it always was.
10639 fn record_mi_luma_rect(
10640 &mut self,
10641 (mi_r, mi_c): (usize, usize),
10642 w_px: usize,
10643 h_px: usize,
10644 grid: &[i32],
10645 ) {
10646 let state = neighbour_state(grid);
10647 if crate::envflags::env_flag!("EC_ECPUB") {
10648 eprintln!(
10649 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
10650 state.level
10651 );
10652 }
10653 for cell in 0..h_px / MI {
10654 if mi_r + cell < self.mi_rows {
10655 self.left[mi_r + cell][0] = state;
10656 }
10657 }
10658 for cell in 0..w_px / MI {
10659 if mi_c + cell < self.mi_cols {
10660 self.above[mi_c + cell][0] = state;
10661 }
10662 }
10663 }
10664
10665 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
10666 /// block whose luma was decoded as several transform units through
10667 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
10668 /// whole-block luma write -- everything [`Self::record`] does except
10669 /// plane 0, which is already correct per-TU by the time this runs.
10670 fn record_split_luma(
10671 &mut self,
10672 at: (usize, usize),
10673 side: usize,
10674 mode: usize,
10675 uv_mode: usize,
10676 chroma_grids: [&[i32]; 2],
10677 ) {
10678 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
10679 }
10680
10681 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
10682 /// extents in pixels (lane-rectsplit r1), the same relationship
10683 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
10684 /// luma transform split into several square units needs exactly this
10685 /// bookkeeping, at its own true rectangular extents.
10686 fn record_split_luma_rect(
10687 &mut self,
10688 at: (usize, usize),
10689 w: usize,
10690 h: usize,
10691 mode: usize,
10692 uv_mode: usize,
10693 chroma_grids: [&[i32]; 2],
10694 ) {
10695 let (r, c) = at;
10696 self.record_split_luma_rect_mi(
10697 (r * (SUB / MI), c * (SUB / MI)),
10698 w,
10699 h,
10700 mode,
10701 uv_mode,
10702 chroma_grids,
10703 );
10704 }
10705
10706 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
10707 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
10708 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
10709 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
10710 /// convention [`decode_block_rect4`] already established for 1:4 strips.
10711 fn record_split_luma_rect_mi(
10712 &mut self,
10713 at_mi: (usize, usize),
10714 w: usize,
10715 h: usize,
10716 mode: usize,
10717 uv_mode: usize,
10718 chroma_grids: [&[i32]; 2],
10719 ) {
10720 self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10721 let (mi_r, _) = at_mi;
10722 let (w_mi, h_mi) = (w / MI, h / MI);
10723 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10724 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10725 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
10726 let plane = plane_idx + 1;
10727 let state = neighbour_state(grid);
10728 for cell in 0..h_mi {
10729 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
10730 self.left[mi_r + cell][plane] = state;
10731 }
10732 }
10733 for cell in 0..w_mi {
10734 if cell < w_mi.min(bound_w.saturating_sub(at_mi.1)) {
10735 self.above[at_mi.1 + cell][plane] = state;
10736 }
10737 }
10738 }
10739 }
10740
10741 /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half,
10742 /// without the per-plane coefficient stamp -- see
10743 /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block
10744 /// must not take the whole-block stamp.
10745 fn record_split_luma_rect_mi_modes(
10746 &mut self,
10747 at_mi: (usize, usize),
10748 w: usize,
10749 h: usize,
10750 mode: usize,
10751 uv_mode: usize,
10752 ) {
10753 let (mi_r, mi_c) = at_mi;
10754 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10755 for cell in 0..w.div_ceil(SUB) {
10756 if c + cell >= self.above_mode.len() {
10757 break;
10758 }
10759 self.above_mode[c + cell] = mode;
10760 self.above_uv_mode[c + cell] = uv_mode;
10761 self.above_side[c + cell] = w;
10762 }
10763 for cell in 0..h.div_ceil(SUB) {
10764 if r + cell >= self.left_mode.len() {
10765 break;
10766 }
10767 self.left_mode[r + cell] = mode;
10768 self.left_uv_mode[r + cell] = uv_mode;
10769 self.left_side[r + cell] = h;
10770 }
10771
10772 let (w_mi, h_mi) = (w / MI, h / MI);
10773 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
10774 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
10775 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10776 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10777 }
10778}
10779
10780/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
10781/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
10782/// exactly — including its skip context, which the real key-frame writer
10783/// always writes at a fixed context of zero (it never tracks a neighbour-based
10784/// one for intra blocks; that is the inter-frame writer's rule instead).
10785/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
10786/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
10787/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
10788/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
10789/// plain DC chroma.
10790/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
10791/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
10792/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
10793/// instead (the defect commit 1a89ed9 fixed at the square sites).
10794pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
10795 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
10796 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
10797}
10798
10799/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
10800/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
10801/// bound (spec `filter_intra_mode_info` never reads a symbol there).
10802pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
10803 match side {
10804 4 => Some(0),
10805 8 => Some(1),
10806 16 => Some(2),
10807 32 => Some(3),
10808 _ => None,
10809 }
10810}
10811
10812/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
10813/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
10814/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
10815/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
10816fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
10817 match (bw, bh) {
10818 (32, 16) => Some(4),
10819 (16, 32) => Some(5),
10820 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
10821 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
10822 // here dropped that symbol on every DC_PRED strip of that size and
10823 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
10824 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
10825 (16, 8) => Some(6),
10826 (8, 16) => Some(7),
10827 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
10828 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
10829 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
10830 (4, 8) => Some(8),
10831 (8, 4) => Some(9),
10832 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
10833 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
10834 // `use_filter_intra` symbol on those strips although aomenc writes
10835 // one for every DC_PRED block of that shape with
10836 // `--enable-filter-intra=1` (its default), silently desyncing the
10837 // tile (class symbol-consumption-gap).
10838 (32, 8) => Some(10),
10839 (8, 32) => Some(11),
10840 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
10841 // strips), rows 17/16 of `default_filter_intra_cdfs`.
10842 (16, 4) => Some(12),
10843 (4, 16) => Some(13),
10844 _ if bw == bh => filter_intra_size_class(bw),
10845 _ => None,
10846 }
10847}
10848
10849/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
10850/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
10851/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
10852/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
10853/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
10854pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
10855 palette_bsize_ctx_wh(side, side)
10856}
10857
10858/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
10859/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
10860/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
10861/// for ANY bsize, not just the square ones a hand-picked table happened to
10862/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
10863/// row breaks the moment its indexing field moves off the diagonal, and a
10864/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
10865/// block dimension is a power of two, so `bw*bh` always is too and
10866/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
10867/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
10868fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
10869 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
10870 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
10871 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
10872 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
10873 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
10874 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
10875 if bw > 64 || bh > 64 || bw * bh < 64 {
10876 return None;
10877 }
10878 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
10879}
10880
10881/// A just-decoded palette-Y block's own size, base colours (only the first
10882/// `size` entries are real), and per-pixel colour-index map (`side*side`,
10883/// row-major, each entry `< size`).
10884struct PaletteY {
10885 size: usize,
10886 colors: [u16; 8],
10887 map: Vec<u8>,
10888}
10889
10890/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
10891/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
10892/// shared between U and V, both co-located after 4:2:0 subsampling) plus
10893/// each plane's own base colours.
10894struct PaletteUv {
10895 size: usize,
10896 u_colors: [u16; 8],
10897 v_colors: [u16; 8],
10898 map: Vec<u8>,
10899}
10900
10901/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
10902/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
10903/// `get_unsigned_bits`, which is the same formula): smallest `n` with
10904/// `2^n >= x`, `0` for `x <= 1`.
10905pub(crate) fn ceil_log2(x: u32) -> u32 {
10906 if x < 2 {
10907 0
10908 } else {
10909 32 - (x - 1).leading_zeros()
10910 }
10911}
10912
10913/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
10914/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
10915fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
10916 let l = ceil_log2(n as u32);
10917 let m = (1usize << l) - n;
10918 let v = dec.literal(l - 1) as usize;
10919 if v < m {
10920 v
10921 } else {
10922 (v << 1) - m + dec.literal(1) as usize
10923 }
10924}
10925
10926/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
10927/// colours (already-known, from the above/left neighbours) with the
10928/// ascending `transmitted` ones (delta-coded off the wire) back into one
10929/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
10930/// value picks the cached copy first, matching the C `<=`.
10931fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
10932 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
10933 let (mut ci, mut ti) = (0, 0);
10934 while ci < cached.len() && ti < transmitted.len() {
10935 if cached[ci] <= transmitted[ti] {
10936 out.push(cached[ci]);
10937 ci += 1;
10938 } else {
10939 out.push(transmitted[ti]);
10940 ti += 1;
10941 }
10942 }
10943 out.extend_from_slice(&cached[ci..]);
10944 out.extend_from_slice(&transmitted[ti..]);
10945 out
10946}
10947
10948/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
10949/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
10950/// each delta's width, the `range` bound and the clamp) is sized by
10951/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
10952/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
10953/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
10954/// the msac range, so a cross-decoder range ladder stays bit-identical
10955/// through the whole miscount -- only the decoded VALUE differs (class
10956/// `compare-range-not-tell`'s blind spot). (this
10957/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
10958/// (one flag bit each, in cache order), then delta-codes the remainder
10959/// (first value raw, each following delta `>= 1` off a shrinking bit width),
10960/// and merges the two ascending lists back together.
10961fn read_palette_colors_y(
10962 dec: &mut SymbolDecoder,
10963 n: usize,
10964 cache: &[u16],
10965 fctx: &crate::decode::FrameCtx,
10966) -> [u16; 8] {
10967 let mut cached = Vec::with_capacity(n);
10968 for &c in cache {
10969 if cached.len() >= n {
10970 break;
10971 }
10972 if dec.literal(1) == 1 {
10973 cached.push(c);
10974 }
10975 }
10976 let bd = u32::from(bit_depth(fctx));
10977 let max_val = (1i32 << bd) - 1;
10978 let mut colors = [0u16; 8];
10979 let n_cached = cached.len();
10980 if n_cached < n {
10981 let mut transmitted = Vec::with_capacity(n - n_cached);
10982 let first = dec.literal(bd) as u16;
10983 transmitted.push(first);
10984 if n_cached + 1 < n {
10985 let min_bits = bd - 3;
10986 let mut bits = min_bits + dec.literal(2);
10987 let mut range = (1i32 << bd) - i32::from(first) - 1;
10988 for _ in (n_cached + 1)..n {
10989 let delta = dec.literal(bits) as i32 + 1;
10990 let prev = *transmitted.last().unwrap();
10991 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
10992 range -= i32::from(val) - i32::from(prev);
10993 bits = bits.min(ceil_log2(range.max(0) as u32));
10994 transmitted.push(val);
10995 }
10996 }
10997 let merged = merge_colors(&transmitted, &cached);
10998 colors[..n].copy_from_slice(&merged);
10999 } else {
11000 colors[..n].copy_from_slice(&cached[..n]);
11001 }
11002 colors
11003}
11004
11005/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
11006/// `bit_depth` (see [`read_palette_colors_y`]): U reads
11007/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
11008/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
11009/// unbiased by `+1` -- both differences from Y's own reader, matching the C
11010/// side by side). V never uses a cache: a leading bit picks either `n` raw
11011/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
11012/// rather than clamp.
11013fn read_palette_colors_uv(
11014 dec: &mut SymbolDecoder,
11015 n: usize,
11016 cache: &[u16],
11017 fctx: &crate::decode::FrameCtx,
11018) -> ([u16; 8], [u16; 8]) {
11019 let mut cached = Vec::with_capacity(n);
11020 for &c in cache {
11021 if cached.len() >= n {
11022 break;
11023 }
11024 if dec.literal(1) == 1 {
11025 cached.push(c);
11026 }
11027 }
11028 let bd = u32::from(bit_depth(fctx));
11029 let max_val = 1i32 << bd;
11030 let mut u_colors = [0u16; 8];
11031 let n_cached = cached.len();
11032 if n_cached < n {
11033 let mut transmitted = Vec::with_capacity(n - n_cached);
11034 let first = dec.literal(bd) as u16;
11035 transmitted.push(first);
11036 if n_cached + 1 < n {
11037 let min_bits = bd - 3;
11038 let mut bits = min_bits + dec.literal(2);
11039 let mut range = max_val - i32::from(first);
11040 for _ in (n_cached + 1)..n {
11041 let delta = dec.literal(bits) as i32;
11042 let prev = *transmitted.last().unwrap();
11043 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
11044 range -= i32::from(val) - i32::from(prev);
11045 bits = bits.min(ceil_log2(range.max(0) as u32));
11046 transmitted.push(val);
11047 }
11048 }
11049 let merged = merge_colors(&transmitted, &cached);
11050 u_colors[..n].copy_from_slice(&merged);
11051 } else {
11052 u_colors[..n].copy_from_slice(&cached[..n]);
11053 }
11054 let mut v_colors = [0u16; 8];
11055 if dec.literal(1) == 1 {
11056 let min_bits_v = bd - 4;
11057 let bits = min_bits_v + dec.literal(2);
11058 v_colors[0] = dec.literal(bd) as u16;
11059 for i in 1..n {
11060 let mut delta = dec.literal(bits) as i32;
11061 if delta != 0 && dec.literal(1) == 1 {
11062 delta = -delta;
11063 }
11064 let mut val = i32::from(v_colors[i - 1]) + delta;
11065 if val < 0 {
11066 val += max_val;
11067 }
11068 if val >= max_val {
11069 val -= max_val;
11070 }
11071 v_colors[i] = val as u16;
11072 }
11073 } else {
11074 for i in 0..n {
11075 v_colors[i] = dec.literal(bd) as u16;
11076 }
11077 }
11078 (u_colors, v_colors)
11079}
11080
11081/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
11082/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
11083/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
11084const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
11085
11086/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
11087/// map's own per-pixel context and colour-order permutation, from the
11088/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
11089/// selection sort). `map`'s stride is `side` (this decoder never crops a
11090/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
11091/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
11092/// actual colour index to store.
11093pub(crate) fn palette_color_index_context(
11094 map: &[u8],
11095 side: usize,
11096 row: usize,
11097 col: usize,
11098 n: usize,
11099) -> (usize, [u8; 8]) {
11100 let left = if col >= 1 {
11101 Some(map[row * side + col - 1])
11102 } else {
11103 None
11104 };
11105 let up_left = if col >= 1 && row >= 1 {
11106 Some(map[(row - 1) * side + col - 1])
11107 } else {
11108 None
11109 };
11110 let up = if row >= 1 {
11111 Some(map[(row - 1) * side + col])
11112 } else {
11113 None
11114 };
11115 let mut scores = [0i32; 8];
11116 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
11117 if let Some(v) = neighbour {
11118 scores[v as usize] += weight;
11119 }
11120 }
11121 let mut color_order = [0u8; 8];
11122 for i in 0..8 {
11123 color_order[i] = i as u8;
11124 }
11125 for i in 0..3 {
11126 let mut max = scores[i];
11127 let mut max_idx = i;
11128 for j in (i + 1)..n {
11129 if scores[j] > max {
11130 max = scores[j];
11131 max_idx = j;
11132 }
11133 }
11134 if max_idx != i {
11135 let max_score = scores[max_idx];
11136 let max_color = color_order[max_idx];
11137 for k in (i + 1..=max_idx).rev() {
11138 scores[k] = scores[k - 1];
11139 color_order[k] = color_order[k - 1];
11140 }
11141 scores[i] = max_score;
11142 color_order[i] = max_color;
11143 }
11144 }
11145 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
11146 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
11147 (ctx as usize, color_order)
11148}
11149
11150/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
11151/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
11152/// cut by the frame's bottom or right mi edge codes its colour-index map only
11153/// over this part and replicates it outward -- reading the full `bw x bh` grid
11154/// consumed symbols libaom never wrote and desynced the rest of the tile
11155/// (lane-svtinter; class map-read-past-frame-edge).
11156fn palette_onscreen(
11157 mi_r: usize,
11158 mi_c: usize,
11159 bw: usize,
11160 bh: usize,
11161 fctx: &crate::decode::FrameCtx,
11162) -> (usize, usize) {
11163 // lane-palw: the ENCODER's own in-process reconstruct runs on a
11164 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
11165 // frame encoders publish the header's mi dims onto it themselves
11166 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
11167 // clamp and `tile::write_color_index_map`'s now agree there too.
11168 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
11169 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
11170}
11171
11172/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
11173/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
11174/// compute the same on-screen extent or the decoder reads a different number
11175/// of symbols than the encoder wrote.
11176pub(crate) fn palette_onscreen_dims(
11177 mi_r: usize,
11178 mi_c: usize,
11179 bw: usize,
11180 bh: usize,
11181 (mi_rows, mi_cols): (usize, usize),
11182) -> (usize, usize) {
11183 (
11184 bw.min(mi_cols.saturating_sub(mi_c) * MI),
11185 bh.min(mi_rows.saturating_sub(mi_r) * MI),
11186 )
11187}
11188
11189/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
11190/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
11191/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
11192/// together or a cut 8-wide block reads its chroma map at the wrong width.
11193/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
11194/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
11195/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
11196pub(crate) fn palette_onscreen_uv(
11197 luma: (usize, usize),
11198 on: (usize, usize),
11199 chroma: (usize, usize),
11200 ss: (usize, usize),
11201) -> (usize, usize) {
11202 (
11203 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
11204 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
11205 )
11206}
11207
11208/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
11209/// map's wavefront decode over a `side x side` grid, read over the on-screen
11210/// `on_side x on_side` corner (see [`palette_onscreen`]).
11211fn decode_color_index_map(
11212 dec: &mut SymbolDecoder,
11213 cdfs: &mut Cdfs,
11214 n: usize,
11215 side: usize,
11216 on: (usize, usize),
11217 uv: bool,
11218) -> Vec<u8> {
11219 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
11220}
11221
11222/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
11223/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
11224/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
11225/// independently rather than one shared `side` -- the square call above is
11226/// just `bw == bh`.
11227fn decode_color_index_map_wh(
11228 dec: &mut SymbolDecoder,
11229 cdfs: &mut Cdfs,
11230 n: usize,
11231 bw: usize,
11232 bh: usize,
11233 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
11234 on: (usize, usize),
11235 uv: bool,
11236) -> Vec<u8> {
11237 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
11238 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11239 if on_bw < bw || on_bh < bh {
11240 hit!(PALETTE_ONSCREEN_CUT_HITS);
11241 }
11242 let mut map = vec![0u8; bw * bh];
11243 if trace {
11244 let (rng, _) = dec.debug_state();
11245 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
11246 }
11247 map[0] = read_uniform(dec, n) as u8;
11248 if trace {
11249 let (rng, _) = dec.debug_state();
11250 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11251 }
11252 for i in 1..(on_bw + on_bh - 1) {
11253 let j_hi = i.min(on_bw - 1);
11254 let j_lo = i.saturating_sub(on_bh - 1);
11255 for j in (j_lo..=j_hi).rev() {
11256 let row = i - j;
11257 let col = j;
11258 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11259 if trace {
11260 let (rng, _) = dec.debug_state();
11261 let row_cdf = if uv {
11262 &cdfs.palette_uv_color_index[n - 2][ctx]
11263 } else {
11264 &cdfs.palette_y_color_index[n - 2][ctx]
11265 };
11266 eprintln!(
11267 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11268 row_cdf[0], row_cdf[n]
11269 );
11270 }
11271 let symbol = if uv {
11272 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11273 } else {
11274 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11275 };
11276 map[row * bw + col] = color_order[symbol];
11277 if trace {
11278 let (rng, _) = dec.debug_state();
11279 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11280 }
11281 }
11282 }
11283 palette_replicate(&mut map, bw, bh, on);
11284 map
11285}
11286
11287/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11288/// last on-screen column then the last on-screen row are replicated over the
11289/// off-screen remainder, so the prediction still covers the whole block. The
11290/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11291/// so the pixels it prices and reconstructs are the ones the on-screen
11292/// symbols it writes really decode to.
11293pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11294 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11295 for row in 0..on_bh {
11296 let last = map[row * bw + on_bw - 1];
11297 map[row * bw + on_bw..row * bw + bw].fill(last);
11298 }
11299 for row in on_bh..bh {
11300 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11301 }
11302}
11303
11304/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11305/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11306/// size class comes from [`filter_intra_size_class_rect`] instead of the
11307/// square-only [`filter_intra_size_class`], and the palette read (when
11308/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11309/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11310/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11311/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11312#[allow(clippy::too_many_arguments)]
11313fn read_intra_mode_rect(
11314 dec: &mut SymbolDecoder,
11315 cdfs: &mut Cdfs,
11316 above_mode: usize,
11317 left_mode: usize,
11318 cfl: bool,
11319 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11320 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11321 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11322 // chroma is coded once, on the closing strip). Every other caller is a
11323 // block big enough to own its chroma and passes `true`.
11324 has_chroma: bool,
11325 bw: usize,
11326 bh: usize,
11327 enable_filter_intra: bool,
11328 skip_ctx: usize,
11329 allow_screen_content_tools: bool,
11330 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11331 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11332 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11333 palette: Option<(usize, &[u16])>,
11334 palette_uv_cache: &[u16],
11335 mi_r: usize,
11336 mi_c: usize,
11337 fctx: &crate::decode::FrameCtx,
11338) -> Result<(
11339 bool,
11340 usize,
11341 i32,
11342 usize,
11343 i32,
11344 Option<(i32, i32)>,
11345 Option<usize>,
11346 Option<PaletteY>,
11347 Option<PaletteUv>,
11348 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11349 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11350 // straight out of `read_intra_frame_mode_info` then, so every later field
11351 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11352 // no filter intra). A caller that can reconstruct intrabc at its shape
11353 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11354 // name with the same string it always did.
11355 Option<(i32, i32)>,
11356)> {
11357 // lane-av1mono: libaom guards every chroma symbol read with
11358 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11359 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11360 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11361 // into the same `has_chroma` this reader already gates on.
11362 let has_chroma = has_chroma && !mono(fctx);
11363 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11364 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11365 if ec_istep {
11366 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11367 // (decodemv.c:818), printed at the same point: before the first
11368 // mode-info symbol of the block, so a cross-decoder range ladder can
11369 // be keyed on the BLOCK, not just on the symbol sequence.
11370 eprintln!(
11371 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11372 enable_filter_intra as i32,
11373 filter_intra_size_class_rect(bw, bh),
11374 dec.debug_state().0
11375 );
11376 }
11377 macro_rules! istep {
11378 ($name:literal, $val:expr) => {
11379 if ec_istep {
11380 let (rng, _) = dec.debug_state();
11381 eprintln!(
11382 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11383 $name, $val
11384 );
11385 }
11386 };
11387 }
11388 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11389 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11390 // the one point every rect caller routes through, so no call site can
11391 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11392 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11393 let cfl = if cfl && bw.max(bh) > 32 {
11394 hit!(NOCFL_UV_MODE_HITS);
11395 false
11396 } else {
11397 cfl
11398 };
11399 // lane-intra14 r1: on the INTER block path everything up to and including
11400 // `is_inter` was already read by [`decode_inter_block`], so this reader
11401 // starts at the mode syntax with the `skip` that caller read.
11402 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11403 let skip = if let Some((_, skip)) = inter {
11404 skip
11405 } else {
11406 // Same `intra_segment_id` placement as the square reader above.
11407 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11408 if seg_id_pre_skip(fctx) {
11409 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11410 }
11411 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11412 istep!("skip", skip as i32);
11413 if !seg_id_pre_skip(fctx) {
11414 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11415 }
11416 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11417 istep!("cdef", 0);
11418 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11419 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11420 // `false`.
11421 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11422 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11423 istep!("dq", 0);
11424 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11425 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11426 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11427 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11428 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11429 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11430 // decoder at the FIRST symbol of the first rect block of every
11431 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11432 // block at this shape is out of scope, so the flag is consumed and
11433 // refused by name when it fires.
11434 if allow_intrabc_frame(fctx) {
11435 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11436 hit!(RECT_INTRABC_READS);
11437 istep!("intrabc", use_intrabc as i32);
11438 if use_intrabc {
11439 hit!(INTRABC_HITS);
11440 // libaom `read_intrabc_info`: the DV read, then an immediate
11441 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
11442 // no angle deltas, no palette, no filter intra. The caller owns
11443 // the reconstruction at its own shape.
11444 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
11445 return Ok((
11446 skip,
11447 DC_PRED,
11448 0,
11449 DC_PRED,
11450 0,
11451 None,
11452 None,
11453 None,
11454 None,
11455 Some(dv),
11456 ));
11457 }
11458 }
11459 skip
11460 };
11461 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
11462 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
11463 // off `kf_y_mode_cdf[above][left]`).
11464 let mode = if let Some((size_group, _)) = inter {
11465 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
11466 dec.symbol(&mut cdfs.y_mode[size_group])
11467 } else {
11468 let above_ctx = INTRA_MODE_CTX[above_mode];
11469 let left_ctx = INTRA_MODE_CTX[left_mode];
11470 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
11471 };
11472 istep!("mode", mode as i32);
11473 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11474 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11475 } else {
11476 0
11477 };
11478 istep!("angle_y", angle_delta_y);
11479 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
11480 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
11481 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
11482 // here, from the block's own size, is the single point every caller routes
11483 // through -- a caller passing `true` for a >32 strip used to pick the
11484 // 14-symbol CFL CDF, same value but a different range (class
11485 // wrong-alphabet-same-value).
11486 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
11487 let uv_mode = if !has_chroma {
11488 DC_PRED
11489 } else if cfl {
11490 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11491 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11492 } else {
11493 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11494 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11495 };
11496 istep!("uv_mode", uv_mode as i32);
11497 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
11498 Some(read_cfl_alphas(dec, cdfs))
11499 } else {
11500 None
11501 };
11502 if has_chroma && (9..=12).contains(&uv_mode) {
11503 hit!(SMOOTH_UV_HITS);
11504 }
11505 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
11506 hit!(DIRECTIONAL_UV_HITS);
11507 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11508 } else {
11509 0
11510 };
11511 istep!("angle_uv", angle_delta_uv);
11512 if angle_delta_uv != 0 {
11513 hit!(UV_ANGLE_DELTA_HITS);
11514 }
11515 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
11516 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
11517 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
11518 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
11519 // colours only here, the colour-index maps deferred past `filter_intra`
11520 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
11521 // runs from the caller, after the whole mode-info read).
11522 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11523 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11524 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
11525 // r6: this is the exact site the removed blanket refusal used to
11526 // guard -- reached for EVERY rect strip in a screen-content frame,
11527 // independent of whether the block ends up using a palette.
11528 hit!(RECT_SCREEN_CONTENT_HITS);
11529 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11530 let use_palette_y =
11531 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11532 if use_palette_y {
11533 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11534 let colors = read_palette_colors_y(dec, n, cache, fctx);
11535 palette_y_pending = Some((n, colors));
11536 }
11537 let palette_uv_mode_ctx = usize::from(use_palette_y);
11538 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
11539 if has_chroma
11540 && uv_mode == DC_PRED
11541 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
11542 {
11543 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11544 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
11545 palette_uv_pending = Some((n, u_colors, v_colors));
11546 }
11547 }
11548 let mut filter_intra = None;
11549 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11550 let (rng, _) = dec.debug_state();
11551 eprintln!(
11552 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
11553 class={:?} rng={rng}",
11554 enable_filter_intra as i32,
11555 filter_intra_size_class_rect(bw, bh)
11556 );
11557 }
11558 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
11559 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
11560 if mode == DC_PRED
11561 && enable_filter_intra
11562 && palette_y_pending.is_none()
11563 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11564 {
11565 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11566 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11567 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
11568 }
11569 istep!("use_filter_intra", use_filter_intra as i32);
11570 if use_filter_intra {
11571 hit!(FILTER_INTRA_HITS);
11572 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11573 istep!("filter_intra_mode", fi_mode as i32);
11574 filter_intra = Some(fi_mode);
11575 }
11576 }
11577 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
11578 // same order as [`read_intra_mode`]'s own square path.
11579 let palette_y = palette_y_pending.map(|(n, colors)| {
11580 let map = decode_color_index_map_wh(
11581 dec,
11582 cdfs,
11583 n,
11584 bw,
11585 bh,
11586 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11587 false,
11588 );
11589 hit!(PALETTE_HITS);
11590 hit!(PALETTE_RECT_HITS);
11591 PaletteY {
11592 size: n,
11593 colors,
11594 map,
11595 }
11596 });
11597 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11598 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
11599 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
11600 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
11601 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
11602 // chroma palette and desynced the tile from there.
11603 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11604 let on = palette_onscreen_uv(
11605 (bw, bh),
11606 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11607 (cw, ch),
11608 (ss_x(fctx), ss_y(fctx)),
11609 );
11610 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11611 hit!(PALETTE_UV_HITS);
11612 PaletteUv {
11613 size: n,
11614 u_colors,
11615 v_colors,
11616 map,
11617 }
11618 });
11619 Ok((
11620 skip,
11621 mode,
11622 angle_delta_y,
11623 uv_mode,
11624 angle_delta_uv,
11625 alpha,
11626 filter_intra,
11627 palette_y,
11628 palette_uv,
11629 None,
11630 ))
11631}
11632
11633/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
11634/// at the strip's REAL mi position. `av1_get_palette_cache` reads
11635/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
11636/// block, so each strip owns its own rows and columns and no aliasing rule
11637/// is needed (lane-kf900 r6).
11638#[allow(clippy::too_many_arguments)]
11639fn record_strip_palette(
11640 n: &mut Neighbours,
11641 mi: (usize, usize),
11642 bw: usize,
11643 bh: usize,
11644 y_size: usize,
11645 y_colors: [u16; 8],
11646 uv_size: usize,
11647 uv_colors: [u16; 8],
11648) {
11649 let (r, c) = mi;
11650 // lane-t900 r23 rung: every publication of a block's palette state into
11651 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
11652 // path left a stale `left_palette_size` behind when
11653 // `av1_get_palette_mode_ctx` disagrees with libaom's.
11654 if crate::envflags::env_flag!("EC_PALPUB") {
11655 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
11656 }
11657 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
11658 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
11659 // existed because the 16px [`SUB`] cell held one slot for all the strips
11660 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
11661 // real neighbour leaf 1 reads.
11662 {
11663 for cell in 0..(bw / MI).max(1) {
11664 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
11665 *e = y_size as u8;
11666 n.above_palette_uv_size[c + cell] = uv_size as u8;
11667 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
11668 // colours of a size-0 neighbour are never read.
11669 if y_size > 0 {
11670 n.above_palette_colors[c + cell] = y_colors;
11671 }
11672 if uv_size > 0 {
11673 n.above_palette_uv_colors[c + cell] = uv_colors;
11674 }
11675 }
11676 }
11677 }
11678 {
11679 for cell in 0..(bh / MI).max(1) {
11680 if n.left_palette_size.get(r + cell).is_none() {
11681 break;
11682 }
11683 n.left_palette_size[r + cell] = y_size as u8;
11684 n.left_palette_uv_size[r + cell] = uv_size as u8;
11685 if y_size > 0 {
11686 n.left_palette_colors[r + cell] = y_colors;
11687 }
11688 if uv_size > 0 {
11689 n.left_palette_uv_colors[r + cell] = uv_colors;
11690 }
11691 }
11692 }
11693}
11694
11695/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
11696fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
11697 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
11698 i32::from(y.data[ly * y.width + lx])
11699 })
11700}
11701
11702/// Everything a rect strip already read out of the stream before its luma
11703/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
11704/// (nine values that would otherwise be nine more parameters).
11705struct RectStripModes {
11706 skip: bool,
11707 mode: usize,
11708 angle_delta_y: i32,
11709 uv_predict_mode: usize,
11710 angle_delta_uv: i32,
11711 alpha: Option<(i32, i32)>,
11712 filter_intra: Option<usize>,
11713 smooth_neighbor: bool,
11714 smooth_neighbor_uv: bool,
11715 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
11716 /// mapped through the colour table), sliced per transform unit below --
11717 /// palette prediction reads no edge pixels, so a unit's slice of the
11718 /// whole-block map IS its prediction. Without this a palette strip whose
11719 /// transform splits predicted DC and came out flat grey while the entropy
11720 /// stream stayed in sync (the coefficients are read either way).
11721 palette_y: Option<Vec<u16>>,
11722 /// As `palette_y`, for the un-split chroma transform (U, V).
11723 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
11724}
11725
11726/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
11727/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
11728/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
11729/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
11730/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
11731/// TX_32X16`) and only the second reaches a square -- the reason
11732/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
11733/// already square) mis-tiled 1:4 strips.
11734fn depth_to_tx_wh(
11735 bw: usize,
11736 bh: usize,
11737 depth: usize,
11738 fctx: &crate::decode::FrameCtx,
11739) -> (usize, usize) {
11740 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
11741 // `read_tx_size`: the lossless early return comes before
11742 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
11743 if lossless(fctx) {
11744 return (4, 4);
11745 }
11746 let (mut w, mut h) = (bw.min(64), bh.min(64));
11747 for _ in 0..depth {
11748 match w.cmp(&h) {
11749 std::cmp::Ordering::Greater => w /= 2,
11750 std::cmp::Ordering::Less => h /= 2,
11751 std::cmp::Ordering::Equal => {
11752 w /= 2;
11753 h /= 2;
11754 }
11755 }
11756 }
11757 (w, h)
11758}
11759
11760/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
11761/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
11762/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
11763/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
11764/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
11765/// 2-px-wide area is not a transform shape. The strip pairs with its
11766/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
11767/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
11768/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
11769/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
11770/// the entropy context on the floored cell. Returns
11771/// `(pair block width, pair block height, write anchor x, entropy mi column)`
11772/// for that pair, or `None` when the strip keeps its own plane block at its
11773/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
11774/// 2 px wide) and every 4:2:2 strip of 8 px or more.
11775fn chroma422_pair_plane(
11776 ss_x: bool,
11777 ss_y: bool,
11778 mi_col: usize,
11779 bw: usize,
11780 bh: usize,
11781) -> Option<(usize, usize, usize, usize)> {
11782 if ss_x && !ss_y && (bw >> 1) == 2 {
11783 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
11784 } else {
11785 None
11786 }
11787}
11788
11789/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
11790/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
11791/// rect path here refused by name until now ("per-unit rect prediction is not
11792/// ported").
11793///
11794/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
11795/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
11796/// strip the very first step already lands on a SQUARE transform
11797/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
11798/// every further step halves a square) -- so each unit is square and reads
11799/// through the ordinary square [`read_plane`]. What is genuinely rectangular
11800/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
11801/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
11802/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
11803/// split by luma's depth.
11804///
11805/// Each unit predicts off whatever the earlier units of this same block
11806/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
11807/// inside `av1_foreach_transformed_block`, raster order), which is exactly
11808/// what predicting the whole strip in one shot got wrong.
11809#[allow(clippy::too_many_arguments)]
11810fn decode_rect_split(
11811 dec: &mut SymbolDecoder,
11812 cdfs: &mut Cdfs,
11813 neighbours: &mut Neighbours,
11814 at_mi: (usize, usize),
11815 bw: usize,
11816 bh: usize,
11817 // The transform unit's own width and height in pixels. Square for every
11818 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
11819 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
11820 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
11821 tx_w: usize,
11822 tx_h: usize,
11823 m: &RectStripModes,
11824 y: &mut PlaneBuf<'static>,
11825 u: &mut PlaneBuf<'static>,
11826 v: &mut PlaneBuf<'static>,
11827 base_q_idx: u8,
11828 reduced_tx_set: bool,
11829 fctx: &crate::decode::FrameCtx,
11830) -> Result<()> {
11831 let (mi_r, mi_c) = at_mi;
11832 let (px, py) = (mi_c * MI, mi_r * MI);
11833 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
11834 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
11835 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
11836 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
11837 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
11838 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
11839 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
11840 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
11841 // measurement). The plane is still coded -- `decode_token_recon_block`
11842 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
11843 // 4x8 rect units, plane-major.
11844 let chroma_422_oob = ss_x(fctx) == 1
11845 && ss_y(fctx) == 0
11846 && matches!(
11847 (bw, bh),
11848 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
11849 );
11850 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
11851 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
11852 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
11853 // plane is then `(4, chroma_h)` written at the FLOORED cell
11854 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
11855 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
11856 // the same walk the (8, 32) class takes). The lossless raster arm keeps
11857 // the strip's own geometry: no caller of this function can present a
11858 // 4-wide strip yet (the enumeration test pins the five callers at
11859 // `8 <= min`), and the skip/tiled arms are the routes a future caller
11860 // needs.
11861 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
11862 let chroma_422_pair_wide = chroma422_pair.is_some();
11863 let (chroma_block_w, chroma_block_h, chroma_x) =
11864 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
11865 // The chroma transform is picked before any symbol is read, so an
11866 // unsupported chroma shape refuses before this strip desyncs the tile.
11867 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
11868 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
11869 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
11870 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
11871 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
11872 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
11873 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
11874 // squares a rect transform down to a CDF set by
11875 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
11876 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
11877 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
11878 // paths already prove for these same shapes.
11879 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
11880 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
11881 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
11882 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
11883 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
11884 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
11885 _ => None,
11886 };
11887 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
11888 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
11889 // below; everything else still needs a single-unit table.
11890 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
11891 // halves only the width, so a rect luma strip codes a SQUARE chroma block
11892 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
11893 // rect strip's chroma is itself rect, so the square rows are unreachable
11894 // there and cannot change their results.
11895 // lane-av1-422blockhalf: the tiled arms below handle every shape this
11896 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
11897 // diagnostic names only the shapes that would actually refuse -- it used
11898 // to fire for every tiled square too (the parent lane's `chroma=8x8`
11899 // rows) and sent the next lane chasing handled shapes.
11900 let chroma_tiled = chroma_422_pair_wide
11901 || chroma_422_oob
11902 || matches!(
11903 (chroma_w, chroma_h),
11904 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
11905 );
11906 if !m.skip {
11907 if let Some(i) = match (chroma_w, chroma_h) {
11908 (32, 8) => Some(0),
11909 (8, 32) => Some(1),
11910 (8, 4) => Some(2),
11911 (4, 8) => Some(3),
11912 _ => None,
11913 } {
11914 hit_do! {
11915 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
11916 let mut hits = c.get();
11917 hits[i] += 1;
11918 c.set(hits);
11919 });
11920 }
11921 }
11922 if !m.skip && chroma.is_none() && !chroma_tiled {
11923 // Diagnostic for the next caller that lands here (class
11924 // refusal-names-a-correlate: the message names the tool, not the
11925 // shape); the refusal below keeps its inventory-pinned wording.
11926 eprintln!(
11927 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
11928 chroma={chroma_w}x{chroma_h}"
11929 );
11930 }
11931 }
11932 // lane-rectsplit r2 (verifier finding): with both callers wired
11933 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
11934 // 64x32/32x64) every shape that reaches here has a table above, so this
11935 // arm is UNREACHABLE today. It stays as the shape guard for the next
11936 // caller -- a new strip size would otherwise hit the `expect` below and
11937 // panic instead of refusing by name -- and so stays in
11938 // `refusal_inventory::REFUSALS`.
11939 if !m.skip && chroma.is_none() && !chroma_tiled {
11940 return Err(unsupported(
11941 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
11942 ));
11943 }
11944 hit!(RECT_SPLIT_TX_HITS);
11945 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
11946 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
11947 }
11948 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
11949 // A square unit reads through the ordinary square [`read_plane`]; a rect
11950 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
11951 // the very tables the unsplit 16x8/32x16 paths use.
11952 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
11953 (w, h) if w == h => None,
11954 (16, 8) | (8, 16) => Some((
11955 if reduced_tx_set {
11956 TxbSet::LumaRect16x8
11957 } else {
11958 TxbSet::LumaRect16x8Set1
11959 },
11960 if tx_w == 16 {
11961 &SCAN_16X8[..]
11962 } else {
11963 &SCAN_8X16[..]
11964 },
11965 )),
11966 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
11967 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
11968 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
11969 // strip, read through the `luma_64corner` arm below instead of a rect
11970 // table -- a 64-length axis codes only its low 32 coefficients
11971 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
11972 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
11973 // depth-0 arm already reads on the key-frame path.
11974 //
11975 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
11976 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
11977 // sub-8x8 intra leaves still refused: with those lifted (r2) the
11978 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
11979 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
11980 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
11981 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
11982 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
11983 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
11984 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
11985 (64, 32) | (32, 64) => None,
11986 _ => {
11987 return Err(unsupported(format!(
11988 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
11989 coefficient tables for that shape here)"
11990 )));
11991 }
11992 };
11993 // The `None` above that is NOT the square arm.
11994 let luma_64corner = tx_w != tx_h;
11995 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
11996 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
11997 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
11998 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
11999 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
12000 // per-unit rect walk stay wired above/below; the round that finds that
12001 // defect deletes this refusal and nothing else.
12002 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
12003 let luma_scan = default_scan(tx_w.min(tx_h));
12004 let zero_tu = vec![0i32; tx_w * tx_h];
12005 // The strip's OWN edge availability, the fallback for a transform unit
12006 // whose top-right/bottom-left pixels fall outside the strip.
12007 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12008 for tu_row in 0..bh / tx_h {
12009 for tu_col in 0..bw / tx_w {
12010 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
12011 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12012 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
12013 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
12014 // libaom clips `av1_foreach_transformed_block_in_plane` to
12015 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
12016 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
12017 // TOP-LEFT sample falls outside the frame is never coded. We read
12018 // coefficients for those phantom units and desynced the stream at
12019 // the very next symbol.
12020 if tu_px >= y.true_width || tu_py >= y.true_height {
12021 continue;
12022 }
12023 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
12024 // transform unit INSIDE a block, which is a different rule from
12025 // the standalone-block table [`Reach::of`] applies -- and the
12026 // reason a depth-2 superblock strip came out one sample off
12027 // before this: `Reach::of(tx, ..)` answered as if the unit were
12028 // its own block at that superblock position.
12029 // * top-right: if the unit's right neighbour is still inside the
12030 // strip the pixels are already reconstructed (`col_off +
12031 // tx_wide < plane_bw`); otherwise only the strip's own top row
12032 // of units can reach past it, through the block-level answer.
12033 // * bottom-left: a unit that is not in the strip's left column
12034 // has none (`col_off > 0` returns 0); inside the strip
12035 // (`row_off + tx_high < plane_bh`) they are the left
12036 // neighbour's, already reconstructed; the last row falls back
12037 // to the block-level answer.
12038 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
12039 // The unit's own window on the block's palette prediction.
12040 if let Some(buf) = &m.palette_y {
12041 let tu_buf: Vec<u16> = (0..tx_h)
12042 .flat_map(|i| {
12043 let base = (row_off + i) * bw + col_off;
12044 buf[base..base + tx_w].iter().copied()
12045 })
12046 .collect();
12047 set_palette_pred(tu_buf, fctx);
12048 }
12049 if m.skip {
12050 push_intra_rect(
12051 0,
12052 tu_px,
12053 tu_py,
12054 tx_w,
12055 tx_h,
12056 m.mode,
12057 m.angle_delta_y,
12058 tu_reach,
12059 &zero_tu,
12060 None,
12061 m.filter_intra,
12062 m.smooth_neighbor,
12063 fctx,
12064 );
12065 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12066 } else if luma_64corner && luma_rect.is_none() {
12067 // The un-split 64-level luma transform: `read_coeffs` on the
12068 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
12069 // and the real rect shape passed through for
12070 // `av1_nz_map_ctx_offset` -- byte for byte
12071 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
12072 // 64-level strip gate already proves. `tx_type` is not coded
12073 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
12074 // the square-up size is TX_64X64), and this unit covers its
12075 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
12076 if crate::envflags::env_flag!("EC_RECT64TU") {
12077 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
12078 }
12079 hit_do! {
12080 RECT64_CORNER_TU_HITS.with(|c| {
12081 let mut v = c.get();
12082 v[usize::from(tx_h > tx_w)] += 1;
12083 c.set(v);
12084 });
12085 }
12086 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12087 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
12088 let (corner, tu_tx_type) = read_coeffs(
12089 dec,
12090 &mut coding,
12091 default_scan(TX32),
12092 0,
12093 dc_sign_ctx(tu_around.2),
12094 TxType::DctDct,
12095 Some((tx_w, tx_h)),
12096 )?;
12097 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
12098 let mut tu_grid = vec![0i32; tx_w * tx_h];
12099 for row in 0..ch {
12100 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
12101 }
12102 let residual = dequant_and_inverse_typed_wh(
12103 &tu_grid,
12104 tx_w,
12105 tx_h,
12106 crate::decode::bit_depth(fctx),
12107 block_q_idx(fctx),
12108 plane_q_delta(0, fctx).0,
12109 plane_q_delta(0, fctx).1,
12110 tu_tx_type,
12111 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12112 );
12113 push_intra_rect(
12114 0,
12115 tu_px,
12116 tu_py,
12117 tx_w,
12118 tx_h,
12119 m.mode,
12120 m.angle_delta_y,
12121 tu_reach,
12122 &residual,
12123 None,
12124 m.filter_intra,
12125 m.smooth_neighbor,
12126 fctx,
12127 );
12128 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12129 } else if let Some((rect_set, rect_scan)) = luma_rect {
12130 // The rect-unit twin of the square arm below: same contexts,
12131 // same order, through the rect coefficient reader. The
12132 // `tx_type` CDF row of a filter-intra block is
12133 // `fimode_to_intradir[filter_intra_mode]`, never the block's
12134 // own (always DC_PRED) mode -- [`read_plane`] applies that
12135 // for the square arm, so this one must too.
12136 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12137 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
12138 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
12139 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
12140 // neighbour-magnitude table is for a unit SMALLER than its
12141 // block. [`decode_block_rect`]'s own unsplit read passes a
12142 // literal 0 for the same reason; this arm applied the table
12143 // unconditionally and desynced every depth-0 rect strip that
12144 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
12145 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
12146 0
12147 } else {
12148 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
12149 };
12150 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
12151 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12152 dec,
12153 &mut coding,
12154 rect_scan,
12155 tx_w,
12156 tx_h,
12157 tu_skip_ctx,
12158 dc_sign_ctx(tu_around.2),
12159 TxType::DctDct,
12160 0,
12161 )?;
12162 let residual = dequant_and_inverse_typed_wh(
12163 &tu_grid,
12164 tx_w,
12165 tx_h,
12166 crate::decode::bit_depth(fctx),
12167 block_q_idx(fctx),
12168 plane_q_delta(0, fctx).0,
12169 plane_q_delta(0, fctx).1,
12170 tu_tx_type,
12171 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12172 );
12173 push_intra_rect(
12174 0,
12175 tu_px,
12176 tu_py,
12177 tx_w,
12178 tx_h,
12179 m.mode,
12180 m.angle_delta_y,
12181 tu_reach,
12182 &residual,
12183 None,
12184 m.filter_intra,
12185 m.smooth_neighbor,
12186 fctx,
12187 );
12188 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12189 } else {
12190 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12191 // This unit is smaller than the block it sits in, so
12192 // `txb_skip_ctx` is the neighbour-magnitude table, not the
12193 // lone-TU 0 (spec `get_txb_ctx_general`).
12194 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12195 let tu_grid = read_plane(
12196 dec,
12197 cdfs,
12198 luma_set,
12199 &luma_scan,
12200 0,
12201 tu_around,
12202 m.mode,
12203 m.mode,
12204 m.angle_delta_y,
12205 tu_reach,
12206 y,
12207 tu_px,
12208 tu_py,
12209 tx_w,
12210 tx_w,
12211 base_q_idx,
12212 None,
12213 m.filter_intra,
12214 Some(tu_skip_ctx),
12215 m.smooth_neighbor,
12216 fctx,
12217 )?;
12218 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12219 }
12220 }
12221 }
12222 // CHROMA: one un-split rect transform for the whole strip.
12223 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
12224 // units -- each stamps its own neighbour context as it is read, and the
12225 // whole-block `record_split_luma_rect_mi` below would overwrite all of
12226 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
12227 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
12228 // collected here and replayed after that record.
12229 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12230 // The chroma_tiled arm below stamps each unit's coefficient context
12231 // immediately (so the NEXT unit reads it), then the whole-strip
12232 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
12233 // whole-strip state and the per-unit DC signs and levels are lost
12234 // (class `override-slot-on-one-arm`). The units are collected here and
12235 // replayed after that record, the way the lossless arm's
12236 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
12237 // already do.
12238 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12239 let ac = m.alpha.map(|_| {
12240 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
12241 // luma -- the 8-px-wide region the floored 4-px chroma block covers
12242 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
12243 if chroma_422_pair_wide {
12244 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
12245 } else {
12246 cfl_src_rect(px, py, bw, bh)
12247 }
12248 });
12249 let reach = if chroma_422_pair_wide {
12250 // The chroma units predict off the PAIR block's edges: an odd-column
12251 // strip's pair starts 4 luma px to the strip's left, so the strip's
12252 // own answer names the wrong above/right samples (the pair16 arm's
12253 // `pair_reach`, one partition level up).
12254 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12255 } else {
12256 block_reach
12257 };
12258 let (u_grid, v_grid) = if mono(fctx) {
12259 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12260 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12261 // section -- the skipped-strip pushes, the lossless raster and the
12262 // un-split `read_coeffs_rect` below -- is bypassed.
12263 let zero = Grid::Zero(chroma_w * chroma_h);
12264 (zero.clone(), zero)
12265 } else if m.skip {
12266 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12267 if chroma_422_pair_wide || chroma_422_oob {
12268 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12269 // per transform unit even when the strip is skipped
12270 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12271 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12272 // units -- one whole-plane push here would ask the intra
12273 // predictor for a 1:8 rect it never needs.
12274 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12275 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12276 // grid at the floored anchor `chroma_x`.
12277 let (uw, uh) = (4usize, 8usize);
12278 for plane_idx in 1..=2 {
12279 if let Some((ub, vb)) = &m.palette_uv {
12280 let buf = if plane_idx == 1 { ub } else { vb };
12281 set_palette_pred(buf.clone(), fctx);
12282 }
12283 for cu_row in 0..chroma_block_h / uh {
12284 for cu_col in 0..chroma_block_w / uw {
12285 push_intra_rect(
12286 plane_idx,
12287 chroma_x + cu_col * uw,
12288 cpy + cu_row * uh,
12289 uw,
12290 uh,
12291 m.uv_predict_mode,
12292 m.angle_delta_uv,
12293 reach,
12294 &ZERO_RESIDUAL[..uw * uh],
12295 m.alpha
12296 .zip(ac.clone())
12297 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12298 None,
12299 m.smooth_neighbor_uv,
12300 fctx,
12301 );
12302 }
12303 }
12304 }
12305 } else {
12306 if let Some((ub, _)) = &m.palette_uv {
12307 set_palette_pred(ub.clone(), fctx);
12308 }
12309 push_intra_rect(
12310 1,
12311 cpx,
12312 cpy,
12313 chroma_w,
12314 chroma_h,
12315 m.uv_predict_mode,
12316 m.angle_delta_uv,
12317 reach,
12318 &zero,
12319 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12320 None,
12321 m.smooth_neighbor_uv,
12322 fctx,
12323 );
12324 if let Some((_, vb)) = &m.palette_uv {
12325 set_palette_pred(vb.clone(), fctx);
12326 }
12327 push_intra_rect(
12328 2,
12329 cpx,
12330 cpy,
12331 chroma_w,
12332 chroma_h,
12333 m.uv_predict_mode,
12334 m.angle_delta_uv,
12335 reach,
12336 &zero,
12337 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12338 None,
12339 m.smooth_neighbor_uv,
12340 fctx,
12341 );
12342 }
12343 (zero.clone(), zero)
12344 } else if lossless(fctx) {
12345 // lane-lossless: the strip's chroma plane block is coded as 4x4
12346 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12347 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12348 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12349 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12350 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12351 // offset (our `+3` row base) whenever the plane block is bigger than
12352 // the transform.
12353 let scan4 = default_scan(4);
12354 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12355 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12356 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12357 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12358 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12359 // cell), and the 8-px step made every unit past the first column/row
12360 // read its `txb_skip` context at the WRONG mi (two cells over) and
12361 // stamp a 2-cell span with one unit's state -- the polluted above-band
12362 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12363 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12364 // ours read `above[28..29]` where the oracle read `above[26]`).
12365 let span_x = 4 << ss_x(fctx);
12366 let span_y = 4 << ss_y(fctx);
12367 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12368 for plane_idx in 1..=2 {
12369 for cu_row in 0..ch_n {
12370 for cu_col in 0..cw_n {
12371 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12372 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
12373 let cu_reach = tu_reach(
12374 bw,
12375 bh,
12376 cu_col * span_x,
12377 cu_row * span_y,
12378 span_x,
12379 block_reach,
12380 px,
12381 py,
12382 y.width,
12383 y.height,
12384 fctx,
12385 );
12386 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12387 if let Some((ub, vb)) = &m.palette_uv {
12388 let pbuf = if plane_idx == 1 { ub } else { vb };
12389 set_palette_pred(
12390 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12391 fctx,
12392 );
12393 }
12394 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12395 let grid = read_plane(
12396 dec,
12397 cdfs,
12398 TxbSet::Chroma4,
12399 &scan4,
12400 plane_idx,
12401 cu_around[plane_idx],
12402 m.mode,
12403 m.uv_predict_mode,
12404 m.angle_delta_uv,
12405 cu_reach,
12406 plane,
12407 cu_x,
12408 cu_y,
12409 4,
12410 4,
12411 base_q_idx,
12412 m.alpha
12413 .zip(ac)
12414 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12415 None,
12416 offset,
12417 m.smooth_neighbor_uv,
12418 fctx,
12419 )?;
12420 if span_x == 4 && span_y == 4 {
12421 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
12422 }
12423 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
12424 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
12425 last[plane_idx - 1] = grid;
12426 }
12427 }
12428 }
12429 let [ug, vg] = last;
12430 (ug, vg)
12431 } else if chroma_tiled {
12432 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
12433 if chroma_422_pair_wide || chroma_422_oob {
12434 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
12435 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
12436 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
12437 // see above). For the 4-wide strip the units tile the PAIR's
12438 // plane, stepping from the floored anchor.
12439 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
12440 } else {
12441 match (chroma_w, chroma_h) {
12442 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
12443 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
12444 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
12445 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
12446 // through the square reader like every other square chroma unit.
12447 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
12448 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
12449 _ => unreachable!("chroma_tiled"),
12450 }
12451 };
12452 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
12453 // frame's square chroma units count it.
12454 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12455 hit!(CHROMA422_SQUARE_HITS);
12456 }
12457 if chroma_422_pair_wide {
12458 hit!(CHROMA422_PAIR_WIDE_HITS);
12459 }
12460 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
12461 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
12462 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
12463 // the pinned Release oracle), so its txb_skip rows always carry the
12464 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
12465 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
12466 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12467 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
12468 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
12469 // mode-indexed default, the same rule the unsplit arm below applies.
12470 let default_tx = if uw.max(uh) >= 32 {
12471 TxType::DctDct
12472 } else {
12473 default_intra_tx_type(m.uv_predict_mode as u8)
12474 };
12475 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
12476 for plane_idx in 1..=2 {
12477 for cu_row in 0..nh {
12478 for cu_col in 0..nw {
12479 let luma_span_x = uw << ss_x(fctx);
12480 let luma_span_y = uh << ss_y(fctx);
12481 let cu_mi = (
12482 mi_r + cu_row * (luma_span_y / MI),
12483 if chroma_422_pair_wide {
12484 mi_c & !1
12485 } else {
12486 mi_c
12487 } + cu_col * (luma_span_x / MI),
12488 );
12489 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
12490 // chroma context per chroma cell
12491 // ([`Neighbours::around_mi_422_chroma`], the block-8
12492 // rule) -- the plain rect walk samples one chroma cell
12493 // twice at ss_x 1. Every pre-existing shape keeps its own
12494 // walk.
12495 // lane-av1422mi24: the plain rect walk's double-count
12496 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
12497 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
12498 // read its above dc votes twice and its U dc_sign one
12499 // ctx row high (t422 frame 1). Route every ss (1,0)
12500 // unit through the every-second-above-cell sampling;
12501 // 4:2:0/4:4:4 keep the plain walk verbatim.
12502 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
12503 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
12504 } else {
12505 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
12506 };
12507 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
12508 let cfl = m.alpha.map(|(au, av)| {
12509 let alpha = if plane_idx == 1 { au } else { av };
12510 (
12511 alpha,
12512 if chroma_422_pair_wide {
12513 // The unit's co-located luma is the PAIR's
12514 // 8-px-wide band at the floored mi column.
12515 cfl_src_rect(
12516 (mi_c & !1) * MI + cu_col * luma_span_x,
12517 py + cu_row * luma_span_y,
12518 luma_span_x,
12519 luma_span_y,
12520 )
12521 } else {
12522 cfl_src_rect(
12523 px + cu_col * luma_span_x,
12524 py + cu_row * luma_span_y,
12525 luma_span_x,
12526 luma_span_y,
12527 )
12528 },
12529 )
12530 });
12531 // lane-av1-422kf: the palette colour map is consumed per
12532 // unit here like every other chroma arm (`av1_visit_palette`
12533 // feeds the whole plane block; window it to this unit).
12534 // Without this the square chroma rows decoded a uv-palette
12535 // strip's chroma as plain DC (class same-symbols-silent-
12536 // prediction: the rng stayed in sync, only the prediction
12537 // was dropped).
12538 if let Some((ub, vb)) = &m.palette_uv {
12539 let buf = if plane_idx == 1 { ub } else { vb };
12540 set_palette_pred(
12541 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
12542 fctx,
12543 );
12544 }
12545 // 32x32 does not fit read_coeffs_rect's scratch (768). The
12546 // square reader is the path every other 32x32 chroma unit uses.
12547 let levels = if uw == uh {
12548 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12549 read_plane(
12550 dec,
12551 cdfs,
12552 set,
12553 scan,
12554 plane_idx,
12555 cu_around[plane_idx],
12556 m.mode,
12557 m.uv_predict_mode,
12558 m.angle_delta_uv,
12559 reach,
12560 plane,
12561 cu_x,
12562 cu_y,
12563 uw,
12564 uw,
12565 base_q_idx,
12566 cfl,
12567 None,
12568 bigger.then_some(3),
12569 m.smooth_neighbor_uv,
12570 fctx,
12571 )?
12572 } else {
12573 let skip_ctx = usize::from(cu_around[plane_idx].0)
12574 + usize::from(cu_around[plane_idx].1)
12575 + usize::from(bigger) * 3;
12576 let mut coding = cdfs.txb(set, m.uv_predict_mode);
12577 let (levels, tx_type) = read_coeffs_rect(
12578 dec,
12579 &mut coding,
12580 scan,
12581 uw,
12582 uh,
12583 skip_ctx,
12584 dc_sign_ctx(cu_around[plane_idx].2),
12585 default_tx,
12586 plane_idx,
12587 )?;
12588 let residual = dequant_and_inverse_typed_wh(
12589 &levels,
12590 uw,
12591 uh,
12592 crate::decode::bit_depth(fctx),
12593 block_q_idx(fctx),
12594 plane_q_delta(plane_idx, fctx).0,
12595 plane_q_delta(plane_idx, fctx).1,
12596 tx_type,
12597 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
12598 );
12599 push_intra_rect(
12600 plane_idx,
12601 cu_x,
12602 cu_y,
12603 uw,
12604 uh,
12605 m.uv_predict_mode,
12606 m.angle_delta_uv,
12607 reach,
12608 &residual,
12609 cfl,
12610 None,
12611 m.smooth_neighbor_uv,
12612 fctx,
12613 );
12614 levels
12615 };
12616 neighbours.record_mi_chroma(
12617 cu_mi,
12618 luma_span_x,
12619 luma_span_y,
12620 plane_idx,
12621 &levels,
12622 );
12623 tiled_chroma_units.push((
12624 cu_mi,
12625 plane_idx,
12626 levels.clone(),
12627 luma_span_x,
12628 luma_span_y,
12629 ));
12630 last[plane_idx - 1] = levels;
12631 }
12632 }
12633 }
12634 (last[0].clone(), last[1].clone())
12635 } else {
12636 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
12637 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12638 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
12639 // so only the 16x8/8x16 pair takes the mode-indexed default.
12640 let default_tx = if chroma_w.max(chroma_h) >= 32 {
12641 TxType::DctDct
12642 } else {
12643 default_intra_tx_type(m.uv_predict_mode as u8)
12644 };
12645 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
12646 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
12647 // counts every chroma column's whole-unit dc sign twice (the t422
12648 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
12649 // row high). Luma keeps the per-mi gather; the two chroma planes
12650 // take [`Neighbours::around_mi_422_chroma`]'s every-second
12651 // above-cell sampling, like every other 4:2:2 chroma gather.
12652 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
12653 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12654 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
12655 around[1] = c[1];
12656 around[2] = c[2];
12657 }
12658 let mut grids: Vec<Grid> = Vec::with_capacity(2);
12659 for plane_idx in 1..=2 {
12660 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
12661 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
12662 let (levels, tx_type) = read_coeffs_rect(
12663 dec,
12664 &mut coding,
12665 chroma_scan,
12666 chroma_w,
12667 chroma_h,
12668 skip_ctx,
12669 dc_sign_ctx(around[plane_idx].2),
12670 default_tx,
12671 plane_idx,
12672 )?;
12673 // The same delta_q proof the unsplit rect64 path records
12674 // (lane-rectsplit r4: lifting the split-transform refusal moved
12675 // superblock strips onto this path, so only counting there would
12676 // leave the delta_q gate's counter silent for them).
12677 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
12678 hit!(RECT64_QIDX_DRIFT_HITS);
12679 }
12680 let residual = dequant_and_inverse_typed_wh(
12681 &levels,
12682 chroma_w,
12683 chroma_h,
12684 crate::decode::bit_depth(fctx),
12685 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
12686 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
12687 // reading `current_q_idx` here dropped the segment feature
12688 // that every other dequant site applies (class
12689 // `parsed-then-discarded`).
12690 block_q_idx(fctx),
12691 plane_q_delta(plane_idx, fctx).0,
12692 plane_q_delta(plane_idx, fctx).1,
12693 tx_type,
12694 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
12695 );
12696 let cfl = m
12697 .alpha
12698 .zip(ac)
12699 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
12700 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12701 if let Some((ub, vb)) = &m.palette_uv {
12702 let buf = if plane_idx == 1 { ub } else { vb };
12703 set_palette_pred(buf.clone(), fctx);
12704 }
12705 push_intra_rect(
12706 plane_idx,
12707 cpx,
12708 cpy,
12709 chroma_w,
12710 chroma_h,
12711 m.uv_predict_mode,
12712 m.angle_delta_uv,
12713 reach,
12714 &residual,
12715 cfl,
12716 None,
12717 m.smooth_neighbor_uv,
12718 fctx,
12719 );
12720 grids.push(levels);
12721 }
12722 let mut it = grids.into_iter();
12723 (it.next().unwrap(), it.next().unwrap())
12724 };
12725 neighbours.record_split_luma_rect_mi(
12726 at_mi,
12727 bw,
12728 bh,
12729 m.mode,
12730 m.uv_predict_mode,
12731 [&u_grid, &v_grid],
12732 );
12733 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
12734 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12735 }
12736 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
12737 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12738 }
12739 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
12740 neighbours.fill_lf_grid_rect(
12741 (mi_r, mi_c),
12742 bw / MI,
12743 bh / MI,
12744 tx_w as u8,
12745 tx_h as u8,
12746 0,
12747 fctx,
12748 );
12749 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12750 let (rng, _) = dec.debug_state();
12751 eprintln!(
12752 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
12753 tx={tx_w}x{tx_h} rng={rng}"
12754 );
12755 }
12756 Ok(())
12757}
12758
12759/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
12760/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
12761/// because it predicts squares only. Every pixel here goes through the rect
12762/// machinery the key-frame paths already prove: [`decode_rect_split`], which
12763/// at `depth == 0` is the unsplit strip as a single transform unit and
12764/// beyond it the per-unit walk of [`depth_to_tx_wh`].
12765///
12766/// What is genuinely different from [`decode_block_rect`] is the mode
12767/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
12768/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
12769/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
12770/// intra-in-inter arm's own reads at the rect footprint, including its
12771/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
12772/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
12773/// square and this arm) and a nonzero luma angle delta refused by name.
12774///
12775/// The strip's own neighbour records (luma per transform unit, chroma, skip
12776/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
12777/// inter-side bands and the mi map.
12778#[allow(clippy::too_many_arguments)]
12779/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
12780/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
12781/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
12782/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
12783/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
12784/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
12785/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
12786/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
12787/// table here rather than a shift of `bw.min(bh)`.
12788fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12789 Some(match (bw.min(bh), bw.max(bh)) {
12790 (8, 16) => (1usize, 1usize),
12791 (16, 32) => (2, 2),
12792 (32, 64) => (3, 3),
12793 (8, 32) => (1, 2),
12794 (16, 64) => (2, 3),
12795 _ => return None,
12796 })
12797}
12798
12799/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
12800/// block path"): the shapes that can reach that arm, enumerated against the
12801/// MEASURED domain of the inter block path
12802/// ([`INTER_BLOCK_SHAPES`], the census the gate
12803/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
12804/// fills from three real streams).
12805///
12806/// [`decode_intra_rect_in_inter`] is called from one site, under
12807/// `write_w != side || write_h != side`, and only after two earlier arms have
12808/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
12809/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
12810/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
12811/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
12812/// and each of those has a row, so the refusal names a shape no measured
12813/// stream can present.
12814#[test]
12815fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12816 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12817 // names that string exactly (placeholders included) and pins its guard
12818 // site. The enumeration below establishes the shape domain; on its own it
12819 // never said WHICH string the domain was about, so under a real function
12820 // boundary -- rather than a window that ran into the next test -- the row
12821 // read as unanchored.
12822 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)";
12823 assert!(
12824 include_str!("decode.rs").contains(REFUSAL),
12825 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12826 );
12827 let mut checked = 0;
12828 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12829 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
12830 continue;
12831 }
12832 assert!(
12833 intra_in_inter_size_row(w, h).is_some(),
12834 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
12835 the \"no size-group/tx-category row\" refusal"
12836 );
12837 checked += 1;
12838 }
12839 assert_eq!(
12840 checked, 10,
12841 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
12842 lookup, not the 10 this claim was measured over"
12843 );
12844}
12845
12846/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
12847/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
12848/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
12849/// matched before the square arm's `log2` shortcut).
12850///
12851/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
12852/// row here"; the enumeration below is what proves no conformant block can
12853/// reach it.
12854pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
12855 Some(match (write_w, write_h) {
12856 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
12857 // below maps 128 to row 4 (BLOCK_16X32).
12858 (64, 128) => 14,
12859 (128, 64) => 15,
12860 (128, 128) => 16,
12861 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
12862 (16, 32) => 4,
12863 (32, 16) => 5,
12864 (32, 64) => 6,
12865 (64, 32) => 7,
12866 (8, 32) => 8,
12867 (32, 8) => 9,
12868 (16, 64) => 10,
12869 (64, 16) => 11,
12870 // lane-inter4 r3: the 16x16-level rect inter leaves.
12871 (8, 16) => 12,
12872 (16, 8) => 13,
12873 _ => return None,
12874 })
12875}
12876
12877/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
12878/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
12879/// `block_size_wide`/`block_size_high`).
12880#[cfg(test)]
12881const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12882 (4, 4),
12883 (4, 8),
12884 (8, 4),
12885 (8, 8),
12886 (8, 16),
12887 (16, 8),
12888 (16, 16),
12889 (16, 32),
12890 (32, 16),
12891 (32, 32),
12892 (32, 64),
12893 (64, 32),
12894 (64, 64),
12895 (64, 128),
12896 (128, 64),
12897 (128, 128),
12898 (4, 16),
12899 (16, 4),
12900 (8, 32),
12901 (32, 8),
12902 (16, 64),
12903 (64, 16),
12904];
12905
12906/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
12907/// shape with no CDF row here" names a shape no conformant stream can present.
12908///
12909/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
12910/// whose `write_w.min(write_h) >= 8` clause is libaom's
12911/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
12912/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
12913/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
12914/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
12915/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
12916/// clause rejects before the lookup.
12917#[test]
12918fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12919 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12920 // names it and pins its guard site.
12921 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
12922 assert!(
12923 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
12924 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12925 );
12926 let mut rows = std::collections::BTreeSet::new();
12927 let mut excluded = 0;
12928 for (w, h) in BLOCK_SIZES_ALL_WH {
12929 if w.min(h) < 8 {
12930 excluded += 1;
12931 assert!(
12932 w == 4 || h == 4,
12933 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
12934 );
12935 continue;
12936 }
12937 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
12938 panic!(
12939 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
12940 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
12941 )
12942 });
12943 assert!(
12944 row < 17,
12945 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
12946 );
12947 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
12948 }
12949 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
12950 assert_eq!(
12951 rows.len(),
12952 17,
12953 "17 eligible footprints must fill all 17 rows of the motion_mode table"
12954 );
12955}
12956
12957/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
12958/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
12959/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
12960/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
12961/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
12962/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
12963/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
12964/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
12965#[test]
12966fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
12967 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
12968 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
12969 let ss10_invalid: &[(&str, bool)] = &[
12970 ("4x4", false),
12971 ("4x8", true),
12972 ("8x4", false),
12973 ("8x8", false),
12974 ("8x16", true),
12975 ("16x8", false),
12976 ("16x16", false),
12977 ("16x32", true),
12978 ("32x16", false),
12979 ("32x32", false),
12980 ("32x64", true),
12981 ("64x32", false),
12982 ("64x64", false),
12983 ("64x128", true),
12984 ("128x64", false),
12985 ("128x128", false),
12986 ("4x16", true),
12987 ("16x4", false),
12988 ("8x32", true),
12989 ("32x8", false),
12990 ("16x64", true),
12991 ("64x16", false),
12992 ];
12993 for (footprint, invalid10) in ss10_invalid {
12994 let (w, h) = footprint.split_once('x').unwrap();
12995 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
12996 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
12997 // valid because a (2, 4) plane area rounds UP to the 4x4 read
12998 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
12999 // [`decode_rect_split`] at all.
13000 if (bw, bh) == (4, 4) {
13001 continue;
13002 }
13003 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
13004 for (ss_x, ss_y) in [(false, false), (true, true)] {
13005 assert!(
13006 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
13007 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
13008 );
13009 }
13010 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
13011 // BLOCK_INVALID column, anchored at the floored mi column.
13012 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
13013 assert_eq!(
13014 pair.is_some(),
13015 *invalid10 && bw == 4,
13016 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
13017 );
13018 if let Some((block_w, block_h, x, ctx_col)) = pair {
13019 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
13020 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
13021 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
13022 // An even-column strip anchors at its own cell.
13023 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
13024 Some((_, _, x, c)) => (x, c),
13025 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
13026 };
13027 assert_eq!(
13028 (x_even, col_even),
13029 (12, 6),
13030 "even column keeps its own cell"
13031 );
13032 }
13033 }
13034 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
13035 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
13036 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
13037 for (bw, bh) in [
13038 (8usize, 16),
13039 (16, 32),
13040 (32, 64),
13041 (64, 128),
13042 (8, 32),
13043 (16, 64),
13044 ] {
13045 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
13046 }
13047}
13048
13049fn decode_intra_rect_in_inter(
13050 dec: &mut SymbolDecoder,
13051 cdfs: &mut Cdfs,
13052 neighbours: &mut Neighbours,
13053 at: (usize, usize),
13054 bw: usize,
13055 bh: usize,
13056 skip: bool,
13057 allow_screen_content_tools: bool,
13058 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
13059 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
13060 strip16: Option<(bool, bool)>,
13061 y: &mut PlaneBuf<'static>,
13062 u: &mut PlaneBuf<'static>,
13063 v: &mut PlaneBuf<'static>,
13064 base_q_idx: u8,
13065 fctx: &crate::decode::FrameCtx,
13066) -> Result<()> {
13067 // `at` is in MI units (the inter path's own unit since lane-inter4);
13068 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
13069 // below are still keyed by.
13070 let (mi_r, mi_c) = at;
13071 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
13072 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
13073 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
13074 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
13075 // finding -- the category is NOT the same for every strip size).
13076 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
13077 // it is refused by name rather than read from the wrong CDF row.
13078 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
13079 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
13080 // tx-depth category is 1 -- but nothing here has to know either, because
13081 // the strip decodes through the very body the KEY FRAME path proves for
13082 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
13083 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
13084 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
13085 // inter-frame difference is the mode-info read, which
13086 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
13087 // `y_mode[0]` plus the `skip` this caller already read.
13088 if let Some((horz, has_chroma)) = strip16 {
13089 // lane-t900 r22: the screen-content refusal here was STALE (class
13090 // stale-premise): [`decode_rect4_16_strip`] takes
13091 // `allow_screen_content_tools` and reads the whole palette syntax
13092 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
13093 // pair) -- the key frame proves that body. Lifted with the 10-bit
13094 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
13095 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
13096 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
13097 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
13098 let res = decode_rect4_16_strip(
13099 dec,
13100 cdfs,
13101 neighbours,
13102 (mi_r, mi_c),
13103 horz,
13104 has_chroma,
13105 // The inter strips of the same partition publish their own
13106 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
13107 // has nothing to add here.
13108 None,
13109 y,
13110 u,
13111 v,
13112 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13113 allow_screen_content_tools,
13114 base_q_idx,
13115 fctx.tx_select_inter.with(std::cell::Cell::get),
13116 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13117 fctx,
13118 );
13119 fctx.intra_in_inter_mode.with(|c| c.set(None));
13120 let (mode, uv, (tx_w, tx_h)) = res?;
13121 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
13122 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
13123 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
13124 // block of an inter frame, intra ones included, and
13125 // `txfm_partition_update` for the var-tx context. The key-frame body
13126 // writes neither (a key frame has no var-tx tree and its own readers
13127 // use the deblock grid), so the block AFTER this strip read a stale
13128 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
13129 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
13130 // 16x16 row.
13131 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13132 for i in 0..bw / MI {
13133 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13134 *cell = tx_w as u8;
13135 }
13136 }
13137 for i in 0..bh / MI {
13138 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13139 *cell = tx_h as u8;
13140 }
13141 }
13142 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
13143 // coarse 16-px cell holds one entry for the whole 16x16 and the last
13144 // block to write it wins).
13145 neighbours.above_mode[c] = mode;
13146 neighbours.left_mode[r] = mode;
13147 if let Some(uvm) = uv {
13148 neighbours.above_uv_mode[c] = uvm;
13149 neighbours.left_uv_mode[r] = uvm;
13150 }
13151 neighbours.above_side[c] = bw;
13152 neighbours.left_side[r] = bh;
13153 if crate::envflags::env_flag!("EC_INTRA16X4") {
13154 eprintln!(
13155 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
13156 mi_c * MI,
13157 mi_r * MI
13158 );
13159 }
13160 hit_do! {
13161 INTRA16X4_IN_INTER_HITS.with(|h| {
13162 let mut v = h.get();
13163 v[usize::from(!horz)] += 1;
13164 v[2] += usize::from(has_chroma);
13165 h.set(v);
13166 });
13167 }
13168 return Ok(());
13169 }
13170 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
13171 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
13172 // puts BLOCK_128X64/64X128/128X128 in group 3 and
13173 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
13174 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
13175 // block decodes through the very body the KEY FRAME path proves for this
13176 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
13177 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
13178 // `Reach` rule and the frame-edge write clip). The only inter-frame
13179 // differences live inside that body: the mode-info read
13180 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
13181 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
13182 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
13183 // palette (>64) do not exist at this size and are refused by name there.
13184 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
13185 // `intra128_in_inter_witness2.obu` (gate
13186 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
13187 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
13188 // all 15 frames, so the hits are counted out of exact frames (class
13189 // `counter-from-refused-stream`). What r16/r17 could not find, and what
13190 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
13191 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
13192 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
13193 // where the frame EDGE forces it: a partial last superblock row has
13194 // `has_rows128 == false`, so the 128x64 top half is implied, and a
13195 // partial last column implies the 64x128 left half. Put content no
13196 // reference holds (a fresh smooth ramp) in exactly those two bands of an
13197 // inter frame and the encoder codes those forced halves INTRA.
13198 if bw.max(bh) == 128 {
13199 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
13200 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
13201 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
13202 // palette_syntax`), so a 128-root half consumes no palette syntax and
13203 // a screen-content frame's half is syntactically identical to the
13204 // non-screen one this arm already decodes byte-exact.
13205 if coeff_trace_on() {
13206 // lane-t900 r16: which decode-order frame this arm fires in --
13207 // interleaved with the `EC_COEFF_FRAME` markers, this is what
13208 // proves the hit is counted out of a frame that compares exact
13209 // (class `counter-from-refused-stream`).
13210 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
13211 }
13212 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
13213 let res = decode_block_128rect(
13214 dec,
13215 cdfs,
13216 neighbours,
13217 (r, c),
13218 bw,
13219 bh,
13220 y,
13221 u,
13222 v,
13223 base_q_idx,
13224 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13225 allow_screen_content_tools,
13226 fctx.tx_select_inter.with(std::cell::Cell::get),
13227 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13228 fctx,
13229 );
13230 fctx.intra_in_inter_mode.with(|c| c.set(None));
13231 return res;
13232 }
13233 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
13234 if crate::envflags::env_flag!("EC_OBMCREC") {
13235 eprintln!(
13236 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
13237 );
13238 }
13239 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
13240 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
13241 // can arrive here are enumerated against the measured block-shape
13242 // census ([`INTER_BLOCK_SHAPES`]) by
13243 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
13244 // -- every one of them has a row, so this arm names a shape no stream
13245 // has been able to present.
13246 return Err(unsupported(format!(
13247 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13248 )));
13249 };
13250 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13251 // screen-content frame ("palette syntax is consumed for square blocks
13252 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13253 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13254 // it, while the 2:1 reader inlined further down now codes the same syntax
13255 // itself. A real `--tune-content=screen` inter stream reached this refusal
13256 // on 8x16 / 16x8 strips (gate
13257 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13258 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13259 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13260 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13261 // luma/chroma transform tables, the per-unit split walk and the strip's
13262 // own neighbour records). The ONLY difference on an inter frame is the
13263 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13264 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13265 // this caller already read. `tx_cat` above is the same category those
13266 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13267 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13268 if bw.max(bh) == 4 * bw.min(bh) {
13269 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13270 fctx.intra_in_inter_mode
13271 .with(|c| c.set(Some((size_group, skip))));
13272 let res = if bw.max(bh) == 64 {
13273 decode_block_rect64(
13274 dec,
13275 cdfs,
13276 neighbours,
13277 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13278 bw,
13279 bh,
13280 y,
13281 u,
13282 v,
13283 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13284 allow_screen_content_tools,
13285 base_q_idx,
13286 fctx.tx_select_inter.with(std::cell::Cell::get),
13287 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13288 fctx,
13289 )
13290 } else {
13291 decode_block_rect4(
13292 dec,
13293 cdfs,
13294 neighbours,
13295 (mi_r, mi_c),
13296 bw,
13297 bh,
13298 None,
13299 y,
13300 u,
13301 v,
13302 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13303 allow_screen_content_tools,
13304 base_q_idx,
13305 fctx.tx_select_inter.with(std::cell::Cell::get),
13306 fctx,
13307 )
13308 .map(|_| ())
13309 };
13310 fctx.intra_in_inter_mode.with(|c| c.set(None));
13311 res?;
13312 let shape = match (bw, bh) {
13313 (64, 16) => 0,
13314 (16, 64) => 1,
13315 (32, 8) => 2,
13316 _ => 3,
13317 };
13318 hit_do! {
13319 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13320 let mut v = h.get();
13321 v[shape] += 1;
13322 h.set(v);
13323 });
13324 }
13325 return Ok(());
13326 }
13327 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13328 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13329 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13330 // own, so a cross-decoder bisection could only see the block's first
13331 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13332 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13333 if step_trace {
13334 eprintln!(
13335 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13336 dec.debug_state().0
13337 );
13338 }
13339 if mode >= 13 {
13340 return Err(unsupported(
13341 "an intra mode this decoder does not code (round 2)",
13342 ));
13343 }
13344 // lane-angleinter (merged on main for the square intra-in-inter arm):
13345 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
13346 // directional predictor; this arm refused a nonzero one before the merge.
13347 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13348 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
13349 } else {
13350 0
13351 };
13352 if angle_delta_y != 0 {
13353 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
13354 }
13355 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
13356 // superblock-level strip reads the no-CFL alphabet -- the same split
13357 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
13358 //
13359 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
13360 // (libaom `decodemv.c:933`).
13361 let has_chroma = !mono(fctx);
13362 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
13363 let uv_mode = if !has_chroma {
13364 DC_PRED
13365 } else if cfl_allowed {
13366 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13367 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13368 } else {
13369 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13370 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13371 };
13372 if step_trace {
13373 eprintln!(
13374 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
13375 u8::from(cfl_allowed),
13376 dec.debug_state().0
13377 );
13378 }
13379 if (9..=12).contains(&uv_mode) {
13380 hit!(SMOOTH_UV_HITS);
13381 }
13382 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
13383 Some(read_cfl_alphas(dec, cdfs))
13384 } else {
13385 None
13386 };
13387 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13388 DC_PRED
13389 } else {
13390 uv_mode
13391 };
13392 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13393 hit!(DIRECTIONAL_UV_HITS);
13394 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13395 } else {
13396 0
13397 };
13398 if angle_delta_uv != 0 {
13399 hit!(UV_ANGLE_DELTA_HITS);
13400 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
13401 }
13402 // `read_palette_mode_info` (spec 5.11.13), in the position
13403 // `read_intra_block_mode_info` writes it: after the chroma mode and
13404 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
13405 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
13406 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
13407 // skipping the syntax here desynced the tile at the strip's own symbol.
13408 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
13409 // context and colour cache at its own mi position, and the two
13410 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
13411 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
13412 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
13413 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
13414 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13415 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13416 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
13417 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
13418 let use_palette_y =
13419 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
13420 if use_palette_y {
13421 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13422 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
13423 }
13424 // A 2:1 strip of at least 8x8 is always a chroma reference, so
13425 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
13426 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13427 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
13428 let use_palette_uv = has_chroma
13429 && uv_mode == DC_PRED
13430 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
13431 if crate::envflags::env_flag!("EC_PALSYN") {
13432 eprintln!(
13433 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
13434 use_palette_y as i32,
13435 use_palette_uv as i32,
13436 dec.debug_state().0
13437 );
13438 }
13439 if use_palette_uv {
13440 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13441 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
13442 palette_uv_pending = Some((n, u_colors, v_colors));
13443 }
13444 }
13445 // lane-fiinter (merged on main for the square intra-in-inter arm):
13446 // `read_filter_intra_mode_info` is the tail of
13447 // `read_intra_block_mode_info`, after the palette syntax (refused whole
13448 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
13449 // 2:1 strips with both sides <= 32 -- their own CDF rows
13450 // ([`filter_intra_size_class_rect`]).
13451 let mut filter_intra = None;
13452 if mode == DC_PRED
13453 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
13454 // `av1_filter_intra_allowed` excludes a palette-Y block.
13455 && palette_y_pending.is_none()
13456 && let Some(class) = filter_intra_size_class_rect(bw, bh)
13457 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
13458 {
13459 hit!(FILTER_INTRA_HITS);
13460 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
13461 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
13462 }
13463 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
13464 let palette_y = palette_y_pending.map(|(n, colors)| {
13465 let map = decode_color_index_map_wh(
13466 dec,
13467 cdfs,
13468 n,
13469 bw,
13470 bh,
13471 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13472 false,
13473 );
13474 hit!(PALETTE_HITS);
13475 hit!(PALETTE_RECT_HITS);
13476 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
13477 PaletteY {
13478 size: n,
13479 colors,
13480 map,
13481 }
13482 });
13483 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13484 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
13485 let on = palette_onscreen_uv(
13486 (bw, bh),
13487 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13488 (cw, ch),
13489 (ss_x(fctx), ss_y(fctx)),
13490 );
13491 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
13492 hit!(PALETTE_UV_HITS);
13493 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
13494 PaletteUv {
13495 size: n,
13496 u_colors,
13497 v_colors,
13498 map,
13499 }
13500 });
13501 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
13502 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
13503 // chroma ones -- [`decode_block_rect`]'s own pair.
13504 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
13505 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
13506 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
13507 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
13508 // one exactly as [`decode_leaf8`] already does (class
13509 // context-read-from-one-cell).
13510 let coarse_pair = neighbours.modes_above_left(r, c);
13511 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
13512 if (nb_above_mode, nb_left_mode) != coarse_pair {
13513 hit!(EDGE_FILTER_MI_FIX_HITS);
13514 }
13515 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13516 if smooth_neighbor {
13517 hit!(SMOOTH_LUMA_HITS);
13518 }
13519 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13520 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13521 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
13522 // an inter frame codes no depth symbol either (`xd->lossless` is per
13523 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
13524 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
13525 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
13526 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
13527 let d = match tx_cat {
13528 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
13529 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
13530 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
13531 };
13532 if step_trace {
13533 eprintln!(
13534 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
13535 dec.debug_state().0
13536 );
13537 }
13538 d
13539 } else {
13540 0
13541 };
13542 if depth != 0 || lossless(fctx) {
13543 hit!(TX_DEPTH_HITS);
13544 // lane-intrasplit r1: a split intra strip in an inter frame walks the
13545 // key frame's own per-TU path ([`decode_rect_split`] below); what was
13546 // wrong when this refusal was written was the depth SYMBOL, not the walk.
13547 hit_do! {
13548 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
13549 let mut v = h.get();
13550 v[depth.min(2)] += 1;
13551 h.set(v);
13552 });
13553 }
13554 }
13555 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
13556 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
13557 // the two are indistinguishable when the diagnostic fires on splits alone.
13558 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
13559 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
13560 }
13561 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13562 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
13563 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
13564 // of an inter frame, intra ones included -- with the skip term 0 it
13565 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
13566 // and `left_txfm_context` to `tx_size_high` over its height. This strip
13567 // wrote neither, so the next block's var-tx `txfm_partition` context read
13568 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
13569 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
13570 // mi(16,0) and desyncing the tile at that symbol.
13571 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13572 let modes = RectStripModes {
13573 skip,
13574 mode,
13575 angle_delta_y,
13576 uv_predict_mode,
13577 angle_delta_uv,
13578 alpha,
13579 filter_intra,
13580 smooth_neighbor,
13581 smooth_neighbor_uv,
13582 palette_y: palette_y
13583 .as_ref()
13584 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
13585 palette_uv: palette_uv.as_ref().map(|p| {
13586 (
13587 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13588 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13589 )
13590 }),
13591 };
13592 decode_rect_split(
13593 dec,
13594 cdfs,
13595 neighbours,
13596 (mi_r, mi_c),
13597 bw,
13598 bh,
13599 tx_w,
13600 tx_h,
13601 &modes,
13602 y,
13603 u,
13604 v,
13605 base_q_idx,
13606 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13607 fctx,
13608 )?;
13609 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
13610 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
13611 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
13612 // left column over its height. This arm wrote neither before lane-intrasplit
13613 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
13614 // context across the strip's footprint.
13615 for i in 0..bw / MI {
13616 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13617 *cell = tx_w as u8;
13618 }
13619 }
13620 for i in 0..bh / MI {
13621 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13622 *cell = tx_h as u8;
13623 }
13624 }
13625 // The strip's own palette state into the mi-granular neighbour bands, so
13626 // the next block's colour cache and `palette_y_mode` context are libaom's.
13627 record_strip_palette(
13628 neighbours,
13629 (mi_r, mi_c),
13630 bw,
13631 bh,
13632 palette_y.as_ref().map_or(0, |p| p.size),
13633 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
13634 palette_uv.as_ref().map_or(0, |p| p.size),
13635 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
13636 );
13637 let class = match bw.max(bh) {
13638 64 => 0,
13639 32 => 1,
13640 _ => 2,
13641 };
13642 hit_do! {
13643 INTRA_RECT_IN_INTER_HITS.with(|h| {
13644 let mut v = h.get();
13645 v[class] += 1;
13646 h.set(v);
13647 });
13648 }
13649 Ok(())
13650}
13651
13652/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
13653/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
13654///
13655/// libaom treats an intrabc block as INTER for everything except the mode-info
13656/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
13657/// (`blockd.h:373`), so
13658///
13659/// * `parse_decode_block` reads the transform size through the INTER var-tx
13660/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
13661/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
13662/// whose leaves publish their own resolved size back;
13663/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
13664/// frame's own pre-loop-filter reconstruction, at the coded block vector
13665/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
13666/// * `decode_token_recon_block`'s inter branch then reads one residual per
13667/// transform unit, through the INTER coefficient sets
13668/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
13669/// inheriting the colocated luma unit's coded `tx_type`.
13670///
13671/// Text order is libaom's: transform tree, prediction, luma residual, chroma
13672/// residual, bookkeeping. A skipped block codes no residual at all -- the
13673/// prediction is the reconstruction.
13674#[allow(clippy::too_many_arguments)]
13675fn decode_intrabc_rect(
13676 dec: &mut SymbolDecoder,
13677 cdfs: &mut Cdfs,
13678 neighbours: &mut Neighbours,
13679 (mi_r, mi_c): (usize, usize),
13680 (bw, bh): (usize, usize),
13681 skip: bool,
13682 (dv_row, dv_col): (i32, i32),
13683 y: &mut PlaneBuf<'static>,
13684 u: &mut PlaneBuf<'static>,
13685 v: &mut PlaneBuf<'static>,
13686 base_q_idx: u8,
13687 fctx: &crate::decode::FrameCtx,
13688) -> Result<()> {
13689 hit!(INTRABC_RECT_HITS);
13690 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
13691 let idx = usize::from(bh > bw);
13692 if skip {
13693 INTRABC_RECT_SKIPPED_HITS.with(|c| {
13694 let mut seen = c.get();
13695 seen[idx] += 1;
13696 c.set(seen);
13697 });
13698 } else {
13699 INTRABC_RECT_CODED_HITS.with(|c| {
13700 let mut seen = c.get();
13701 seen[idx] += 1;
13702 c.set(seen);
13703 });
13704 }
13705 let (px, py) = (mi_c * MI, mi_r * MI);
13706 // lane-whtshape: a LOSSLESS block's chroma plane block is
13707 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
13708 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
13709 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
13710 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
13711 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
13712 // walk below coded 2 units per plane where libaom codes 8.
13713 //
13714 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
13715 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
13716 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
13717 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
13718 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
13719 // the block at mi (92, 104) read all_zero=0 here against the oracle's
13720 // all_zero=1 -- the bit position forks there. Identical arithmetic at
13721 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
13722 // witness is the identity arm of this lane's gate.
13723 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13724 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
13725 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
13726 // shape this helper is called at, so the uv plane block is ONE unit --
13727 // the same call `decode_token_recon_block`'s own chroma loop makes.
13728 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13729 // lane-av1-intrabc r2: the square stride the proven INTER path uses
13730 // (`side`). The residual grids, the prediction windows AND
13731 // `TxParams::stride` are all laid out at it -- the block's own width
13732 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
13733 // exceeds the stride).
13734 let side = bw.max(bh);
13735 let cside = cw.max(ch);
13736 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
13737 // or bottom frame edge reads no transform-tree symbol for the units
13738 // outside it.
13739 let mi_cols = 2 * y.true_width.div_ceil(8);
13740 let mi_rows = 2 * y.true_height.div_ceil(8);
13741 let leaves = read_block_tx_size_rect(
13742 dec,
13743 cdfs,
13744 neighbours,
13745 (mi_r, mi_c),
13746 (bw, bh),
13747 (mi_cols, mi_rows),
13748 skip,
13749 fctx,
13750 )?;
13751 if leaves.is_some() {
13752 hit!(INTRABC_RECT_VARTX_HITS);
13753 }
13754 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
13755 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
13756 }
13757 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
13758 if crate::envflags::env_flag!("EC_IBCBLOCK") {
13759 eprintln!(
13760 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
13761 cw={cw} ch={ch} cside={cside} skip={skip}"
13762 );
13763 }
13764 // The whole-block prediction: `predict_inter_block` runs once, before any
13765 // coefficient is read. `flush_recon` first -- the source is this frame's
13766 // own reconstruction, including the writes this superblock has queued.
13767 flush_recon(fctx, y, u, v);
13768 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
13769 // reads it at the square stride, so re-lay it -- the same step the inter
13770 // path takes for its own square prediction buffer.
13771 let mut pred_y_dense = vec![0u16; bw * bh];
13772 mc::predict_with_filter(
13773 &y.data,
13774 y.width,
13775 y.true_width,
13776 y.true_height,
13777 mv_to_q4(px, dv_col, 0),
13778 mv_to_q4(py, dv_row, 0),
13779 bw,
13780 bh,
13781 mc::InterpFilterKind::Bilinear,
13782 &mut pred_y_dense,
13783 fctx,
13784 );
13785 let mut pred_y = vec![0u16; side * side];
13786 for row in 0..bh {
13787 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13788 }
13789 let mut pred_u_dense = vec![0u16; cw * ch];
13790 mc::predict_with_filter(
13791 &u.data,
13792 u.width,
13793 u.true_width,
13794 u.true_height,
13795 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13796 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13797 cw,
13798 ch,
13799 mc::InterpFilterKind::Bilinear,
13800 &mut pred_u_dense,
13801 fctx,
13802 );
13803 let mut pred_u = vec![0u16; cside * cside];
13804 for row in 0..ch {
13805 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13806 }
13807 let mut pred_v_dense = vec![0u16; cw * ch];
13808 mc::predict_with_filter(
13809 &v.data,
13810 v.width,
13811 v.true_width,
13812 v.true_height,
13813 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13814 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13815 cw,
13816 ch,
13817 mc::InterpFilterKind::Bilinear,
13818 &mut pred_v_dense,
13819 fctx,
13820 );
13821 let mut pred_v = vec![0u16; cside * cside];
13822 for row in 0..ch {
13823 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13824 }
13825 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13826 let luma_tx_type: TxType;
13827 let (luma_grid, u_grid, v_grid);
13828 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
13829 // kept so their per-4x4 slices can be re-stamped over the whole-block
13830 // record in the tail. `None` on every other arm.
13831 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
13832 if skip {
13833 // No residual syntax at all: the prediction IS the block.
13834 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
13835 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
13836 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
13837 push_mc_rect(
13838 0,
13839 px,
13840 py,
13841 side,
13842 bw,
13843 bh,
13844 Pred::Inline(&pred_y, side),
13845 &ZERO_RESIDUAL[..side * side],
13846 fctx,
13847 );
13848 push_mc_rect(
13849 1,
13850 cpx,
13851 cpy,
13852 cside,
13853 cw,
13854 ch,
13855 Pred::Inline(&pred_u, cside),
13856 &ZERO_RESIDUAL[..cside * cside],
13857 fctx,
13858 );
13859 push_mc_rect(
13860 2,
13861 cpx,
13862 cpy,
13863 cside,
13864 cw,
13865 ch,
13866 Pred::Inline(&pred_v, cside),
13867 &ZERO_RESIDUAL[..cside * cside],
13868 fctx,
13869 );
13870 if let Some(ls) = leaves.as_ref() {
13871 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
13872 // skip arm performs -- libaom `av1_reset_entropy_context`
13873 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
13874 // SKIPPED block zeroes its whole entropy-band footprint. This
13875 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
13876 // so a skipped lossless strip whose `leaves` resolved (every
13877 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13878 // returns the 4x4 grid before it looks at `skip`) left the
13879 // PREVIOUS occupant's luma bands standing and the NEXT block's
13880 // partition parse diverged from libaom's: the 320x242 lossless
13881 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
13882 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
13883 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13884 for &(row, col, tw, th) in ls {
13885 neighbours.record_mi_luma_rect(
13886 (mi_r + row, mi_c + col),
13887 tw,
13888 th,
13889 &ZERO_RESIDUAL[..tw * th],
13890 );
13891 }
13892 }
13893 luma_tx_type = TxType::DctDct;
13894 luma_grid = Grid::Zero(side * side);
13895 u_grid = Grid::Zero(cside * cside);
13896 v_grid = Grid::Zero(cside * cside);
13897 } else {
13898 match leaves.as_ref() {
13899 None => {
13900 // One whole-block rectangular transform unit.
13901 // lane-av1422mi24: at ss (1,0) the chroma above span is
13902 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
13903 // the per-mi gather counts every chroma column's whole-unit
13904 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
13905 // strip's U dc_sign read ctx 1 where the oracle's cell sum
13906 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
13907 // chroma planes take
13908 // [`Neighbours::around_mi_422_chroma`]'s every-second
13909 // above-cell sampling, like every other 4:2:2 chroma gather.
13910 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13911 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13912 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13913 around[1] = c[1];
13914 around[2] = c[2];
13915 }
13916 let (grid, tx_type) = read_inter_plane_rect(
13917 dec,
13918 cdfs,
13919 rect_inter_luma_set(bw, bh, fctx)?,
13920 (bw, bh),
13921 side,
13922 0,
13923 around[0],
13924 0,
13925 y,
13926 px,
13927 py,
13928 Pred::Inline(&pred_y, side),
13929 None,
13930 None,
13931 fctx,
13932 )?;
13933 luma_tx_type = tx_type;
13934 luma_grid = embed_grid_stride(&grid, bw, bh, side);
13935 let (ug, _) = read_inter_plane_rect(
13936 dec,
13937 cdfs,
13938 rect_inter_chroma_set(cw, ch)?,
13939 (cw, ch),
13940 cside,
13941 1,
13942 around[1],
13943 0,
13944 u,
13945 cpx,
13946 cpy,
13947 Pred::Inline(&pred_u, cside),
13948 Some(luma_tx_type),
13949 None,
13950 fctx,
13951 )?;
13952 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13953 let (vg, _) = read_inter_plane_rect(
13954 dec,
13955 cdfs,
13956 rect_inter_chroma_set(cw, ch)?,
13957 (cw, ch),
13958 cside,
13959 2,
13960 around[2],
13961 0,
13962 v,
13963 cpx,
13964 cpy,
13965 Pred::Inline(&pred_v, cside),
13966 Some(luma_tx_type),
13967 None,
13968 fctx,
13969 )?;
13970 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13971 }
13972 Some(leaves) => {
13973 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
13974 // the split override to LUMA only, per leaf -- the step the
13975 // proven inter var-tx path applies right after its own residual
13976 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
13977 // leaf's own transform edges are never filtered.
13978 for &(row, col, tw, th) in leaves.iter() {
13979 neighbours.fill_lf_grid_leaf_luma(
13980 (mi_r + row, mi_c + col),
13981 tw / MI,
13982 th / MI,
13983 tw as u8,
13984 th as u8,
13985 );
13986 }
13987 // One residual per transform unit, in the order the tree coded
13988 // them; each unit reads its own neighbour-magnitude context off
13989 // the units already decoded before it, and every unit adds onto
13990 // its own window of the block's single prediction.
13991 let mut first_tx_type = TxType::DctDct;
13992 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
13993 let tu_mi = (mi_r + row, mi_c + col);
13994 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13995 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13996 let (tu_grid, tu_tx_type) = if tw == th {
13997 let scan = default_scan(tw.min(32));
13998 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
13999 read_inter_plane(
14000 dec,
14001 cdfs,
14002 inter_txbset_for(tw, reduced),
14003 scan,
14004 0,
14005 neighbours.around_mi(tu_mi, tw)[0],
14006 0,
14007 y,
14008 tu_px,
14009 tu_py,
14010 tw,
14011 base_q_idx,
14012 tu_pred,
14013 None,
14014 Some(tu_skip_ctx),
14015 fctx,
14016 )?
14017 } else {
14018 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
14019 read_inter_plane_rect(
14020 dec,
14021 cdfs,
14022 rect_inter_luma_set(tw, th, fctx)?,
14023 (tw, th),
14024 side,
14025 0,
14026 neighbours.around_mi_rect(tu_mi, tw, th)[0],
14027 0,
14028 y,
14029 tu_px,
14030 tu_py,
14031 tu_pred,
14032 None,
14033 Some(tu_skip_ctx),
14034 fctx,
14035 )?
14036 };
14037 if idx == 0 {
14038 first_tx_type = tu_tx_type;
14039 }
14040 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14041 }
14042 // `av1_get_tx_type`'s chroma lookup lands on the colocated
14043 // LUMA unit, which for a split block is the top-left one.
14044 luma_tx_type = first_tx_type;
14045 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
14046 // `None` arm above -- the per-mi rect gather double-counts
14047 // each chroma column's whole-unit dc sign at ss (1,0).
14048 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14049 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14050 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14051 around[1] = c[1];
14052 around[2] = c[2];
14053 }
14054 if lossless(fctx) {
14055 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
14056 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
14057 // lossless block before it looks at a tree, `read_tx_mode`
14058 // already forced `ONLY_4X4` for the frame, and
14059 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
14060 // -- so this block's chroma plane block is a
14061 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
14062 // (`decode_token_recon_block`: every U unit, then every V
14063 // unit), not the single rect unit the two
14064 // `read_inter_plane_rect` calls below read. That single
14065 // 8x4 unit is what reached the lossless WHT with the wrong
14066 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
14067 // replaced). Same helper, same walk, as the inter 8x8 and
14068 // 128 paths.
14069 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
14070 let mut uo = vec![0i32; cside * cside];
14071 let mut vo = vec![0i32; cside * cside];
14072 read_inter_chroma_lossless(
14073 dec,
14074 cdfs,
14075 neighbours,
14076 u,
14077 v,
14078 Pred::Inline(&pred_u, cside),
14079 Pred::Inline(&pred_v, cside),
14080 (mi_r, mi_c),
14081 (cpx, cpy),
14082 (0, 0),
14083 (cw, ch),
14084 (cw, ch),
14085 cside,
14086 0,
14087 base_q_idx,
14088 &mut uo,
14089 &mut vo,
14090 fctx,
14091 )?;
14092 // The per-unit walk stamped every unit's own coefficient
14093 // context, but the whole-block `record_split_luma_rect_mi`
14094 // in the tail rewrites every chroma cell with ONE composed
14095 // state, which drops the per-unit DC signs and levels (class
14096 // `override-slot-on-one-arm` -- the same one
14097 // `decode_rect_split`'s `ll_chroma_units` replay exists
14098 // for). The grids are kept here and replayed AFTER that
14099 // record, from the same 4x4 slices, so the same states.
14100 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
14101 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
14102 ll_chroma = Some((uo, vo));
14103 luma_grid = Grid::Zero(side * side);
14104 } else {
14105 let (ug, _) = read_inter_plane_rect(
14106 dec,
14107 cdfs,
14108 rect_inter_chroma_set(cw, ch)?,
14109 (cw, ch),
14110 cside,
14111 1,
14112 around[1],
14113 0,
14114 u,
14115 cpx,
14116 cpy,
14117 Pred::Inline(&pred_u, cside),
14118 Some(luma_tx_type),
14119 None,
14120 fctx,
14121 )?;
14122 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14123 let (vg, _) = read_inter_plane_rect(
14124 dec,
14125 cdfs,
14126 rect_inter_chroma_set(cw, ch)?,
14127 (cw, ch),
14128 cside,
14129 2,
14130 around[2],
14131 0,
14132 v,
14133 cpx,
14134 cpy,
14135 Pred::Inline(&pred_v, cside),
14136 Some(luma_tx_type),
14137 None,
14138 fctx,
14139 )?;
14140 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14141 luma_grid = Grid::Zero(side * side);
14142 }
14143 }
14144 }
14145 }
14146 let _ = luma_tx_type;
14147 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
14148 // next block reads a neighbour mode, its own block size in both `TXFM`
14149 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
14150 // state (a stale entry would feed the next block's colour cache), and its
14151 // DV into the intrabc mi grid the next block's DV predictor reads.
14152 if leaves.is_some() {
14153 neighbours.record_split_luma_rect_mi(
14154 (mi_r, mi_c),
14155 bw,
14156 bh,
14157 DC_PRED,
14158 DC_PRED,
14159 [&u_grid, &v_grid],
14160 );
14161 } else {
14162 neighbours.record_rect_mi(
14163 (mi_r, mi_c),
14164 bw,
14165 bh,
14166 DC_PRED,
14167 DC_PRED,
14168 &[&luma_grid, &u_grid, &v_grid],
14169 );
14170 }
14171 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
14172 // the whole-block record above, so the NEXT block reads the per-unit DC
14173 // signs and levels libaom's plane-major walk left behind instead of one
14174 // composed state for the whole plane block.
14175 if let Some((uo, vo)) = ll_chroma {
14176 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
14177 for ur in 0..ch / 4 {
14178 for uc in 0..cw / 4 {
14179 let mut unit = Vec::with_capacity(16);
14180 for r in 0..4 {
14181 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
14182 }
14183 neighbours.record_mi_chroma(
14184 // lane-av1lm444loss-corr: the MI STEP between chroma
14185 // units is that same footprint expressed in luma mi
14186 // cells, `(4 << ss) / MI` -- which is exactly what
14187 // `decode_inter_block`'s reference `mu_chroma_units`
14188 // construction writes (decode.rs:43688,
14189 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
14190 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
14191 // this replaces is 4:2:0-only arithmetic that happens
14192 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
14193 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
14194 // SAME value, so 4:2:0 is unchanged by construction.
14195 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
14196 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
14197 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
14198 // The step therefore lands every replayed unit at 4x
14199 // its own mi row/column on a 4:4:4 lossless frame, and
14200 // the whole block's per-unit states are stamped over
14201 // cells that belong to other blocks (or to nothing).
14202 (
14203 mi_r + ur * ((4 << ss_y(fctx)) / MI),
14204 mi_c + uc * ((4 << ss_x(fctx)) / MI),
14205 ),
14206 4 << ss_x(fctx),
14207 4 << ss_y(fctx),
14208 plane_idx,
14209 &Grid::Own(unit),
14210 );
14211 }
14212 }
14213 }
14214 }
14215 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14216 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14217 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14218 neighbours.fill_lf_grid_rect(
14219 (mi_r, mi_c),
14220 bw / MI,
14221 bh / MI,
14222 bw.min(64) as u8,
14223 bh.min(64) as u8,
14224 0,
14225 fctx,
14226 );
14227 record_intrabc_mi_rect(
14228 mi_r,
14229 mi_c,
14230 bw / MI,
14231 bh / MI,
14232 Some((dv_row, dv_col)),
14233 neighbours,
14234 fctx,
14235 );
14236 Ok(())
14237}
14238
14239/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
14240/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
14241/// `decode_block_128rect` refused by name before this port. libaom decodes
14242/// such a block through the INTER machinery (an intrabc block
14243/// `is_inter_block`): `predict_inter_block` copies the whole block from this
14244/// frame's own reconstruction at the integer block vector once, then
14245/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
14246/// per chunk every plane, luma units at the block's own resolved transform
14247/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
14248/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
14249/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
14250/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
14251/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14252/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14253#[allow(clippy::too_many_arguments)]
14254fn decode_intrabc_128rect(
14255 dec: &mut SymbolDecoder,
14256 cdfs: &mut Cdfs,
14257 neighbours: &mut Neighbours,
14258 (mi_r, mi_c): (usize, usize),
14259 (bw, bh): (usize, usize),
14260 skip: bool,
14261 (dv_row, dv_col): (i32, i32),
14262 y: &mut PlaneBuf<'static>,
14263 u: &mut PlaneBuf<'static>,
14264 v: &mut PlaneBuf<'static>,
14265 base_q_idx: u8,
14266 fctx: &crate::decode::FrameCtx,
14267) -> Result<()> {
14268 hit!(INTRABC_128RECT_HITS);
14269 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14270 let (rng, _) = dec.debug_state();
14271 eprintln!(
14272 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14273 );
14274 }
14275 let (px, py) = (mi_c * MI, mi_r * MI);
14276 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14277 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14278 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14279 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14280 // `/2` origin and extent made the prediction window half as tall as
14281 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14282 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14283 // `bw / 2, bh / 2` line-for-line.
14284 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14285 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14286 // The square strides the proven INTER path lays its residual grids,
14287 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14288 // note): 128/64 here.
14289 let side = bw.max(bh);
14290 let cside = cw.max(ch);
14291 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14292 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14293 let mi_cols = 2 * y.true_width.div_ceil(8);
14294 let mi_rows = 2 * y.true_height.div_ceil(8);
14295 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14296 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14297 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14298 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14299 // arms (lane-sb128c r7).
14300 let leaves = read_block_tx_size_rect(
14301 dec,
14302 cdfs,
14303 neighbours,
14304 (mi_r, mi_c),
14305 (bw, bh),
14306 (mi_cols, mi_rows),
14307 skip,
14308 fctx,
14309 )?;
14310 // Whole-block prediction, once, before any coefficient is read
14311 // (`predict_inter_block`); the source is this frame's own
14312 // reconstruction, including the writes this superblock has queued.
14313 flush_recon(fctx, y, u, v);
14314 let mut pred_y_dense = vec![0u16; bw * bh];
14315 mc::predict_with_filter(
14316 &y.data,
14317 y.width,
14318 y.true_width,
14319 y.true_height,
14320 mv_to_q4(px, dv_col, 0),
14321 mv_to_q4(py, dv_row, 0),
14322 bw,
14323 bh,
14324 mc::InterpFilterKind::Bilinear,
14325 &mut pred_y_dense,
14326 fctx,
14327 );
14328 let mut pred_y = vec![0u16; side * side];
14329 for row in 0..bh {
14330 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14331 }
14332 let mut pred_u_dense = vec![0u16; cw * ch];
14333 mc::predict_with_filter(
14334 &u.data,
14335 u.width,
14336 u.true_width,
14337 u.true_height,
14338 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14339 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14340 cw,
14341 ch,
14342 mc::InterpFilterKind::Bilinear,
14343 &mut pred_u_dense,
14344 fctx,
14345 );
14346 let mut pred_u = vec![0u16; cside * cside];
14347 for row in 0..ch {
14348 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14349 }
14350 let mut pred_v_dense = vec![0u16; cw * ch];
14351 mc::predict_with_filter(
14352 &v.data,
14353 v.width,
14354 v.true_width,
14355 v.true_height,
14356 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14357 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14358 cw,
14359 ch,
14360 mc::InterpFilterKind::Bilinear,
14361 &mut pred_v_dense,
14362 fctx,
14363 );
14364 let mut pred_v = vec![0u16; cside * cside];
14365 for row in 0..ch {
14366 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14367 }
14368 let (luma_grid, u_grid, v_grid);
14369 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
14370 // contexts per transform unit -- the replay after this fn's end-of-block
14371 // record restores them (the record itself re-stamps both planes with ONE
14372 // composed state, class `override-slot-on-one-arm`).
14373 let mut mu_chroma = false;
14374 if skip {
14375 // No residual syntax at all: the prediction IS the block. Strides are
14376 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
14377 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
14378 push_mc_rect(
14379 0,
14380 px,
14381 py,
14382 side,
14383 bw,
14384 bh,
14385 Pred::Inline(&pred_y, side),
14386 &ZERO_RESIDUAL[..side * side],
14387 fctx,
14388 );
14389 push_mc_rect(
14390 1,
14391 cpx,
14392 cpy,
14393 cside,
14394 cw,
14395 ch,
14396 Pred::Inline(&pred_u, cside),
14397 &ZERO_RESIDUAL[..cside * cside],
14398 fctx,
14399 );
14400 push_mc_rect(
14401 2,
14402 cpx,
14403 cpy,
14404 cside,
14405 cw,
14406 ch,
14407 Pred::Inline(&pred_v, cside),
14408 &ZERO_RESIDUAL[..cside * cside],
14409 fctx,
14410 );
14411 if let Some(ls) = leaves.as_ref() {
14412 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
14413 // grid before it looks at `skip`; the skipped block still zeroes
14414 // its entropy-band footprint over every unit (libaom
14415 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
14416 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
14417 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14418 for &(row, col, tw, th) in ls {
14419 neighbours.record_mi_luma_rect(
14420 (mi_r + row, mi_c + col),
14421 tw,
14422 th,
14423 &ZERO_RESIDUAL[..tw * th],
14424 );
14425 }
14426 }
14427 luma_grid = Grid::Zero(side * side);
14428 u_grid = Grid::Zero(cside * cside);
14429 v_grid = Grid::Zero(cside * cside);
14430 } else {
14431 let leaves = leaves
14432 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
14433 // libaom `get_transform_size`'s split override applies to LUMA only,
14434 // per leaf -- each unit's own transform edges get filtered
14435 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
14436 for &(row, col, tw, th) in leaves.iter() {
14437 neighbours.fill_lf_grid_leaf_luma(
14438 (mi_r + row, mi_c + col),
14439 tw / MI,
14440 th / MI,
14441 tw as u8,
14442 th as u8,
14443 );
14444 }
14445 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14446 let mut u_units: Vec<i32> = Vec::new();
14447 let mut v_units: Vec<i32> = Vec::new();
14448 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
14449 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
14450 // top-left sample is outside the frame codes nothing.
14451 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
14452 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
14453 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
14454 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
14455 for (pos, &idx) in order.iter().enumerate() {
14456 let (row, col, tw, th) = leaves[idx];
14457 debug_assert_eq!(
14458 tw, th,
14459 "a square TX_64X64 tree root only yields square leaves"
14460 );
14461 let tu_mi = (mi_r + row, mi_c + col);
14462 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14463 if tu_px >= y.true_width || tu_py >= y.true_height {
14464 continue;
14465 }
14466 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14467 let scan = default_scan(tw.min(32));
14468 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14469 let (tu_grid, tu_tx_type) = read_inter_plane(
14470 dec,
14471 cdfs,
14472 inter_txbset_for(tw, reduced),
14473 &scan,
14474 0,
14475 neighbours.around_mi(tu_mi, tw)[0],
14476 0,
14477 y,
14478 tu_px,
14479 tu_py,
14480 tw,
14481 base_q_idx,
14482 tu_pred,
14483 None,
14484 Some(tu_skip_ctx),
14485 fctx,
14486 )?;
14487 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
14488 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14489 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
14490 // mu chunk before the next one starts: once this chunk's leaves
14491 // are done, its chroma is read immediately (the inter 128 path's
14492 // interleave).
14493 let chunk = (row / 16, col / 16);
14494 let done = pos + 1 == order.len()
14495 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
14496 if done {
14497 let (cr, cc) = chunk;
14498 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
14499 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
14500 // within the chunk, plane-major inside the chunk.
14501 let cu_tx = 32usize;
14502 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
14503 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
14504 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
14505 // plane block is 32x64 there), four at 4:4:4. The old
14506 // `chunk_chroma = cside * 64 / side` walked a
14507 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
14508 // axes: at 4:2:2 it read HALF the chroma units of a chunk
14509 // (one 32x32 at the chunk's top-left instead of two), left
14510 // the chunk's lower 32 chroma rows with no residual at all,
14511 // and stamped every unit's entropy context over a 16x16-mi
14512 // luma span instead of 16x8. The same defect and the same
14513 // per-axis repair as `decode_inter_block`'s
14514 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
14515 // witnessed on `422_sb128_3f.obu`).
14516 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14517 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14518 // The unit's own footprint on the LUMA mi grid, per axis:
14519 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
14520 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
14521 // `record_mi_chroma` stamp exactly the unit's own cells.
14522 let unit_luma_w = cu_tx << ss_x(fctx);
14523 let unit_luma_h = cu_tx << ss_y(fctx);
14524 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
14525 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
14526 });
14527 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
14528 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
14529 let units_x = chunk_w_mi / (unit_luma_w / MI);
14530 let units_y = chunk_h_mi / (unit_luma_h / MI);
14531 if lossless(fctx) {
14532 // TX_4X4 chroma units over this chunk (lane-lossless2's
14533 // walk, shared with the inter 128 path).
14534 read_inter_chroma_lossless(
14535 dec,
14536 cdfs,
14537 neighbours,
14538 u,
14539 v,
14540 Pred::Inline(&pred_u, cside),
14541 Pred::Inline(&pred_v, cside),
14542 (mi_r, mi_c),
14543 (cpx, cpy),
14544 (cc * chunk_chroma_w, cr * chunk_chroma_h),
14545 (chunk_chroma_w, chunk_chroma_h),
14546 (cw, ch),
14547 cside,
14548 0,
14549 base_q_idx,
14550 &mut u_units,
14551 &mut v_units,
14552 fctx,
14553 )?;
14554 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
14555 // every TX_4X4 unit's own context (`record_mi_chroma`
14556 // inside the walk) -- the end-of-block record below must
14557 // not overwrite them with the composed grid (the inter
14558 // 128 path sets the same flag on this arm).
14559 mu_chroma = true;
14560 continue;
14561 }
14562 let cu_scan = default_scan(cu_tx);
14563 for plane_idx in 1..3 {
14564 let (src, buf) = if plane_idx == 1 {
14565 (Pred::Inline(&pred_u, cside), &mut *u)
14566 } else {
14567 (Pred::Inline(&pred_v, cside), &mut *v)
14568 };
14569 for ur in 0..units_y {
14570 for uc in 0..units_x {
14571 let unit_mi = (
14572 mi_r + cr * 16 + ur * (unit_luma_h / MI),
14573 mi_c + cc * 16 + uc * (unit_luma_w / MI),
14574 );
14575 // Per unit, AFTER the earlier units' stamps: this
14576 // unit's coefficient context must see them.
14577 let cu_around =
14578 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
14579 if crate::envflags::env_flag!("EC_ECDUMP") {
14580 for p in 1..3 {
14581 let ab: Vec<String> = (0..unit_luma_w / MI)
14582 .map(|k| {
14583 format!(
14584 "{:?}/{}",
14585 neighbours.above[unit_mi.1 + k][p].dc,
14586 neighbours.above[unit_mi.1 + k][p].level
14587 )
14588 })
14589 .collect();
14590 let lf: Vec<String> = (0..unit_luma_h / MI)
14591 .map(|k| {
14592 format!(
14593 "{:?}/{}",
14594 neighbours.left[unit_mi.0 + k][p].dc,
14595 neighbours.left[unit_mi.0 + k][p].level
14596 )
14597 })
14598 .collect();
14599 eprintln!(
14600 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
14601 cu_around[p].0,
14602 cu_around[p].1,
14603 cu_around[p].2,
14604 ab.join(","),
14605 lf.join(",")
14606 );
14607 }
14608 }
14609 let (cu_x, cu_y) = (
14610 cpx + cc * chunk_chroma_w + uc * cu_tx,
14611 cpy + cr * chunk_chroma_h + ur * cu_tx,
14612 );
14613 // `av1_get_tx_type` (blockd.h:1291): an inter
14614 // block's chroma unit never codes a tx_type; it
14615 // inherits the coded type of the luma leaf
14616 // covering its own quadrant (all of this chunk's
14617 // leaves are read by now).
14618 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
14619 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
14620 // The prediction window is the block's own square
14621 // `cside` buffer with the unit's true per-axis
14622 // position inside it.
14623 let cu_pred = src.offset(
14624 (cr * chunk_chroma_h + ur * cu_tx) * cside
14625 + cc * chunk_chroma_w
14626 + uc * cu_tx,
14627 );
14628 let cu_grid = read_inter_plane(
14629 dec,
14630 cdfs,
14631 TxbSet::Chroma32,
14632 &cu_scan,
14633 plane_idx,
14634 cu_around[plane_idx],
14635 0,
14636 buf,
14637 cu_x,
14638 cu_y,
14639 cu_tx,
14640 base_q_idx,
14641 cu_pred,
14642 Some(covering.unwrap_or(TxType::DctDct)),
14643 Some(3),
14644 fctx,
14645 )?
14646 .0;
14647 // Immediately, so the NEXT unit reads this one's
14648 // coefficient context.
14649 neighbours.record_mi_chroma(
14650 unit_mi,
14651 unit_luma_w,
14652 unit_luma_h,
14653 plane_idx,
14654 &cu_grid,
14655 );
14656 if crate::envflags::env_flag!("EC_ECDUMP") {
14657 let st = crate::decode::neighbour_state(&cu_grid);
14658 eprintln!(
14659 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
14660 st.dc, st.level
14661 );
14662 }
14663 hit!(CHROMA_SPLIT_TX_HITS);
14664 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
14665 // lane-av1-ibcrect: per-unit chroma context -- the
14666 // end-of-block record's composed-grid re-stamp
14667 // must not stand (replayed below).
14668 mu_chroma = true;
14669 let dst = mu_units(
14670 if plane_idx == 1 {
14671 &mut u_units
14672 } else {
14673 &mut v_units
14674 },
14675 cside * cside,
14676 );
14677 for rr in 0..cu_tx {
14678 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
14679 + cc * chunk_chroma_w
14680 + uc * cu_tx;
14681 dst[start..start + cu_tx]
14682 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
14683 }
14684 }
14685 }
14686 }
14687 }
14688 }
14689 // The block-level luma bands were recorded per leaf above; the
14690 // composed chroma grids carry every unit in place.
14691 luma_grid = Grid::Zero(side * side);
14692 u_grid = if u_units.is_empty() {
14693 Grid::Zero(cside * cside)
14694 } else {
14695 Grid::Own(std::mem::take(&mut u_units))
14696 };
14697 v_grid = if v_units.is_empty() {
14698 Grid::Zero(cside * cside)
14699 } else {
14700 Grid::Own(std::mem::take(&mut v_units))
14701 };
14702 }
14703 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
14704 // neighbour reads a mode, zeroed palette state, the skip grid, the
14705 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
14706 // and the DV into the intrabc mi grid.
14707 if skip {
14708 neighbours.record_rect_mi(
14709 (mi_r, mi_c),
14710 bw,
14711 bh,
14712 DC_PRED,
14713 DC_PRED,
14714 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
14715 );
14716 } else {
14717 neighbours.record_split_luma_rect_mi(
14718 (mi_r, mi_c),
14719 bw,
14720 bh,
14721 DC_PRED,
14722 DC_PRED,
14723 [&u_grid[..], &v_grid[..]],
14724 );
14725 }
14726 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
14727 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
14728 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
14729 // both planes with ONE `neighbour_state(composed_grid)` over the whole
14730 // span -- level = the SUM of every unit's levels and dc = the top-left
14731 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
14732 // inter block: the next block read a stale `dc_sign_ctx` one row low).
14733 // Measured on this shape: the 128x64 block at mi(64,32) of the
14734 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
14735 // into chunk-0's cells and the block below read `txb_skip` off the sum.
14736 // Replay every coded unit's own state after the record, in mu-chunk order
14737 // so a later unit still wins over an earlier one on the shared seam cells
14738 // (the composed construction `mu_chroma_units` uses, transcribed here).
14739 if mu_chroma {
14740 let cu = if lossless(fctx) { 4usize } else { 32usize };
14741 // The unit's own footprint on the LUMA mi grid (the chroma context
14742 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
14743 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
14744 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
14745 let unit_luma_w = cu << ss_x(fctx);
14746 let unit_luma_h = cu << ss_y(fctx);
14747 // A 64x64 mu chunk's chroma plane block is PER-AXIS
14748 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
14749 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
14750 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
14751 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14752 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14753 if lossless(fctx) {
14754 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
14755 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
14756 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
14757 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
14758 // enumerate it, and this arm re-stamps only the 4x4 at each
14759 // chunk's top-left with a 2x2-mi span. The twin
14760 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
14761 // instead raster-walks the WHOLE plane block at `cu` steps, and
14762 // that is the correct shape here too. It is left as-is on purpose:
14763 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
14764 // it would change 4:2:0 LOSSLESS output -- which this lane's
14765 // byte-identity requirement forbids doing on an unverified
14766 // reconstruction. Measured unreachability: this arm is entered
14767 // 0 times by the whole `lossless` and `intrabc` gate battery
14768 // (temporary env-gated counter in the arm). Unblock: one
14769 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
14770 // intrabc strip (`--lossless=1 --sb-size=128
14771 // --min-partition-size=64 --enable-rect-partitions=1
14772 // --enable-intrabc=1` over near-match screen content).
14773 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14774 for cr in 0..rows {
14775 for cc in 0..cols {
14776 let unit_mi = (
14777 mi_r + cr * (unit_luma_h / MI),
14778 mi_c + cc * (unit_luma_w / MI),
14779 );
14780 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14781 let mut unit = Vec::with_capacity(cu * cu);
14782 for rr in 0..cu {
14783 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
14784 unit.extend_from_slice(&grid[start..start + cu]);
14785 }
14786 neighbours.record_mi_chroma(
14787 unit_mi,
14788 unit_luma_w,
14789 unit_luma_h,
14790 plane_idx,
14791 &unit,
14792 );
14793 }
14794 }
14795 }
14796 } else {
14797 // The chunk count on each axis, then EVERY unit inside each
14798 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
14799 // span, and its own quadrant of the composed plane grid -- the
14800 // twin's loop (decode_inter_block's `mu_chroma_units`,
14801 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
14802 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
14803 // the grid PER UNIT, which only agrees when a chunk holds exactly
14804 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
14805 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
14806 // 2 or 4, so the old body reached only the first of the stacked
14807 // units and the rest of the chunk kept the composed-grid smearing
14808 // this replay exists to undo. A unit the frame edge clipped codes
14809 // nothing and carries no composed samples beyond the clip, so it
14810 // replays as the zero state exactly like libaom's uncoded unit.
14811 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
14812 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14813 for cr in 0..rows {
14814 for cc in 0..cols {
14815 for kr in 0..ur {
14816 for kc in 0..uc {
14817 let unit_mi = (
14818 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
14819 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
14820 );
14821 let (cy, cx) =
14822 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
14823 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14824 let mut unit = Vec::with_capacity(cu * cu);
14825 for rr in 0..cu {
14826 let start = (cy + rr) * cside + cx;
14827 unit.extend_from_slice(&grid[start..start + cu]);
14828 }
14829 neighbours.record_mi_chroma(
14830 unit_mi,
14831 unit_luma_w,
14832 unit_luma_h,
14833 plane_idx,
14834 &unit,
14835 );
14836 }
14837 }
14838 }
14839 }
14840 }
14841 }
14842 }
14843 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14844 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14845 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14846 neighbours.fill_lf_grid_rect(
14847 (mi_r, mi_c),
14848 bw / MI,
14849 bh / MI,
14850 bw.min(64) as u8,
14851 bh.min(64) as u8,
14852 0,
14853 fctx,
14854 );
14855 record_intrabc_mi_rect(
14856 mi_r,
14857 mi_c,
14858 bw / MI,
14859 bh / MI,
14860 Some((dv_row, dv_col)),
14861 neighbours,
14862 fctx,
14863 );
14864 Ok(())
14865}
14866
14867/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
14868/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
14869/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
14870/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
14871/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
14872/// has no rectangular-transform coefficient reader, and a chroma plane here
14873/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
14874/// with no depth-based square-tiling escape the way luma's own resolved
14875/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
14876/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
14877#[allow(clippy::too_many_arguments)]
14878fn decode_block_rect(
14879 dec: &mut SymbolDecoder,
14880 cdfs: &mut Cdfs,
14881 neighbours: &mut Neighbours,
14882 at: (usize, usize),
14883 bw: usize,
14884 bh: usize,
14885 y: &mut PlaneBuf<'static>,
14886 u: &mut PlaneBuf<'static>,
14887 v: &mut PlaneBuf<'static>,
14888 enable_filter_intra: bool,
14889 allow_screen_content_tools: bool,
14890 base_q_idx: u8,
14891 tx_select: bool,
14892 reduced_tx_set: bool,
14893 fctx: &crate::decode::FrameCtx,
14894) -> Result<()> {
14895 let (r, c) = at;
14896 let (px, py) = (c * SUB, r * SUB);
14897 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14898 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14899 let palette_uv_cache = neighbours.palette_uv_cache(at);
14900 let (
14901 skip,
14902 mode,
14903 angle_delta_y,
14904 uv_mode,
14905 angle_delta_uv,
14906 alpha,
14907 filter_intra,
14908 palette_y,
14909 palette_uv,
14910 intrabc,
14911 ) = read_intra_mode_rect(
14912 dec,
14913 cdfs,
14914 nb_above_mode,
14915 nb_left_mode,
14916 true,
14917 true,
14918 bw,
14919 bh,
14920 enable_filter_intra,
14921 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14922 allow_screen_content_tools,
14923 Some((palette_ctx, &palette_cache)),
14924 &palette_uv_cache,
14925 r * (SUB / MI),
14926 c * (SUB / MI),
14927 fctx,
14928 )?;
14929
14930 if let Some((dv_row, dv_col)) = intrabc {
14931 return decode_intrabc_rect(
14932 dec,
14933 cdfs,
14934 neighbours,
14935 (r * (SUB / MI), c * (SUB / MI)),
14936 (bw, bh),
14937 skip,
14938 (dv_row, dv_col),
14939 y,
14940 u,
14941 v,
14942 base_q_idx,
14943 fctx,
14944 );
14945 }
14946 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14947 if smooth_neighbor {
14948 hit!(SMOOTH_LUMA_HITS);
14949 }
14950 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
14951 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
14952 // `uv_mode`, not the luma one.
14953 let smooth_neighbor_uv =
14954 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14955 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
14956 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
14957 // rectangle just as happily), so a `use_filter_intra` strip at this level
14958 // predicts instead of refusing. The below-16x16 leaf arm
14959 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
14960 if filter_intra.is_some() {
14961 hit!(FILTER_INTRA_RECT_HITS);
14962 }
14963 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14964 DC_PRED
14965 } else {
14966 uv_mode
14967 };
14968 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14969 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
14970 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
14971 // one did not, so with `--enable-tx-size-search=0` -- which several gate
14972 // recipes use -- the decoder consumed a symbol the encoder never wrote and
14973 // desynced the tile from that point on. That is why both strips of the
14974 // pinned HORZ quadrant were wrong from their very first pixel, and why our
14975 // range after the read equalled the oracle's range for the whole block.
14976 // lane-av1mixloss: the lossless-segment early return
14977 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
14978 // rect block codes no depth symbol here either (class sweep of the sub8
14979 // leaf's fix).
14980 let depth = if tx_select && !lossless(fctx) {
14981 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
14982 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
14983 // intra-only frame publishes them from every block too
14984 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
14985 // 1920x792 128-superblock stream,
14986 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
14987 // `tx_size_cat2` row 1 where libaom reads row 2.
14988 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
14989 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
14990 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14991 eprintln!(
14992 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
14993 dec.debug_state().0
14994 );
14995 }
14996 d
14997 } else {
14998 0
14999 };
15000 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
15001 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15002 publish_txfm_bands_if_in_inter(
15003 neighbours,
15004 (mi_r, mi_c),
15005 depth_to_tx_wh(bw, bh, depth, fctx),
15006 (bw, bh),
15007 fctx,
15008 );
15009 if depth != 0 || lossless(fctx) {
15010 hit!(TX_DEPTH_HITS);
15011 // lane-rectsplit r1: a split transform is predicted and reconstructed
15012 // per transform unit, each unit taking its edges from the previous
15013 // unit's reconstruction inside this same strip (spec 5.11.36) --
15014 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
15015 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15016 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15017 eprintln!(
15018 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
15019 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
15020 angle_y={angle_delta_y}"
15021 );
15022 }
15023 let modes = RectStripModes {
15024 skip,
15025 mode,
15026 angle_delta_y,
15027 uv_predict_mode,
15028 angle_delta_uv,
15029 alpha,
15030 filter_intra,
15031 smooth_neighbor,
15032 smooth_neighbor_uv,
15033 palette_y: palette_y
15034 .as_ref()
15035 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
15036 palette_uv: palette_uv.as_ref().map(|p| {
15037 (
15038 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15039 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15040 )
15041 }),
15042 };
15043 if palette_y.is_some() || palette_uv.is_some() {
15044 hit!(PALETTE_SPLIT_TX_HITS);
15045 }
15046 decode_rect_split(
15047 dec,
15048 cdfs,
15049 neighbours,
15050 (mi_r, mi_c),
15051 bw,
15052 bh,
15053 tx_w,
15054 tx_h,
15055 &modes,
15056 y,
15057 u,
15058 v,
15059 base_q_idx,
15060 reduced_tx_set,
15061 fctx,
15062 )?;
15063 // This early return skips this fn's own tail, so the palette
15064 // neighbour state has to be stamped HERE too: without it a split-tx
15065 // strip left the above/left palette arrays holding a DEAD block's
15066 // colours, and the next block's colour cache
15067 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
15068 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
15069 // and only those pixels were wrong (lane-palette2 r10).
15070 let (py_size, py_colors) = palette_y
15071 .as_ref()
15072 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15073 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15074 let (puv_size, puv_colors) = palette_uv
15075 .as_ref()
15076 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15077 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15078 hit!(RECT_PARTITION_HITS);
15079 return Ok(());
15080 }
15081 let (tx_w, tx_h) = (bw, bh);
15082 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15083 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15084 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15085 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15086 let (rng, _) = dec.debug_state();
15087 eprintln!(
15088 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
15089 skip={} tx={depth} rng={rng}",
15090 skip as i32
15091 );
15092 }
15093 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
15094 // block's prediction is the reconstructed colour-index map, set fresh
15095 // right before each `reconstruct_rect` call below (lane-palette2 r4).
15096 if let Some(ref pyv) = palette_y {
15097 let buf: Vec<u16> = pyv
15098 .map
15099 .iter()
15100 .map(|&idx| pyv.colors[idx as usize])
15101 .collect();
15102 set_palette_pred(buf, fctx);
15103 }
15104 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15105 (
15106 puv.map
15107 .iter()
15108 .map(|&idx| puv.u_colors[idx as usize])
15109 .collect(),
15110 puv.map
15111 .iter()
15112 .map(|&idx| puv.v_colors[idx as usize])
15113 .collect(),
15114 )
15115 });
15116 if skip {
15117 push_intra_rect(
15118 0,
15119 px,
15120 py,
15121 bw,
15122 bh,
15123 mode,
15124 angle_delta_y,
15125 reach,
15126 &ZERO_RESIDUAL[..bw * bh],
15127 None,
15128 filter_intra,
15129 smooth_neighbor,
15130 fctx,
15131 );
15132 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15133 if let Some((ub, _)) = &palette_uv_bufs {
15134 set_palette_pred(ub.clone(), fctx);
15135 }
15136 push_intra_rect(
15137 1,
15138 cpx,
15139 cpy,
15140 chroma_w,
15141 chroma_h,
15142 uv_predict_mode,
15143 angle_delta_uv,
15144 reach,
15145 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15146 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15147 None,
15148 smooth_neighbor_uv,
15149 fctx,
15150 );
15151 if let Some((_, vb)) = &palette_uv_bufs {
15152 set_palette_pred(vb.clone(), fctx);
15153 }
15154 push_intra_rect(
15155 2,
15156 cpx,
15157 cpy,
15158 chroma_w,
15159 chroma_h,
15160 uv_predict_mode,
15161 angle_delta_uv,
15162 reach,
15163 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15164 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15165 None,
15166 smooth_neighbor_uv,
15167 fctx,
15168 );
15169 neighbours.record_rect(
15170 at,
15171 bw,
15172 bh,
15173 mode,
15174 uv_predict_mode,
15175 &[
15176 &ZERO_RESIDUAL[..bw * bh],
15177 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15178 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15179 ],
15180 );
15181 } else {
15182 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
15183 // reduces both size pairs to their square-up CDF sets
15184 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
15185 // doc comments); the scan order and 2D context tables are the real
15186 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
15187 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
15188 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
15189 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
15190 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
15191 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15192 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15193 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15194 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
15195 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
15196 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
15197 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
15198 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
15199 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
15200 // default follows the >=32 rule below -- the same pairing the
15201 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
15202 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
15203 // is reachable there.
15204 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
15205 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15206 _ => {
15207 return Err(unsupported(
15208 "a rectangular chroma transform whose size has no coefficient table",
15209 ));
15210 }
15211 };
15212 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
15213 TxType::DctDct
15214 } else {
15215 default_intra_tx_type(uv_predict_mode as u8)
15216 };
15217 // lane-rectwire r3: real coefficients desync a pixel-exact gate
15218 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
15219 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
15220 // pixel (not a subtle context-table off-by-one), while the sibling
15221 // non-rect quadrants of the same frame match. Range-ladder bisection
15222 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
15223 // but the intra key-frame path has no traced symbol between the
15224 // partition read and the first coefficient block (mode/skip/tx_depth
15225 // reads are all untraced in libaom's decodeframe.c intra path, unlike
15226 // the inter EC_TRACE_MODE this round added), so a same-length range
15227 // comparison wasn't reachable within budget -- see
15228 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
15229 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
15230 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
15231 // libaom and match). lane-rectwire r4: range-ladder against the
15232 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
15233 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
15234 // both confirmed in sync -- rng=58692 on both sides right after
15235 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
15236 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
15237 // immediately after: ours moves rng 58692 -> 43570, which cannot be
15238 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
15239 // its own tx_size read) unless oracle's tx symbol is a near-certainty
15240 // CDF that barely narrows the range -- i.e. this decoder's
15241 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
15242 // a 32x16/16x32 strip is the first diverging symbol, not the
15243 // coefficient-context math r3 already cleared. Not confirmed byte-
15244 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
15245 // `read_tx_size`'s own rng, not attempted this round -- budget), so
15246 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
15247 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
15248 // it unconditionally where both square paths gate on `tx_select`. With
15249 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
15250 // decoder consumed one that was never there.
15251 {
15252 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15253 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15254 // strip's chroma is a square (side/2, side) block whose above cells
15255 // spread over `side` LUMA mi columns, so the per-mi rect gather
15256 // double-counts every chroma column's whole-unit dc sign. Measured on
15257 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15258 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15259 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15260 // 45260 whose pre-state, bit position and symbol all match and only
15261 // the CDF row differs, and the first divergence in the EC_SYMR
15262 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15263 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15264 let mut around = neighbours.around_rect(at, bw, bh);
15265 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15266 let c2 =
15267 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15268 around[1] = c2[1];
15269 around[2] = c2[2];
15270 }
15271 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15272 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15273 dec,
15274 &mut luma_coding,
15275 luma_scan,
15276 bw,
15277 bh,
15278 0,
15279 dc_sign_ctx(around[0].2),
15280 TxType::DctDct,
15281 0,
15282 )?;
15283 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15284 let (rng, _) = dec.debug_state();
15285 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15286 }
15287 let luma_residual = dequant_and_inverse_typed_wh(
15288 &luma_levels,
15289 bw,
15290 bh,
15291 crate::decode::bit_depth(fctx),
15292 block_q_idx(fctx),
15293 plane_q_delta(0, fctx).0,
15294 plane_q_delta(0, fctx).1,
15295 luma_tx_type,
15296 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15297 );
15298 push_intra_rect(
15299 0,
15300 px,
15301 py,
15302 bw,
15303 bh,
15304 mode,
15305 angle_delta_y,
15306 reach,
15307 &luma_residual,
15308 None,
15309 filter_intra,
15310 smooth_neighbor,
15311 fctx,
15312 );
15313 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15314 if let Some((ub, _)) = &palette_uv_bufs {
15315 set_palette_pred(ub.clone(), fctx);
15316 }
15317 let u_default_tx = chroma_default_tx;
15318 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15319 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15320 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15321 dec,
15322 &mut u_coding,
15323 chroma_scan,
15324 chroma_w,
15325 chroma_h,
15326 u_skip_ctx,
15327 dc_sign_ctx(around[1].2),
15328 u_default_tx,
15329 fctx,
15330 1,
15331 )?;
15332 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15333 let (rng, _) = dec.debug_state();
15334 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15335 }
15336 let u_residual = dequant_and_inverse_typed_wh(
15337 &u_levels,
15338 chroma_w,
15339 chroma_h,
15340 crate::decode::bit_depth(fctx),
15341 block_q_idx(fctx),
15342 plane_q_delta(1, fctx).0,
15343 plane_q_delta(1, fctx).1,
15344 u_tx_type,
15345 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15346 );
15347 push_intra_rect(
15348 1,
15349 cpx,
15350 cpy,
15351 chroma_w,
15352 chroma_h,
15353 uv_predict_mode,
15354 angle_delta_uv,
15355 reach,
15356 &u_residual,
15357 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15358 None,
15359 smooth_neighbor_uv,
15360 fctx,
15361 );
15362 if let Some((_, vb)) = &palette_uv_bufs {
15363 set_palette_pred(vb.clone(), fctx);
15364 }
15365 let v_default_tx = chroma_default_tx;
15366 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15367 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
15368 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
15369 dec,
15370 &mut v_coding,
15371 chroma_scan,
15372 chroma_w,
15373 chroma_h,
15374 v_skip_ctx,
15375 dc_sign_ctx(around[2].2),
15376 v_default_tx,
15377 fctx,
15378 2,
15379 )?;
15380 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15381 let (rng, _) = dec.debug_state();
15382 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15383 }
15384 let v_residual = dequant_and_inverse_typed_wh(
15385 &v_levels,
15386 chroma_w,
15387 chroma_h,
15388 crate::decode::bit_depth(fctx),
15389 block_q_idx(fctx),
15390 plane_q_delta(2, fctx).0,
15391 plane_q_delta(2, fctx).1,
15392 v_tx_type,
15393 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15394 );
15395 push_intra_rect(
15396 2,
15397 cpx,
15398 cpy,
15399 chroma_w,
15400 chroma_h,
15401 uv_predict_mode,
15402 angle_delta_uv,
15403 reach,
15404 &v_residual,
15405 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15406 None,
15407 smooth_neighbor_uv,
15408 fctx,
15409 );
15410 neighbours.record_rect(
15411 at,
15412 bw,
15413 bh,
15414 mode,
15415 uv_predict_mode,
15416 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15417 );
15418 hit!(RECT_COEFF_HITS);
15419 }
15420 }
15421 let (py_size, py_colors) = palette_y
15422 .as_ref()
15423 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15424 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15425 let (puv_size, puv_colors) = palette_uv
15426 .as_ref()
15427 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15428 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15429 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15430 neighbours.fill_lf_grid_rect(
15431 (mi_r, mi_c),
15432 bw / MI,
15433 bh / MI,
15434 tx_w as u8,
15435 tx_h as u8,
15436 0,
15437 fctx,
15438 );
15439 hit!(RECT_PARTITION_HITS);
15440 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15441 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
15442 }
15443 Ok(())
15444}
15445
15446/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
15447/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
15448/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
15449/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
15450/// the second strip of a HORZ/VERT split sits offset by half the 16x16
15451/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
15452/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
15453/// previous strip is directly above (same column, `mi_h` rows up) or
15454/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
15455/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
15456/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
15457/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
15458/// this strip's real position, never the coarse `record_rect` (which the
15459/// caller uses once, after both strips, exactly like the `VERT_B` arm next
15460/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
15461/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
15462/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
15463/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
15464/// half-width, unhalved height), the two size classes one level
15465/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
15466#[allow(clippy::too_many_arguments)]
15467fn decode_leaf_rect(
15468 dec: &mut SymbolDecoder,
15469 cdfs: &mut Cdfs,
15470 neighbours: &mut Neighbours,
15471 outer_at: (usize, usize),
15472 leaf_mi: (usize, usize),
15473 bw: usize,
15474 bh: usize,
15475 prev_leaf: Option<((usize, usize), usize)>,
15476 y: &mut PlaneBuf<'static>,
15477 u: &mut PlaneBuf<'static>,
15478 v: &mut PlaneBuf<'static>,
15479 enable_filter_intra: bool,
15480 allow_screen_content_tools: bool,
15481 base_q_idx: u8,
15482 tx_select: bool,
15483 reduced_tx_set: bool,
15484 fctx: &crate::decode::FrameCtx,
15485) -> Result<usize> {
15486 let _ = base_q_idx;
15487 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15488 eprintln!(
15489 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
15490 dec.debug_state().0
15491 );
15492 }
15493 let (r, c) = outer_at;
15494 let mut above_mode = neighbours.above_mode[c];
15495 let mut left_mode = neighbours.left_mode[r];
15496 let (mi_w, mi_h) = (bw / MI, bh / MI);
15497 if let Some(((pr, pc), pmode)) = prev_leaf {
15498 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
15499 above_mode = pmode;
15500 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
15501 left_mode = pmode;
15502 }
15503 }
15504 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
15505 // cannot hold the modes a split (or a pair of strips) leaves behind, so
15506 // when the map holds the block at exactly this strip's above/left mi it
15507 // is the neighbour libaom's `above_mi`/`left_mi` reads.
15508 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
15509 // availability-correct -- four 16x8 strips share one coarse 16x16
15510 // `left_mode` cell too, so the fallback must not stand in for an absent
15511 // tile-edge neighbour.
15512 let (above_mode, left_mode) =
15513 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15514 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15515 if smooth_neighbor {
15516 hit!(SMOOTH_LUMA_HITS);
15517 }
15518 // The palette-Y mode CDF row is picked by the neighbours' palette use
15519 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
15520 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
15521 // a palette narrows the wrong interval and desyncs the tile even when the
15522 // decoded bit is the same. The cell is the 16px-SUB cell containing the
15523 // leaf (the palette neighbour arrays have no finer granularity).
15524 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
15525 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
15526 // exclusion and the neighbour palette lookup itself are mi-granular
15527 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
15528 let pal_at = leaf_mi;
15529 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15530 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15531 let (
15532 skip,
15533 mode,
15534 angle_delta_y,
15535 uv_mode,
15536 angle_delta_uv,
15537 alpha,
15538 filter_intra,
15539 palette_y,
15540 palette_uv,
15541 intrabc,
15542 ) = read_intra_mode_rect(
15543 dec,
15544 cdfs,
15545 above_mode,
15546 left_mode,
15547 true,
15548 true,
15549 bw,
15550 bh,
15551 enable_filter_intra,
15552 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15553 allow_screen_content_tools,
15554 Some((palette_ctx, &palette_cache)),
15555 &palette_uv_cache,
15556 leaf_mi.0,
15557 leaf_mi.1,
15558 fctx,
15559 )?;
15560
15561 if let Some((dv_row, dv_col)) = intrabc {
15562 decode_intrabc_rect(
15563 dec,
15564 cdfs,
15565 neighbours,
15566 leaf_mi,
15567 (bw, bh),
15568 skip,
15569 (dv_row, dv_col),
15570 y,
15571 u,
15572 v,
15573 base_q_idx,
15574 fctx,
15575 )?;
15576 return Ok(DC_PRED);
15577 }
15578 // lane-kf900 r4: palette prediction on this shape, the same colour-index
15579 // map -> base colours buffer [`decode_block_rect`] hands each
15580 // `reconstruct_rect` through [`set_palette_pred`].
15581 if palette_y.is_some() || palette_uv.is_some() {
15582 hit!(RECT4_PALETTE_HITS);
15583 }
15584 let palette_y_buf: Option<Vec<u16>> = palette_y
15585 .as_ref()
15586 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15587 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15588 (
15589 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15590 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15591 )
15592 });
15593 let (pal_y_size, pal_y_colors) = palette_y
15594 .as_ref()
15595 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15596 let (pal_uv_size, pal_uv_colors) = palette_uv
15597 .as_ref()
15598 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15599 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15600 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
15601 }
15602 if filter_intra.is_some() {
15603 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
15604 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
15605 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
15606 // below already makes; this refusal was square-only prose.
15607 hit!(FILTER_INTRA_RECT_HITS);
15608 hit!(FILTER_INTRA_RECT_SUB16_HITS);
15609 }
15610 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15611 DC_PRED
15612 } else {
15613 uv_mode
15614 };
15615 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
15616 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
15617 // a constant `false`.
15618 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
15619 let depth = if tx_select && !lossless(fctx) {
15620 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
15621 // every other rect reader now does -- a no-op on a key frame.
15622 // lane-av1mixloss: libaom `read_tx_size`'s first line
15623 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
15624 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
15625 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
15626 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
15627 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
15628 // read was the leaf's own txb_skip.
15629 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
15630 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
15631 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
15632 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
15633 // count (3), different CDF row: a wrong-table read of a real symbol,
15634 // the class that cost lane-rectsplit r1 its 64x32 depth.
15635 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
15636 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
15637 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
15638 // function also decodes) sit at depth 2, so they read
15639 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
15640 // while `tx_size_cat2` belongs to the 32-level shapes
15641 // ([`decode_block_rect`]). Both tables carry three symbols, so the
15642 // wrong one decodes a plausible depth from the wrong probabilities:
15643 // the range diverges silently at the first such leaf and every later
15644 // symbol in the tile is read from the wrong place (class
15645 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
15646 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
15647 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15648 eprintln!(
15649 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
15650 leaf_mi.0,
15651 leaf_mi.1,
15652 dec.debug_state().0
15653 );
15654 }
15655 d
15656 } else {
15657 0
15658 };
15659 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
15660 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15661 publish_txfm_bands_if_in_inter(
15662 neighbours,
15663 leaf_mi,
15664 depth_to_tx_wh(bw, bh, depth, fctx),
15665 (bw, bh),
15666 fctx,
15667 );
15668 if depth != 0 || lossless(fctx) {
15669 // The same per-transform-unit walk the bigger strips take
15670 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
15671 // depth 2), addressed at this leaf's own mi position.
15672 hit!(TX_DEPTH_HITS);
15673 hit!(SUB16_SPLIT_HITS);
15674 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15675 let modes = RectStripModes {
15676 skip,
15677 mode,
15678 angle_delta_y,
15679 uv_predict_mode,
15680 angle_delta_uv,
15681 alpha,
15682 filter_intra,
15683 smooth_neighbor,
15684 // lane-rectsplitx r3: the split arm hard-coded `false` here while
15685 // the unsplit arm below passes the real neighbour answer -- chroma
15686 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
15687 smooth_neighbor_uv,
15688 palette_y: palette_y_buf.clone(),
15689 palette_uv: palette_uv_bufs.clone(),
15690 };
15691 if palette_y.is_some() || palette_uv.is_some() {
15692 hit!(PALETTE_SPLIT_TX_HITS);
15693 }
15694 decode_rect_split(
15695 dec,
15696 cdfs,
15697 neighbours,
15698 leaf_mi,
15699 bw,
15700 bh,
15701 tx_w,
15702 tx_h,
15703 &modes,
15704 y,
15705 u,
15706 v,
15707 base_q_idx,
15708 reduced_tx_set,
15709 fctx,
15710 )?;
15711 record_strip_palette(
15712 neighbours,
15713 pal_at,
15714 bw,
15715 bh,
15716 pal_y_size,
15717 pal_y_colors,
15718 pal_uv_size,
15719 pal_uv_colors,
15720 );
15721 return Ok(mode);
15722 }
15723 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15724 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15725 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15726 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15727 let (luma_levels, u_levels, v_levels);
15728 if skip {
15729 luma_levels = Grid::Zero(bw * bh);
15730 u_levels = Grid::Zero(chroma_w * chroma_h);
15731 v_levels = Grid::Zero(chroma_w * chroma_h);
15732 if let Some(b) = &palette_y_buf {
15733 set_palette_pred(b.clone(), fctx);
15734 }
15735 push_intra_rect(
15736 0,
15737 px,
15738 py,
15739 bw,
15740 bh,
15741 mode,
15742 angle_delta_y,
15743 reach,
15744 &luma_levels,
15745 None,
15746 filter_intra,
15747 smooth_neighbor,
15748 fctx,
15749 );
15750 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15751 if let Some((ub, _)) = &palette_uv_bufs {
15752 set_palette_pred(ub.clone(), fctx);
15753 }
15754 push_intra_rect(
15755 1,
15756 cpx,
15757 cpy,
15758 chroma_w,
15759 chroma_h,
15760 uv_predict_mode,
15761 angle_delta_uv,
15762 reach,
15763 &u_levels,
15764 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15765 None,
15766 smooth_neighbor_uv,
15767 fctx,
15768 );
15769 if let Some((_, vb)) = &palette_uv_bufs {
15770 set_palette_pred(vb.clone(), fctx);
15771 }
15772 push_intra_rect(
15773 2,
15774 cpx,
15775 cpy,
15776 chroma_w,
15777 chroma_h,
15778 uv_predict_mode,
15779 angle_delta_uv,
15780 reach,
15781 &v_levels,
15782 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15783 None,
15784 smooth_neighbor_uv,
15785 fctx,
15786 );
15787 } else {
15788 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
15789 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
15790 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
15791 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
15792 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
15793 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
15794 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
15795 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
15796 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
15797 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
15798 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
15799 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
15800 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
15801 if bw == 16 {
15802 (&SCAN_16X8, &SCAN_16X8)
15803 } else {
15804 (&SCAN_8X16, &SCAN_8X16)
15805 }
15806 } else if chroma_422 {
15807 if bw == 16 {
15808 (&SCAN_16X8, default_scan(8))
15809 } else {
15810 (&SCAN_8X16, default_scan(8))
15811 }
15812 } else if bw == 16 {
15813 (&SCAN_16X8, &SCAN_8X4)
15814 } else {
15815 (&SCAN_8X16, &SCAN_4X8)
15816 };
15817 let chroma_rect_set = if ss_x(fctx) == 0 {
15818 TxbSet::ChromaRect16x8
15819 } else if chroma_422 {
15820 TxbSet::Chroma8
15821 } else {
15822 TxbSet::ChromaRect8x4
15823 };
15824 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
15825 // (side/2, side) block, so `side` chroma 4-px cells above it spread
15826 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
15827 // mi cells, and both carry the covering unit's whole-unit dc sign.
15828 // The per-mi rect gather therefore double-counts every chroma
15829 // column's sign. `around_mi_422_chroma`'s every-second above-cell
15830 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
15831 // gather in this file already routes through it (see the gate at this
15832 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
15833 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
15834 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
15835 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
15836 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
15837 // divergence in the frame (the bit offset is a clean constant through
15838 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
15839 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15840 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
15841 if chroma_422 {
15842 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
15843 around[1] = c[1];
15844 around[2] = c[2];
15845 }
15846 let luma_set = if reduced_tx_set {
15847 TxbSet::LumaRect16x8
15848 } else {
15849 TxbSet::LumaRect16x8Set1
15850 };
15851 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
15852 let (l_levels, luma_tx_type) = read_coeffs_rect(
15853 dec,
15854 &mut luma_coding,
15855 luma_scan,
15856 bw,
15857 bh,
15858 0,
15859 dc_sign_ctx(around[0].2),
15860 TxType::DctDct,
15861 0,
15862 )?;
15863 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15864 let nz: Vec<(usize, i32)> = l_levels
15865 .iter()
15866 .copied()
15867 .enumerate()
15868 .filter(|(_, v)| *v != 0)
15869 .collect();
15870 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
15871 }
15872 luma_levels = l_levels;
15873 let luma_residual = dequant_and_inverse_typed_wh(
15874 &luma_levels,
15875 bw,
15876 bh,
15877 crate::decode::bit_depth(fctx),
15878 block_q_idx(fctx),
15879 plane_q_delta(0, fctx).0,
15880 plane_q_delta(0, fctx).1,
15881 luma_tx_type,
15882 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15883 );
15884 if let Some(b) = &palette_y_buf {
15885 set_palette_pred(b.clone(), fctx);
15886 }
15887 push_intra_rect(
15888 0,
15889 px,
15890 py,
15891 bw,
15892 bh,
15893 mode,
15894 angle_delta_y,
15895 reach,
15896 &luma_residual,
15897 None,
15898 filter_intra,
15899 smooth_neighbor,
15900 fctx,
15901 );
15902 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15903 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15904 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15905 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15906 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
15907 dec,
15908 &mut u_coding,
15909 chroma_scan,
15910 chroma_w,
15911 chroma_h,
15912 u_skip_ctx,
15913 dc_sign_ctx(around[1].2),
15914 u_default_tx,
15915 fctx,
15916 1,
15917 )?;
15918 u_levels = u_l;
15919 let u_residual = dequant_and_inverse_typed_wh(
15920 &u_levels,
15921 chroma_w,
15922 chroma_h,
15923 crate::decode::bit_depth(fctx),
15924 block_q_idx(fctx),
15925 plane_q_delta(1, fctx).0,
15926 plane_q_delta(1, fctx).1,
15927 u_tx_type,
15928 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15929 );
15930 if let Some((ub, _)) = &palette_uv_bufs {
15931 set_palette_pred(ub.clone(), fctx);
15932 }
15933 push_intra_rect(
15934 1,
15935 cpx,
15936 cpy,
15937 chroma_w,
15938 chroma_h,
15939 uv_predict_mode,
15940 angle_delta_uv,
15941 reach,
15942 &u_residual,
15943 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15944 None,
15945 smooth_neighbor_uv,
15946 fctx,
15947 );
15948 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15949 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15950 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15951 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
15952 dec,
15953 &mut v_coding,
15954 chroma_scan,
15955 chroma_w,
15956 chroma_h,
15957 v_skip_ctx,
15958 dc_sign_ctx(around[2].2),
15959 v_default_tx,
15960 fctx,
15961 2,
15962 )?;
15963 v_levels = v_l;
15964 let v_residual = dequant_and_inverse_typed_wh(
15965 &v_levels,
15966 chroma_w,
15967 chroma_h,
15968 crate::decode::bit_depth(fctx),
15969 block_q_idx(fctx),
15970 plane_q_delta(2, fctx).0,
15971 plane_q_delta(2, fctx).1,
15972 v_tx_type,
15973 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15974 );
15975 if let Some((_, vb)) = &palette_uv_bufs {
15976 set_palette_pred(vb.clone(), fctx);
15977 }
15978 push_intra_rect(
15979 2,
15980 cpx,
15981 cpy,
15982 chroma_w,
15983 chroma_h,
15984 uv_predict_mode,
15985 angle_delta_uv,
15986 reach,
15987 &v_residual,
15988 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15989 None,
15990 smooth_neighbor_uv,
15991 fctx,
15992 );
15993 hit!(RECT_LEAF_COEFF_HITS);
15994 }
15995 neighbours.record_mi_rect(
15996 leaf_mi,
15997 bw,
15998 bh,
15999 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16000 );
16001 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
16002 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16003 // The leaf's own palette state (`0` clears, as this site always did
16004 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
16005 // AXIS only until the pair's closing leaf: the coarse cell holds one
16006 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
16007 // real left neighbour leaf 1 reads (lane-kf900 r4).
16008 record_strip_palette(
16009 neighbours,
16010 pal_at,
16011 bw,
16012 bh,
16013 pal_y_size,
16014 pal_y_colors,
16015 pal_uv_size,
16016 pal_uv_colors,
16017 );
16018 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
16019 // rows -- record the whole span, not one cell.
16020 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
16021 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
16022 Ok(mode)
16023}
16024
16025/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
16026/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
16027/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
16028/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
16029/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
16030/// strip's mode so this one's mode context sees its true above/left
16031/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
16032///
16033/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
16034/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
16035/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
16036/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
16037/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
16038/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
16039/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
16040///
16041/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
16042/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
16043/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
16044/// unexamined.
16045#[allow(clippy::too_many_arguments)]
16046fn decode_block_rect4(
16047 dec: &mut SymbolDecoder,
16048 cdfs: &mut Cdfs,
16049 neighbours: &mut Neighbours,
16050 strip_mi: (usize, usize),
16051 bw: usize,
16052 bh: usize,
16053 prev_strip: Option<((usize, usize), usize)>,
16054 y: &mut PlaneBuf<'static>,
16055 u: &mut PlaneBuf<'static>,
16056 v: &mut PlaneBuf<'static>,
16057 enable_filter_intra: bool,
16058 allow_screen_content_tools: bool,
16059 base_q_idx: u8,
16060 tx_select: bool,
16061 fctx: &crate::decode::FrameCtx,
16062) -> Result<(usize, usize)> {
16063 let _ = base_q_idx;
16064 let (mi_r, mi_c) = strip_mi;
16065 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
16066 let (mi_w, mi_h) = (bw / MI, bh / MI);
16067 let mut above_mode = neighbours.above_mode[c];
16068 let mut left_mode = neighbours.left_mode[r];
16069 if let Some(((pr, pc), pmode)) = prev_strip {
16070 if pc == mi_c && mi_r == pr + mi_h {
16071 above_mode = pmode;
16072 } else if pr == mi_r && mi_c == pc + mi_w {
16073 left_mode = pmode;
16074 }
16075 }
16076 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
16077 // availability-correct neighbour modes (see
16078 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
16079 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
16080 let (above_mode, left_mode) =
16081 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
16082 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
16083 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
16084 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
16085 // wrong interval, so a screen-content tile desynced at the first strip
16086 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
16087 let pal_at = (mi_r, mi_c);
16088 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
16089 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
16090 let (
16091 skip,
16092 mode,
16093 angle_delta_y,
16094 uv_mode,
16095 angle_delta_uv,
16096 alpha,
16097 filter_intra,
16098 palette_y,
16099 palette_uv,
16100 intrabc,
16101 ) = read_intra_mode_rect(
16102 dec,
16103 cdfs,
16104 above_mode,
16105 left_mode,
16106 true,
16107 true,
16108 bw,
16109 bh,
16110 enable_filter_intra,
16111 neighbours.skip_txfm_ctx(mi_r, mi_c),
16112 allow_screen_content_tools,
16113 Some((palette_ctx, &palette_cache)),
16114 &palette_uv_cache,
16115 mi_r,
16116 mi_c,
16117 fctx,
16118 )?;
16119 if let Some((dv_row, dv_col)) = intrabc {
16120 decode_intrabc_rect(
16121 dec,
16122 cdfs,
16123 neighbours,
16124 strip_mi,
16125 (bw, bh),
16126 skip,
16127 (dv_row, dv_col),
16128 y,
16129 u,
16130 v,
16131 base_q_idx,
16132 fctx,
16133 )?;
16134 return Ok((DC_PRED, DC_PRED));
16135 }
16136 // lane-kf900 r4: palette prediction on this shape, exactly as
16137 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
16138 // mapped through the base colours IS the prediction (it reads no edge
16139 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
16140 if palette_y.is_some() || palette_uv.is_some() {
16141 hit!(RECT4_PALETTE_HITS);
16142 }
16143 let palette_y_buf: Option<Vec<u16>> = palette_y
16144 .as_ref()
16145 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16146 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16147 (
16148 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16149 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16150 )
16151 });
16152 let (pal_y_size, pal_y_colors) = palette_y
16153 .as_ref()
16154 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16155 let (pal_uv_size, pal_uv_colors) = palette_uv
16156 .as_ref()
16157 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16158 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16159 if smooth_neighbor {
16160 hit!(SMOOTH_LUMA_HITS);
16161 }
16162 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
16163 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
16164 // `r * (SUB / MI)` names a different mi column and the chroma
16165 // edge-filter strength was read from the wrong neighbour (measured:
16166 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
16167 // with luma bit-exact).
16168 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
16169 if filter_intra.is_some() {
16170 hit!(FILTER_INTRA_RECT_HITS);
16171 if bw > bh {
16172 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
16173 } else {
16174 hit!(FILTER_INTRA_RECT4_VERT_HITS);
16175 }
16176 }
16177 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16178 DC_PRED
16179 } else {
16180 uv_mode
16181 };
16182 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
16183 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
16184 // depth symbol here either (class sweep of the sub8 leaf's fix).
16185 let depth = if tx_select && !lossless(fctx) {
16186 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
16187 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
16188 // intra-only frame publishes them from every block too
16189 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
16190 // 1920x792 128-superblock stream,
16191 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
16192 // `tx_size_cat2` row 1 where libaom reads row 2.
16193 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
16194 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
16195 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16196 eprintln!(
16197 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
16198 dec.debug_state().0
16199 );
16200 }
16201 d
16202 } else {
16203 0
16204 };
16205 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
16206 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
16207 publish_txfm_bands_if_in_inter(
16208 neighbours,
16209 (mi_r, mi_c),
16210 depth_to_tx_wh(bw, bh, depth, fctx),
16211 (bw, bh),
16212 fctx,
16213 );
16214 if depth != 0 || lossless(fctx) {
16215 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
16216 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
16217 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
16218 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
16219 // both interleave in every real stream.
16220 hit!(TX_DEPTH_HITS);
16221 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16222 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
16223 // predicted -- depth 1 fires FIRST in every attempt that splits at
16224 // all, so a depth-2-only lift could never be gated. The r1 mismatch
16225 // was never the rect unit: it was the neighbour MODE the strip reads
16226 // (see `modes_above_left_mi`).
16227 let which = if depth == 1 {
16228 &RECT4_SPLIT_DEPTH1_HITS
16229 } else {
16230 &RECT4_SPLIT_DEPTH2_HITS
16231 };
16232 hit_do! { which.with(|c| c.set(c.get() + 1)); }
16233 let modes = RectStripModes {
16234 skip,
16235 mode,
16236 angle_delta_y,
16237 uv_predict_mode,
16238 angle_delta_uv,
16239 alpha,
16240 filter_intra,
16241 smooth_neighbor,
16242 smooth_neighbor_uv,
16243 palette_y: palette_y_buf.clone(),
16244 palette_uv: palette_uv_bufs.clone(),
16245 };
16246 if palette_y.is_some() || palette_uv.is_some() {
16247 hit!(PALETTE_SPLIT_TX_HITS);
16248 }
16249 decode_rect_split(
16250 dec,
16251 cdfs,
16252 neighbours,
16253 (mi_r, mi_c),
16254 bw,
16255 bh,
16256 tx_w,
16257 tx_h,
16258 &modes,
16259 y,
16260 u,
16261 v,
16262 base_q_idx,
16263 false,
16264 fctx,
16265 )?;
16266 record_strip_palette(
16267 neighbours,
16268 pal_at,
16269 bw,
16270 bh,
16271 pal_y_size,
16272 pal_y_colors,
16273 pal_uv_size,
16274 pal_uv_colors,
16275 );
16276 if bw > bh {
16277 hit!(RECT4_32_HORZ_HITS);
16278 } else {
16279 hit!(RECT4_32_VERT_HITS);
16280 }
16281 if !skip {
16282 hit!(RECT4_COEFF_HITS);
16283 }
16284 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16285 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16286 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16287 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16288 // transform size in both TXFM_CONTEXT bands. Without it the next block
16289 // reads the row's stale value.
16290 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16291 return Ok((mode, uv_predict_mode));
16292 }
16293 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16294 // that is 8 px tall, so each strip stamps every cell it touches and the
16295 // LAST strip wins -- which is the right answer for the block below/right
16296 // of the 32x32, the only reader outside it. Written after this strip's
16297 // own context read above, never before.
16298 for cell in 0..bw.div_ceil(SUB) {
16299 neighbours.above_mode[c + cell] = mode;
16300 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16301 neighbours.above_side[c + cell] = bw;
16302 }
16303 for cell in 0..bh.div_ceil(SUB) {
16304 neighbours.left_mode[r + cell] = mode;
16305 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16306 neighbours.left_side[r + cell] = bh;
16307 }
16308 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16309 // [`decode_leaf_rect`] does (the split arm above records these through
16310 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16311 // `sub8_mode_row` holding the previous block, and the next 32x32's
16312 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16313 // fixture).
16314 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16315 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16316 let (px, py) = (mi_c * MI, mi_r * MI);
16317 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16318 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16319 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16320 // lane-av1-444: the strip's chroma shape follows the subsampling.
16321 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16322 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16323 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16324 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16325 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16326 // and 1/1 only -- so the table is exhaustive.
16327 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16328 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16329 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16330 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16331 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16332 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16333 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
16334 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
16335 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
16336 // [`decode_rect_split`]'s chroma table use.
16337 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
16338 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
16339 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
16340 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
16341 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
16342 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
16343 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
16344 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
16345 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
16346 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
16347 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
16348 // instead of refusing; no coefficient-table row is added, because
16349 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
16350 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
16351 // 4:2:2-only.
16352 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
16353 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
16354 // lane-av1-422p: the units' own set/scan -- the whole-rect read
16355 // below never sees this row, the `chroma422_rect32` arm chunks
16356 // first. Anything else is still a named-lane gap.
16357 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
16358 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
16359 };
16360 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
16361 let (luma_levels, u_levels, v_levels) = if skip {
16362 (
16363 vec![0i32; bw * bh],
16364 vec![0i32; chroma_w * chroma_h],
16365 vec![0i32; chroma_w * chroma_h],
16366 )
16367 } else if chroma422_rect32 {
16368 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
16369 // plane-major (every U unit, then every V) -- the walk the pinned
16370 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
16371 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
16372 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
16373 // Luma is the same single TX_8X32 rect the general arm reads.
16374 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16375 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16376 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16377 dec,
16378 &mut luma_coding,
16379 luma_scan,
16380 bw,
16381 bh,
16382 0,
16383 dc_sign_ctx(around[0].2),
16384 TxType::DctDct,
16385 0,
16386 )?;
16387 hit!(RECT4_COEFF_HITS);
16388 let luma_residual = dequant_and_inverse_typed_wh(
16389 &luma_levels,
16390 bw,
16391 bh,
16392 crate::decode::bit_depth(fctx),
16393 block_q_idx(fctx),
16394 plane_q_delta(0, fctx).0,
16395 plane_q_delta(0, fctx).1,
16396 luma_tx_type,
16397 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16398 );
16399 if let Some(b) = &palette_y_buf {
16400 set_palette_pred(b.clone(), fctx);
16401 }
16402 push_intra_rect(
16403 0,
16404 px,
16405 py,
16406 bw,
16407 bh,
16408 mode,
16409 angle_delta_y,
16410 reach,
16411 &luma_residual,
16412 None,
16413 filter_intra,
16414 smooth_neighbor,
16415 fctx,
16416 );
16417 // CfL parameters are computed ONCE per block over the strip's luma
16418 // (`are_parameters_computed`) and shared by all four units, as in
16419 // every other chunk arm.
16420 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16421 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
16422 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16423 for unit_row in 0..4usize {
16424 let unit_mi = (mi_r + unit_row * 2, mi_c);
16425 let unit_reach = tu_reach_rect(
16426 bw,
16427 bh,
16428 0,
16429 unit_row * 8,
16430 8,
16431 8,
16432 reach,
16433 px,
16434 py,
16435 y.width,
16436 y.height,
16437 fctx,
16438 );
16439 if let Some((ub, vb)) = &palette_uv_bufs {
16440 let pbuf = if plane == 1 { ub } else { vb };
16441 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16442 }
16443 // Each unit is read and recorded IMMEDIATELY: unit row 0's
16444 // `txb_skip_ctx` still sees the real above/left neighbour
16445 // states, a lower unit sees this block's own upper unit's
16446 // (libaom's per-unit `set_entropy_context`), and the lower
16447 // unit predicts off the upper one's reconstructed samples.
16448 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
16449 let unit_grid = read_rect_chroma_unit(
16450 dec,
16451 cdfs,
16452 TxbSet::ChromaRect8x4,
16453 &SCAN_4X8,
16454 4,
16455 8,
16456 plane,
16457 chroma_around[plane],
16458 uv_predict_mode,
16459 angle_delta_uv,
16460 unit_reach,
16461 buf,
16462 cpx,
16463 cpy + unit_row * 8,
16464 base_q_idx,
16465 // `get_txb_ctx_general`'s chroma branch
16466 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
16467 // here, `num_pels_log2_lookup[255]` = 255 (the +255
16468 // byte of the decodetxb copy at 0xc0de70,
16469 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
16470 // ctx_offset is 10 -- the port's offset-7-first
16471 // `txb_skip_chroma_8` stores the offset-10 rows at
16472 // rows 3..6, hence +3.
16473 Some(3),
16474 alpha
16475 .zip(ac)
16476 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16477 smooth_neighbor_uv,
16478 fctx,
16479 )?;
16480 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
16481 unit_grids.push((unit_mi, plane, unit_grid));
16482 }
16483 }
16484 // The whole-block stamp rewrites the chroma cells ONE state wide,
16485 // which would erase the unit boundary the next block reads (class
16486 // `override-slot-on-one-arm`), so it carries zero chroma grids and
16487 // the per-unit writes replay after it. Its luma cells and side
16488 // spans are this arm's own bookkeeping.
16489 let zero_chroma = vec![0i32; chroma_w * chroma_h];
16490 neighbours.record_mi_rect(
16491 (mi_r, mi_c),
16492 bw,
16493 bh,
16494 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
16495 );
16496 for (unit_mi, plane, grid) in &unit_grids {
16497 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
16498 }
16499 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16500 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16501 record_strip_palette(
16502 neighbours,
16503 pal_at,
16504 bw,
16505 bh,
16506 pal_y_size,
16507 pal_y_colors,
16508 pal_uv_size,
16509 pal_uv_colors,
16510 );
16511 if bw > bh {
16512 hit!(RECT4_32_HORZ_HITS);
16513 } else {
16514 hit!(RECT4_32_VERT_HITS);
16515 }
16516 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16517 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16518 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16519 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16520 // transform size in both TXFM_CONTEXT bands. Without it the next block
16521 // reads the row's stale value.
16522 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16523 return Ok((mode, uv_predict_mode));
16524 } else {
16525 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16526 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16527 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16528 dec,
16529 &mut luma_coding,
16530 luma_scan,
16531 bw,
16532 bh,
16533 0,
16534 dc_sign_ctx(around[0].2),
16535 TxType::DctDct,
16536 0,
16537 )?;
16538 let mut planes = Vec::with_capacity(2);
16539 for plane in 1..3 {
16540 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
16541 // stands only while it is a member of this tx size's set; a
16542 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
16543 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
16544 // to DCT_DCT there, and ADST is undefined at widths above 16.
16545 let default_tx = if chroma_w.max(chroma_h) >= 32 {
16546 TxType::DctDct
16547 } else {
16548 default_intra_tx_type(uv_predict_mode as u8)
16549 };
16550 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
16551 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
16552 let (levels, tx_type) = read_chroma_coeffs_rect(
16553 dec,
16554 &mut coding,
16555 chroma_scan,
16556 chroma_w,
16557 chroma_h,
16558 skip_ctx,
16559 dc_sign_ctx(around[plane].2),
16560 default_tx,
16561 fctx,
16562 plane,
16563 )?;
16564 planes.push((levels, tx_type));
16565 }
16566 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
16567 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
16568 hit!(RECT4_COEFF_HITS);
16569 let luma_residual = dequant_and_inverse_typed_wh(
16570 &luma_levels,
16571 bw,
16572 bh,
16573 crate::decode::bit_depth(fctx),
16574 block_q_idx(fctx),
16575 plane_q_delta(0, fctx).0,
16576 plane_q_delta(0, fctx).1,
16577 luma_tx_type,
16578 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16579 );
16580 if let Some(b) = &palette_y_buf {
16581 set_palette_pred(b.clone(), fctx);
16582 }
16583 push_intra_rect(
16584 0,
16585 px,
16586 py,
16587 bw,
16588 bh,
16589 mode,
16590 angle_delta_y,
16591 reach,
16592 &luma_residual,
16593 None,
16594 filter_intra,
16595 smooth_neighbor,
16596 fctx,
16597 );
16598 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16599 for (plane, _buf, levels, tx_type) in [
16600 (1usize, &mut *u, &u_levels, u_tx_type),
16601 (2, &mut *v, &v_levels, v_tx_type),
16602 ] {
16603 let residual = dequant_and_inverse_typed_wh(
16604 levels,
16605 chroma_w,
16606 chroma_h,
16607 crate::decode::bit_depth(fctx),
16608 block_q_idx(fctx),
16609 plane_q_delta(plane, fctx).0,
16610 plane_q_delta(plane, fctx).1,
16611 tx_type,
16612 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
16613 );
16614 if let Some((ub, vb)) = &palette_uv_bufs {
16615 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
16616 }
16617 push_intra_rect(
16618 plane,
16619 cpx,
16620 cpy,
16621 chroma_w,
16622 chroma_h,
16623 uv_predict_mode,
16624 angle_delta_uv,
16625 reach,
16626 &residual,
16627 alpha
16628 .zip(ac)
16629 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16630 None,
16631 smooth_neighbor_uv,
16632 fctx,
16633 );
16634 }
16635 neighbours.record_mi_rect(
16636 (mi_r, mi_c),
16637 bw,
16638 bh,
16639 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16640 );
16641 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16642 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16643 record_strip_palette(
16644 neighbours,
16645 pal_at,
16646 bw,
16647 bh,
16648 pal_y_size,
16649 pal_y_colors,
16650 pal_uv_size,
16651 pal_uv_colors,
16652 );
16653 if bw > bh {
16654 hit!(RECT4_32_HORZ_HITS);
16655 } else {
16656 hit!(RECT4_32_VERT_HITS);
16657 }
16658 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16659 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16660 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16661 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16662 // transform size in both TXFM_CONTEXT bands. Without it the next block
16663 // reads the row's stale value.
16664 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16665 return Ok((mode, uv_predict_mode));
16666 };
16667 if let Some(b) = &palette_y_buf {
16668 set_palette_pred(b.clone(), fctx);
16669 }
16670 push_intra_rect(
16671 0,
16672 px,
16673 py,
16674 bw,
16675 bh,
16676 mode,
16677 angle_delta_y,
16678 reach,
16679 &luma_levels,
16680 None,
16681 filter_intra,
16682 smooth_neighbor,
16683 fctx,
16684 );
16685 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16686 if chroma422_rect32 {
16687 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
16688 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
16689 // arm walks the same four TX_4X8 units per plane -- the lower unit
16690 // predicts off the upper one's predicted samples. No coefficients
16691 // are coded; the tail's whole-block zero stamp below is the state
16692 // libaom's `set_entropy_context` leaves.
16693 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16694 for unit_row in 0..4usize {
16695 let unit_reach = tu_reach_rect(
16696 bw,
16697 bh,
16698 0,
16699 unit_row * 8,
16700 8,
16701 8,
16702 reach,
16703 px,
16704 py,
16705 y.width,
16706 y.height,
16707 fctx,
16708 );
16709 if let Some((ub, vb)) = &palette_uv_bufs {
16710 let pbuf = if plane == 1 { ub } else { vb };
16711 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16712 }
16713 push_intra_rect(
16714 plane,
16715 cpx,
16716 cpy + unit_row * 8,
16717 4,
16718 8,
16719 uv_predict_mode,
16720 angle_delta_uv,
16721 unit_reach,
16722 &ZERO_RESIDUAL[..4 * 8],
16723 alpha
16724 .zip(ac)
16725 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16726 None,
16727 smooth_neighbor_uv,
16728 fctx,
16729 );
16730 }
16731 }
16732 } else {
16733 if let Some((ub, _)) = &palette_uv_bufs {
16734 set_palette_pred(ub.clone(), fctx);
16735 }
16736 push_intra_rect(
16737 1,
16738 cpx,
16739 cpy,
16740 chroma_w,
16741 chroma_h,
16742 uv_predict_mode,
16743 angle_delta_uv,
16744 reach,
16745 &u_levels,
16746 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16747 None,
16748 smooth_neighbor_uv,
16749 fctx,
16750 );
16751 if let Some((_, vb)) = &palette_uv_bufs {
16752 set_palette_pred(vb.clone(), fctx);
16753 }
16754 push_intra_rect(
16755 2,
16756 cpx,
16757 cpy,
16758 chroma_w,
16759 chroma_h,
16760 uv_predict_mode,
16761 angle_delta_uv,
16762 reach,
16763 &v_levels,
16764 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16765 None,
16766 smooth_neighbor_uv,
16767 fctx,
16768 );
16769 }
16770 neighbours.record_mi_rect(
16771 (mi_r, mi_c),
16772 bw,
16773 bh,
16774 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16775 );
16776 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16777 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16778 record_strip_palette(
16779 neighbours,
16780 pal_at,
16781 bw,
16782 bh,
16783 pal_y_size,
16784 pal_y_colors,
16785 pal_uv_size,
16786 pal_uv_colors,
16787 );
16788 if bw > bh {
16789 hit!(RECT4_32_HORZ_HITS);
16790 } else {
16791 hit!(RECT4_32_VERT_HITS);
16792 }
16793 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16794 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16795 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16796 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16797 // transform size in both TXFM_CONTEXT bands. Without it the next block
16798 // reads the row's stale value.
16799 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16800 Ok((mode, uv_predict_mode))
16801}
16802
16803/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
16804/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
16805/// down, and the first shape here whose luma block is a single mi row (or
16806/// column).
16807///
16808/// What is new at this size is CHROMA. `is_chroma_reference`
16809/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
16810/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
16811/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
16812/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
16813/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
16814/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
16815/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
16816///
16817/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
16818/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
16819/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
16820/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
16821/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
16822/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
16823/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
16824/// shape's own CDF row.
16825///
16826/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
16827/// refuses by name rather than guess-decode.
16828#[allow(clippy::too_many_arguments)]
16829fn decode_rect4_16(
16830 dec: &mut SymbolDecoder,
16831 cdfs: &mut Cdfs,
16832 neighbours: &mut Neighbours,
16833 at16: (usize, usize),
16834 horz: bool,
16835 y: &mut PlaneBuf<'static>,
16836 u: &mut PlaneBuf<'static>,
16837 v: &mut PlaneBuf<'static>,
16838 enable_filter_intra: bool,
16839 allow_screen_content_tools: bool,
16840 base_q_idx: u8,
16841 tx_select: bool,
16842 reduced_tx_set: bool,
16843 fctx: &crate::decode::FrameCtx,
16844) -> Result<()> {
16845 let (r, c) = at16;
16846 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
16847 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
16848 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
16849 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
16850 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
16851 let mut prev: Option<((usize, usize), usize)> = None;
16852 let mut last_mode = DC_PRED;
16853 let mut last_uv_mode = DC_PRED;
16854 for i in 0..4usize {
16855 let lmi = if horz {
16856 (mi_row0 + i, mi_col0)
16857 } else {
16858 (mi_row0, mi_col0 + i)
16859 };
16860 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
16861 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
16862 // already >= 4x4) -- there is no 4:2:0 pair to close.
16863 // lane-av1-422o: the parity rule is per axis, straight out of
16864 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
16865 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
16866 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
16867 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
16868 // every ss_x == 1 format -- the ODD strip closes the pair and reads
16869 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
16870 // even mi_col, so `i % 2 == 1` is that clause.)
16871 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
16872 let (mode, uv, _tx) = decode_rect4_16_strip(
16873 dec,
16874 cdfs,
16875 neighbours,
16876 lmi,
16877 horz,
16878 has_chroma,
16879 prev,
16880 y,
16881 u,
16882 v,
16883 enable_filter_intra,
16884 allow_screen_content_tools,
16885 base_q_idx,
16886 tx_select,
16887 reduced_tx_set,
16888 fctx,
16889 )?;
16890 if let Some(m) = uv {
16891 last_uv_mode = m;
16892 }
16893 last_mode = mode;
16894 prev = Some((lmi, mode));
16895 }
16896 // The coarse 16-px cell holds one entry for the whole 16x16: the last
16897 // strip is what a block below (right) sees through it, the mi-exact maps
16898 // above answering everything finer.
16899 neighbours.above_mode[c] = last_mode;
16900 neighbours.left_mode[r] = last_mode;
16901 neighbours.above_uv_mode[c] = last_uv_mode;
16902 neighbours.left_uv_mode[r] = last_uv_mode;
16903 neighbours.above_side[c] = bw;
16904 neighbours.left_side[r] = bh;
16905 Ok(())
16906}
16907
16908/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
16909/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
16910/// block path can decode a SINGLE intra strip of a partition whose other
16911/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
16912/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
16913/// every strip publishes its own mi-exact mode). Returns
16914/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
16915/// Intrabc reconstruction for a rect strip that OWNS its chroma
16916/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
16917/// pair goes through [`decode_rect4_16_intrabc`].
16918///
16919/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
16920/// (predict once, then one residual per transform unit on the INTER sets,
16921/// chroma inherits luma's `tx_type`), written against the helpers that exist
16922/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
16923/// merge with lane-av1-intrabc should keep one of the two bodies; the call
16924/// shape is the same.
16925#[allow(clippy::too_many_arguments)]
16926fn decode_intrabc_owned_rect(
16927 dec: &mut SymbolDecoder,
16928 cdfs: &mut Cdfs,
16929 neighbours: &mut Neighbours,
16930 (mi_r, mi_c): (usize, usize),
16931 (bw, bh): (usize, usize),
16932 skip: bool,
16933 (dv_row, dv_col): (i32, i32),
16934 y: &mut PlaneBuf<'static>,
16935 u: &mut PlaneBuf<'static>,
16936 v: &mut PlaneBuf<'static>,
16937 base_q_idx: u8,
16938 tx_select: bool,
16939 reduced_tx_set: bool,
16940 fctx: &crate::decode::FrameCtx,
16941) -> Result<()> {
16942 let _ = base_q_idx;
16943 let (px, py) = (mi_c * MI, mi_r * MI);
16944 // lane-av1chromarect: libaom does NOT halve a 128-root intra-BC strip's
16945 // chroma plane block. `av1_get_max_uv_txsize` (blockd.h:1372) is
16946 // `max_txsize_rect_lookup[get_plane_block_size(bsize, ss_x, ss_y)]` run
16947 // through `av1_get_adjusted_tx_size`, and `get_plane_block_size` is
16948 // `ss_size_lookup[bsize]` -- at 4:4:4 the chroma plane block is the block's
16949 // OWN footprint, so the extent below and the eight chroma MV origin pairs
16950 // that follow must be `>> ss_x` / `>> ss_y`, not `/ 2`. At 4:2:0
16951 // (`ss_x == ss_y == 1`) the two forms are the same arithmetic.
16952 // MEASURED on the 4:4:4 LOSSY witness `fixtures/r512.obu` (6948 B, 3
16953 // frames, 5 strips through this function): with the halving, frame 0
16954 // diverges from the aomdec oracle in 166229 Y / 155383 U / 153498 V
16955 // samples and both later frames keep luma byte-exact while 74708 U +
16956 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
16957 // what makes this a chroma-sizing defect and not a block-geometry one.
16958 // Re-measured by this lane; see lanes/av1chromarect.report.md.
16959 if crate::envflags::env_flag!("EC_HALVSWEEP") {
16960 eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
16961 }
16962 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16963 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16964 let side = bw.max(bh);
16965 let cside = cw.max(ch);
16966 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
16967 hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS);
16968 }
16969 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16970 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
16971 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16972 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
16973 // false; the real bit is the caller's `tx_select`. Restored before return.
16974 fctx.tx_select_inter.with(|c| c.set(tx_select));
16975 let restore = ReducedTxRestore {
16976 fctx,
16977 saved_reduced,
16978 saved_tx,
16979 };
16980
16981 flush_recon(fctx, y, u, v);
16982 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
16983 let pred_u = predict_intrabc_window(u, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
16984 let pred_v = predict_intrabc_window(v, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
16985
16986 let mi_cols = 2 * y.true_width.div_ceil(8);
16987 let mi_rows = 2 * y.true_height.div_ceil(8);
16988 let leaves = read_block_tx_size_rect(
16989 dec,
16990 cdfs,
16991 neighbours,
16992 (mi_r, mi_c),
16993 (bw, bh),
16994 (mi_cols, mi_rows),
16995 skip,
16996 fctx,
16997 )?;
16998 let mut luma_tx_type = TxType::DctDct;
16999 let luma_grid;
17000 let u_grid;
17001 let v_grid;
17002 if skip {
17003 // `reconstruct_mc_rect` indexes the residual at the square stride.
17004 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
17005 push_mc_rect(
17006 0,
17007 px,
17008 py,
17009 side,
17010 bw,
17011 bh,
17012 Pred::Inline(&pred_y, side),
17013 &ZERO_RESIDUAL[..side * bh],
17014 fctx,
17015 );
17016 push_mc_rect(
17017 1,
17018 cpx,
17019 cpy,
17020 cside,
17021 cw,
17022 ch,
17023 Pred::Inline(&pred_u, cside),
17024 &ZERO_RESIDUAL[..cside * ch],
17025 fctx,
17026 );
17027 push_mc_rect(
17028 2,
17029 cpx,
17030 cpy,
17031 cside,
17032 cw,
17033 ch,
17034 Pred::Inline(&pred_v, cside),
17035 &ZERO_RESIDUAL[..cside * ch],
17036 fctx,
17037 );
17038 if let Some(ls) = leaves.as_ref() {
17039 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
17040 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
17041 // whole entropy-band footprint. The non-skip arm below writes
17042 // those bands per transform unit and the tail's
17043 // `record_split_luma_rect_mi` writes chroma only, so without
17044 // this walk a skipped strip whose `leaves` resolved (every
17045 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
17046 // returns the 4x4 grid before it looks at `skip`) leaked the
17047 // PREVIOUS occupant's luma bands into the next block's
17048 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
17049 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
17050 // stream left a stale 7 in left[48] and mi(48,68)'s first
17051 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
17052 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
17053 for &(row, col, tw, th) in ls {
17054 neighbours.record_mi_luma_rect(
17055 (mi_r + row, mi_c + col),
17056 tw,
17057 th,
17058 &ZERO_RESIDUAL[..tw * th],
17059 );
17060 }
17061 }
17062 luma_grid = Grid::Zero(side * side);
17063 u_grid = Grid::Zero(cside * cside);
17064 v_grid = Grid::Zero(cside * cside);
17065 } else if let Some(ls) = leaves.as_ref() {
17066 let mut leaf_types: Vec<(usize, usize, usize, usize, TxType)> =
17067 Vec::with_capacity(ls.len());
17068 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17069 let tu_mi = (mi_r + row, mi_c + col);
17070 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17071 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17072 let (g, tt) = if tw == th {
17073 read_inter_plane(
17074 dec,
17075 cdfs,
17076 inter_txbset_for(tw, reduced_tx_set),
17077 &default_scan(tw.min(32)),
17078 0,
17079 neighbours.around_mi(tu_mi, tw)[0],
17080 0,
17081 y,
17082 tu_px,
17083 tu_py,
17084 tw,
17085 base_q_idx,
17086 tu_pred,
17087 None,
17088 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17089 fctx,
17090 )?
17091 } else {
17092 read_inter_plane_rect(
17093 dec,
17094 cdfs,
17095 rect_inter_luma_set(tw, th, fctx)?,
17096 (tw, th),
17097 side,
17098 0,
17099 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17100 0,
17101 y,
17102 tu_px,
17103 tu_py,
17104 tu_pred,
17105 None,
17106 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17107 fctx,
17108 )?
17109 };
17110 leaf_types.push((row, col, tw, th, tt));
17111 if idx == 0 {
17112 luma_tx_type = tt;
17113 }
17114 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17115 if tw != th {
17116 neighbours.fill_lf_grid_leaf_luma(
17117 (tu_mi.0, tu_mi.1),
17118 tw / MI,
17119 th / MI,
17120 tw as u8,
17121 th as u8,
17122 );
17123 }
17124 }
17125 luma_grid = Grid::Zero(side * side);
17126 if cw.min(32) != cw || ch.min(32) != ch {
17127 // lane-av1chromarect: more than one chroma transform unit (the
17128 // 4:4:4 32x64/64x32 plane block). See the helper.
17129 let (ug, vg) = read_intrabc_rect_chroma_split(
17130 dec,
17131 cdfs,
17132 neighbours,
17133 (mi_r, mi_c),
17134 (cpx, cpy),
17135 (cw, ch),
17136 cside,
17137 &pred_u,
17138 &pred_v,
17139 &leaf_types,
17140 luma_tx_type,
17141 u,
17142 v,
17143 fctx,
17144 )?;
17145 u_grid = ug;
17146 v_grid = vg;
17147 } else {
17148 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17149 let (ug, _) = read_inter_plane_rect(
17150 dec,
17151 cdfs,
17152 rect_inter_chroma_set(cw, ch)?,
17153 (cw, ch),
17154 cside,
17155 1,
17156 around[1],
17157 0,
17158 u,
17159 cpx,
17160 cpy,
17161 Pred::Inline(&pred_u, cside),
17162 Some(luma_tx_type),
17163 None,
17164 fctx,
17165 )?;
17166 let (vg, _) = read_inter_plane_rect(
17167 dec,
17168 cdfs,
17169 rect_inter_chroma_set(cw, ch)?,
17170 (cw, ch),
17171 cside,
17172 2,
17173 around[2],
17174 0,
17175 v,
17176 cpx,
17177 cpy,
17178 Pred::Inline(&pred_v, cside),
17179 Some(luma_tx_type),
17180 None,
17181 fctx,
17182 )?;
17183 u_grid = ug;
17184 v_grid = vg;
17185 }
17186 } else {
17187 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17188 let (g, tt) = read_inter_plane_rect(
17189 dec,
17190 cdfs,
17191 rect_inter_luma_set(bw, bh, fctx)?,
17192 (bw, bh),
17193 side,
17194 0,
17195 around[0],
17196 0,
17197 y,
17198 px,
17199 py,
17200 Pred::Inline(&pred_y, side),
17201 None,
17202 None,
17203 fctx,
17204 )?;
17205 luma_tx_type = tt;
17206 luma_grid = g;
17207 if cw.min(32) != cw || ch.min(32) != ch {
17208 // lane-av1chromarect: more than one chroma transform unit (the
17209 // 4:4:4 32x64/64x32 plane block). See the helper.
17210 let (ug, vg) = read_intrabc_rect_chroma_split(
17211 dec,
17212 cdfs,
17213 neighbours,
17214 (mi_r, mi_c),
17215 (cpx, cpy),
17216 (cw, ch),
17217 cside,
17218 &pred_u,
17219 &pred_v,
17220 &[],
17221 luma_tx_type,
17222 u,
17223 v,
17224 fctx,
17225 )?;
17226 u_grid = ug;
17227 v_grid = vg;
17228 } else {
17229 let (ug, _) = read_inter_plane_rect(
17230 dec,
17231 cdfs,
17232 rect_inter_chroma_set(cw, ch)?,
17233 (cw, ch),
17234 cside,
17235 1,
17236 around[1],
17237 0,
17238 u,
17239 cpx,
17240 cpy,
17241 Pred::Inline(&pred_u, cside),
17242 Some(luma_tx_type),
17243 None,
17244 fctx,
17245 )?;
17246 let (vg, _) = read_inter_plane_rect(
17247 dec,
17248 cdfs,
17249 rect_inter_chroma_set(cw, ch)?,
17250 (cw, ch),
17251 cside,
17252 2,
17253 around[2],
17254 0,
17255 v,
17256 cpx,
17257 cpy,
17258 Pred::Inline(&pred_v, cside),
17259 Some(luma_tx_type),
17260 None,
17261 fctx,
17262 )?;
17263 u_grid = ug;
17264 v_grid = vg;
17265 }
17266 }
17267 drop(restore);
17268 // lane-av1chromarect: when the chroma plane block was walked as SEVERAL
17269 // transform units, each unit stamped its own span through
17270 // `record_mi_chroma` and the whole-block stamp below would overwrite them
17271 // with one state (class `override-slot-on-one-arm`). libaom keeps the
17272 // per-unit above/left contexts distinct; the next block's first unit
17273 // reads them.
17274 // `!skip` matters: a SKIPPED strip reads no chroma unit at all (its whole
17275 // chroma plane block is one `push_mc_rect` of `ZERO_RESIDUAL`), so no
17276 // per-unit `record_mi_chroma` ran and the whole-block chroma stamp below
17277 // is still the only one that happens.
17278 let chroma_split_units = !skip && (cw.min(32) != cw || ch.min(32) != ch);
17279 if leaves.is_some() {
17280 if chroma_split_units {
17281 neighbours.record_split_luma_rect_mi_modes((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED);
17282 } else {
17283 neighbours.record_split_luma_rect_mi(
17284 (mi_r, mi_c),
17285 bw,
17286 bh,
17287 DC_PRED,
17288 DC_PRED,
17289 [&u_grid, &v_grid],
17290 );
17291 }
17292 } else if chroma_split_units {
17293 neighbours.record_rect_mi_luma_only((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &luma_grid);
17294 } else {
17295 neighbours.record_rect_mi(
17296 (mi_r, mi_c),
17297 bw,
17298 bh,
17299 DC_PRED,
17300 DC_PRED,
17301 &[&luma_grid, &u_grid, &v_grid],
17302 );
17303 }
17304 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17305 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17306 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17307 neighbours.fill_lf_grid_rect(
17308 (mi_r, mi_c),
17309 bw / MI,
17310 bh / MI,
17311 bw.min(64) as u8,
17312 bh.min(64) as u8,
17313 0,
17314 fctx,
17315 );
17316 record_intrabc_mi_rect(
17317 mi_r,
17318 mi_c,
17319 bw / MI,
17320 bh / MI,
17321 Some((dv_row, dv_col)),
17322 neighbours,
17323 fctx,
17324 );
17325 let _ = luma_tx_type;
17326 Ok(())
17327}
17328
17329/// The chroma plane block of a 128-root intra-BC HORZ/VERT strip when that
17330/// plane block needs MORE THAN ONE transform unit -- the 4:4:4 cell, and the
17331/// 4:2:0 cell of a strip with a 128-px axis.
17332///
17333/// libaom never forms a 64-point CHROMA transform. `get_vartx_max_txsize`
17334/// (blockd.h:1447) returns `av1_get_adjusted_tx_size(max_txsize_rect_lookup
17335/// [plane_bsize])` and `av1_get_adjusted_tx_size` maps `TX_32X64`/`TX_64X32`
17336/// to `TX_32X32`; `decode_token_recon_block` (decodeframe.c:994-1004) then
17337/// steps the plane block by that size's mi units, and
17338/// `decode_reconstruct_tx`'s `tx_size == plane_tx_size || plane` arm never
17339/// recurses for chroma -- the same statement from the other side. So a 4:4:4
17340/// 32x64 chroma plane block is TWO stacked `TX_32X32` units, each with its
17341/// own eob, its own scan and its own coefficient context, NOT one 32x64 unit
17342/// whose coded corner happens to be 32x32: `av1_get_max_eob`'s 64-axis
17343/// truncation is a LUMA rule, and a chroma plane block is never 64 points
17344/// long to begin with.
17345///
17346/// That is exactly the tiling [`read_inter_rect_chroma`] implements
17347/// (`(write_chroma_w.min(32), write_chroma_h.min(32))` and the `nx * ny`
17348/// walk); this is the same walk for a caller that keeps its own grid
17349/// assembly and neighbour recording. The single-unit case is deliberately
17350/// NOT routed through here, so at 4:2:0 and at every 4:4:4 shape below 64
17351/// the caller keeps its own one-unit read verbatim.
17352#[allow(clippy::too_many_arguments)]
17353fn read_intrabc_rect_chroma_split(
17354 dec: &mut SymbolDecoder,
17355 cdfs: &mut Cdfs,
17356 neighbours: &mut Neighbours,
17357 (mi_r, mi_c): (usize, usize),
17358 (cpx, cpy): (usize, usize),
17359 (cw, ch): (usize, usize),
17360 cside: usize,
17361 pred_u: &[u16],
17362 pred_v: &[u16],
17363 leaf_tx_types: &[(usize, usize, usize, usize, TxType)],
17364 luma_tx_type: TxType,
17365 u: &mut PlaneBuf<'static>,
17366 v: &mut PlaneBuf<'static>,
17367 fctx: &crate::decode::FrameCtx,
17368) -> Result<(Grid, Grid)> {
17369 let (uw, uh) = (cw.min(32), ch.min(32));
17370 let (nx, ny) = (cw / uw, ch / uh);
17371 let set = rect_inter_chroma_set(uw, uh)?;
17372 let assembled_h = ch.max(cside);
17373 let mut assembled: [Vec<i32>; 2] = [
17374 vec![0i32; cside * assembled_h],
17375 vec![0i32; cside * assembled_h],
17376 ];
17377 for plane_idx in 1..=2 {
17378 let (src, buf) = if plane_idx == 1 {
17379 (pred_u, &mut *u)
17380 } else {
17381 (pred_v, &mut *v)
17382 };
17383 for cu_row in 0..ny {
17384 for cu_col in 0..nx {
17385 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
17386 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
17387 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
17388 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
17389 let cu_pred = Pred::Inline(src, cside).offset(cu_row * uh * cside + cu_col * uw);
17390 // libaom's `av1_get_tx_type` (blockd.h:1287) reads
17391 // `xd->tx_type_map` at the chroma unit's OWN position scaled
17392 // back to luma, so a unit sitting over a luma leaf that coded
17393 // nothing takes that leaf's stamp, not the block-level one.
17394 let rel_mi = (cu_mi.0 - mi_r, cu_mi.1 - mi_c);
17395 let inherit_tx_type =
17396 covering_leaf_tx_type(leaf_tx_types, rel_mi).or(Some(luma_tx_type));
17397 let cu_grid = read_inter_plane_rect(
17398 dec,
17399 cdfs,
17400 set,
17401 (uw, uh),
17402 cside,
17403 plane_idx,
17404 cu_around[plane_idx],
17405 0,
17406 buf,
17407 cu_x,
17408 cu_y,
17409 cu_pred,
17410 inherit_tx_type,
17411 // `get_txb_ctx`: plus 10 when the plane block is bigger
17412 // than the transform -- the same offset-3 convention
17413 // `read_inter_rect_chroma` passes on this arm.
17414 Some(3),
17415 fctx,
17416 )?
17417 .0;
17418 // Immediately, so the next unit of this block reads this one's
17419 // coefficient context (libaom updates the chroma above/left
17420 // contexts per unit).
17421 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
17422 let dst = &mut assembled[plane_idx - 1];
17423 for rr in 0..uh {
17424 let start = (cu_row * uh + rr) * cside + cu_col * uw;
17425 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
17426 }
17427 }
17428 }
17429 }
17430 let [ug, vg] = assembled;
17431 Ok((Grid::Own(ug), Grid::Own(vg)))
17432}
17433
17434fn predict_intrabc_window(
17435 plane: &PlaneBuf<'_>,
17436 px: usize,
17437 py: usize,
17438 w: usize,
17439 h: usize,
17440 dv_col: i32,
17441 dv_row: i32,
17442 luma: bool,
17443 stride: usize,
17444 fctx: &crate::decode::FrameCtx,
17445) -> Vec<u16> {
17446 let mut dense = vec![0u16; w * h];
17447 mc::predict_with_filter(
17448 &plane.data,
17449 plane.width,
17450 plane.true_width,
17451 plane.true_height,
17452 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
17453 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
17454 w,
17455 h,
17456 mc::InterpFilterKind::Bilinear,
17457 &mut dense,
17458 fctx,
17459 );
17460 let mut laid = vec![0u16; stride * stride];
17461 for row in 0..h {
17462 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
17463 }
17464 laid
17465}
17466
17467struct ReducedTxRestore<'a> {
17468 fctx: &'a crate::decode::FrameCtx,
17469 saved_reduced: bool,
17470 saved_tx: bool,
17471}
17472impl Drop for ReducedTxRestore<'_> {
17473 fn drop(&mut self) {
17474 self.fctx
17475 .reduced_tx_set_inter
17476 .with(|c| c.set(self.saved_reduced));
17477 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
17478 }
17479}
17480
17481/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
17482///
17483/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
17484/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
17485/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
17486/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
17487/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
17488/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
17489/// strip's own footprint, copied from this strip's DV. The block is
17490/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
17491/// the luma unit's coded `tx_type`.
17492///
17493/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
17494/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
17495/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
17496/// would code chroma on every strip.
17497#[allow(clippy::too_many_arguments)]
17498fn decode_rect4_16_intrabc(
17499 dec: &mut SymbolDecoder,
17500 cdfs: &mut Cdfs,
17501 neighbours: &mut Neighbours,
17502 lmi: (usize, usize),
17503 horz: bool,
17504 has_chroma: bool,
17505 skip: bool,
17506 (dv_row, dv_col): (i32, i32),
17507 y: &mut PlaneBuf<'static>,
17508 u: &mut PlaneBuf<'static>,
17509 v: &mut PlaneBuf<'static>,
17510 base_q_idx: u8,
17511 tx_select: bool,
17512 reduced_tx_set: bool,
17513 fctx: &crate::decode::FrameCtx,
17514) -> Result<(usize, Option<usize>, (usize, usize))> {
17515 let _ = base_q_idx;
17516 hit!(RECT4_16_INTRABC_HITS);
17517 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17518 let (mi_w, mi_h) = (bw / MI, bh / MI);
17519 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17520 let side = bw.max(bh);
17521 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
17522 // publishes `reduced_tx_set` into it; set it here too so a caller that
17523 // passed the bit explicitly cannot disagree with the set we read.
17524 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17525 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17526 let restored = scopeguard_reduced(fctx, saved_reduced);
17527
17528 flush_recon(fctx, y, u, v);
17529 let mut pred_y_dense = vec![0u16; bw * bh];
17530 mc::predict_with_filter(
17531 &y.data,
17532 y.width,
17533 y.true_width,
17534 y.true_height,
17535 mv_to_q4(px, dv_col, 0),
17536 mv_to_q4(py, dv_row, 0),
17537 bw,
17538 bh,
17539 mc::InterpFilterKind::Bilinear,
17540 &mut pred_y_dense,
17541 fctx,
17542 );
17543 let mut pred_y = vec![0u16; side * side];
17544 for row in 0..bh {
17545 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
17546 }
17547
17548 // lane-av1444rect r2 (the class this lane named, second instance): the
17549 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
17550 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
17551 // unconditionally true -- the strip is its own chroma reference, there is
17552 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
17553 // (VERT_4) at the strip's own origin, with its coefficient context read
17554 // over that same extent. The old constants instead predicted and coded an
17555 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
17556 //
17557 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
17558 // --enable-palette=1 --cq-level=60 --min-partition-size=4
17559 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
17560 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
17561 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
17562 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
17563 // twin of the same recipe is byte-exact.
17564 //
17565 // 4:2:0 and 4:2:2 keep every constant below verbatim -- the arm is gated on
17566 // the full ss (0,0), not on a per-axis shift, so `pw / 2` and the literal
17567 // halving are untouched for both.
17568 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
17569 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
17570 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
17571 }
17572 let (pw, ph) = if own444 {
17573 (bw, bh)
17574 } else if horz {
17575 (16usize, 8usize)
17576 } else {
17577 (8, 16)
17578 };
17579 let (cw, ch) = if own444 { (bw, bh) } else { (pw / 2, ph / 2) };
17580 let pair_mi = if has_chroma {
17581 if own444 {
17582 lmi
17583 } else if horz {
17584 (lmi.0 - 1, lmi.1)
17585 } else {
17586 (lmi.0, lmi.1 - 1)
17587 }
17588 } else {
17589 lmi
17590 };
17591 let (cpx, cpy) = if has_chroma {
17592 if own444 {
17593 (px, py)
17594 } else {
17595 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
17596 }
17597 } else {
17598 (0, 0)
17599 };
17600 let cside = cw.max(ch);
17601 let (pred_u, pred_v) = if has_chroma {
17602 let mut ud = vec![0u16; cw * ch];
17603 mc::predict_with_filter(
17604 &u.data,
17605 u.width,
17606 u.true_width,
17607 u.true_height,
17608 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17609 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17610 cw,
17611 ch,
17612 mc::InterpFilterKind::Bilinear,
17613 &mut ud,
17614 fctx,
17615 );
17616 let mut us = vec![0u16; cside * cside];
17617 for row in 0..ch {
17618 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
17619 }
17620 let mut vd = vec![0u16; cw * ch];
17621 mc::predict_with_filter(
17622 &v.data,
17623 v.width,
17624 v.true_width,
17625 v.true_height,
17626 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17627 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17628 cw,
17629 ch,
17630 mc::InterpFilterKind::Bilinear,
17631 &mut vd,
17632 fctx,
17633 );
17634 let mut vs = vec![0u16; cside * cside];
17635 for row in 0..ch {
17636 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
17637 }
17638 (us, vs)
17639 } else {
17640 (Vec::new(), Vec::new())
17641 };
17642
17643 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
17644 // false for a key frame, so `read_block_tx_size_rect` would skip the
17645 // symbol; read it here against the parameter the intra path already uses.
17646 // A skipped intrabc block predicts the whole footprint once and codes
17647 // no residual (`decode_token_recon_block`'s inter branch). Lossless
17648 // still forces TX_4X4 when the block is coded.
17649 let leaves = if skip || (!lossless(fctx) && !tx_select) {
17650 None
17651 } else if lossless(fctx) {
17652 let mut leaves = Vec::new();
17653 for row in 0..bh / MI {
17654 for col in 0..bw / MI {
17655 leaves.push((row, col, 4usize, 4usize));
17656 }
17657 }
17658 Some(leaves)
17659 } else {
17660 let ctx = txfm_partition_ctx_rect(
17661 neighbours.above_txfm[lmi.1],
17662 neighbours.left_txfm[lmi.0],
17663 side,
17664 bw,
17665 bh,
17666 );
17667 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17668 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17669 let (rng, _) = dec.debug_state();
17670 eprintln!(
17671 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17672 lmi.0,
17673 lmi.1,
17674 u8::from(split)
17675 );
17676 }
17677 if !split {
17678 None
17679 } else {
17680 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
17681 let mi_cols = 2 * y.true_width.div_ceil(8);
17682 let mi_rows = 2 * y.true_height.div_ceil(8);
17683 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
17684 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
17685 let mut out = Vec::new();
17686 for row in (0..bh / MI).step_by(sub_h / MI) {
17687 for col in (0..bw / MI).step_by(sub_w / MI) {
17688 read_var_tx_size(
17689 dec,
17690 cdfs,
17691 neighbours,
17692 lmi,
17693 side,
17694 (max_w_mi, max_h_mi),
17695 (sub_w, sub_h),
17696 1,
17697 row,
17698 col,
17699 &mut out,
17700 );
17701 }
17702 }
17703 Some(out)
17704 }
17705 };
17706 let (tx_w, tx_h) = leaves
17707 .as_ref()
17708 .and_then(|ls| ls.first())
17709 .map_or((bw, bh), |l| (l.2, l.3));
17710
17711 let mut luma_tx_type = TxType::DctDct;
17712 let luma_grid;
17713 let mut u_grid = Grid::Zero(cw * ch);
17714 let mut v_grid = Grid::Zero(cw * ch);
17715 let chroma_stamped_per_unit;
17716
17717 if skip {
17718 push_mc_rect(
17719 0,
17720 px,
17721 py,
17722 side,
17723 bw,
17724 bh,
17725 Pred::Inline(&pred_y, side),
17726 &ZERO_RESIDUAL[..side * bh],
17727 fctx,
17728 );
17729 luma_grid = Grid::Zero(bw * bh);
17730 if has_chroma {
17731 push_mc_rect(
17732 1,
17733 cpx,
17734 cpy,
17735 cside,
17736 cw,
17737 ch,
17738 Pred::Inline(&pred_u, cside),
17739 &ZERO_RESIDUAL[..cside * ch],
17740 fctx,
17741 );
17742 push_mc_rect(
17743 2,
17744 cpx,
17745 cpy,
17746 cside,
17747 cw,
17748 ch,
17749 Pred::Inline(&pred_v, cside),
17750 &ZERO_RESIDUAL[..cside * ch],
17751 fctx,
17752 );
17753 }
17754 chroma_stamped_per_unit = false;
17755 } else if let Some(ls) = leaves.as_ref() {
17756 if lossless(fctx) {
17757 for &(row, col, _tw, _th) in ls {
17758 let tu_mi = (lmi.0 + row, lmi.1 + col);
17759 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17760 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17761 let (g, _) = read_inter_plane(
17762 dec,
17763 cdfs,
17764 if reduced_tx_set {
17765 TxbSet::Luma4Inter
17766 } else {
17767 TxbSet::Luma4InterSet1
17768 },
17769 &default_scan(4),
17770 0,
17771 neighbours.around_mi(tu_mi, 4)[0],
17772 0,
17773 y,
17774 tu_px,
17775 tu_py,
17776 4,
17777 base_q_idx,
17778 tu_pred,
17779 None,
17780 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
17781 fctx,
17782 )?;
17783 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
17784 }
17785 } else {
17786 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17787 let tu_mi = (lmi.0 + row, lmi.1 + col);
17788 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17789 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17790 let (g, tt) = if tw == th {
17791 read_inter_plane(
17792 dec,
17793 cdfs,
17794 inter_txbset_for(tw, reduced_tx_set),
17795 &default_scan(tw.min(32)),
17796 0,
17797 neighbours.around_mi(tu_mi, tw)[0],
17798 0,
17799 y,
17800 tu_px,
17801 tu_py,
17802 tw,
17803 base_q_idx,
17804 tu_pred,
17805 None,
17806 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17807 fctx,
17808 )?
17809 } else {
17810 read_inter_plane_rect(
17811 dec,
17812 cdfs,
17813 rect_inter_luma_set(tw, th, fctx)?,
17814 (tw, th),
17815 side,
17816 0,
17817 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17818 0,
17819 y,
17820 tu_px,
17821 tu_py,
17822 tu_pred,
17823 None,
17824 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17825 fctx,
17826 )?
17827 };
17828 if idx == 0 {
17829 luma_tx_type = tt;
17830 }
17831 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17832 }
17833 }
17834 luma_grid = Grid::Zero(bw * bh);
17835 chroma_stamped_per_unit = has_chroma && lossless(fctx);
17836 if has_chroma && lossless(fctx) {
17837 let (mut uo, mut vo) = (Vec::new(), Vec::new());
17838 read_inter_chroma_lossless(
17839 dec,
17840 cdfs,
17841 neighbours,
17842 u,
17843 v,
17844 Pred::Inline(&pred_u, cside),
17845 Pred::Inline(&pred_v, cside),
17846 pair_mi,
17847 (cpx, cpy),
17848 (0, 0),
17849 (cw, ch),
17850 (cw, ch),
17851 cside,
17852 0,
17853 base_q_idx,
17854 &mut uo,
17855 &mut vo,
17856 fctx,
17857 )?;
17858 u_grid = if uo.is_empty() {
17859 Grid::Zero(cw * ch)
17860 } else {
17861 Grid::Own(uo)
17862 };
17863 v_grid = if vo.is_empty() {
17864 Grid::Zero(cw * ch)
17865 } else {
17866 Grid::Own(vo)
17867 };
17868 } else if has_chroma {
17869 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17870 let (ug, _) = read_inter_plane_rect(
17871 dec,
17872 cdfs,
17873 rect_inter_chroma_set(cw, ch)?,
17874 (cw, ch),
17875 cside,
17876 1,
17877 around[1],
17878 0,
17879 u,
17880 cpx,
17881 cpy,
17882 Pred::Inline(&pred_u, cside),
17883 Some(luma_tx_type),
17884 None,
17885 fctx,
17886 )?;
17887 u_grid = ug;
17888 let (vg, _) = read_inter_plane_rect(
17889 dec,
17890 cdfs,
17891 rect_inter_chroma_set(cw, ch)?,
17892 (cw, ch),
17893 cside,
17894 2,
17895 around[2],
17896 0,
17897 v,
17898 cpx,
17899 cpy,
17900 Pred::Inline(&pred_v, cside),
17901 Some(luma_tx_type),
17902 None,
17903 fctx,
17904 )?;
17905 v_grid = vg;
17906 }
17907 } else {
17908 let around = neighbours.around_mi_rect(lmi, bw, bh);
17909 let (g, tt) = read_inter_plane_rect(
17910 dec,
17911 cdfs,
17912 rect_inter_luma_set(bw, bh, fctx)?,
17913 (bw, bh),
17914 side,
17915 0,
17916 around[0],
17917 0,
17918 y,
17919 px,
17920 py,
17921 Pred::Inline(&pred_y, side),
17922 None,
17923 None,
17924 fctx,
17925 )?;
17926 luma_tx_type = tt;
17927 luma_grid = g;
17928 chroma_stamped_per_unit = false;
17929 if has_chroma {
17930 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17931 let (ug, _) = read_inter_plane_rect(
17932 dec,
17933 cdfs,
17934 rect_inter_chroma_set(cw, ch)?,
17935 (cw, ch),
17936 cside,
17937 1,
17938 around[1],
17939 0,
17940 u,
17941 cpx,
17942 cpy,
17943 Pred::Inline(&pred_u, cside),
17944 Some(luma_tx_type),
17945 None,
17946 fctx,
17947 )?;
17948 u_grid = ug;
17949 let (vg, _) = read_inter_plane_rect(
17950 dec,
17951 cdfs,
17952 rect_inter_chroma_set(cw, ch)?,
17953 (cw, ch),
17954 cside,
17955 2,
17956 around[2],
17957 0,
17958 v,
17959 cpx,
17960 cpy,
17961 Pred::Inline(&pred_v, cside),
17962 Some(luma_tx_type),
17963 None,
17964 fctx,
17965 )?;
17966 v_grid = vg;
17967 }
17968 }
17969 drop(restored);
17970
17971 if leaves.is_none() {
17972 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
17973 }
17974 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
17975 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17976 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17977 for cell in 0..mi_w {
17978 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
17979 *slot = bw as u8;
17980 }
17981 }
17982 for cell in 0..mi_h {
17983 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
17984 *slot = bh as u8;
17985 }
17986 }
17987 let mut last_uv = None;
17988 if has_chroma {
17989 hit!(RECT4_16_CHROMA_HITS);
17990 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
17991 if !chroma_stamped_per_unit {
17992 let u_state = neighbour_state(&u_grid);
17993 let v_state = neighbour_state(&v_grid);
17994 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17995 let bound_h = round_up_even(neighbours.mi_rows);
17996 let bound_w = round_up_even(neighbours.mi_cols);
17997 for cell in 0..(ph / MI) {
17998 if pair_mi.0 + cell < bound_h
17999 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18000 {
18001 slot[1] = u_state;
18002 slot[2] = v_state;
18003 }
18004 }
18005 for cell in 0..(pw / MI) {
18006 if pair_mi.1 + cell < bound_w
18007 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18008 {
18009 slot[1] = u_state;
18010 slot[2] = v_state;
18011 }
18012 }
18013 }
18014 last_uv = Some(DC_PRED);
18015 }
18016 if horz {
18017 hit!(RECT4_16_HORZ_HITS);
18018 } else {
18019 hit!(RECT4_16_VERT_HITS);
18020 }
18021 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
18022 if leaves.is_none() {
18023 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
18024 // with `skip && is_inter`, or the unsplit unit). A split tree already
18025 // published per leaf inside `read_var_tx_size`.
18026 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18027 }
18028 record_intrabc_mi_rect(
18029 lmi.0,
18030 lmi.1,
18031 mi_w,
18032 mi_h,
18033 Some((dv_row, dv_col)),
18034 neighbours,
18035 fctx,
18036 );
18037 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
18038}
18039
18040/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
18041/// including through `?`.
18042struct ReducedRestore<'a> {
18043 fctx: &'a crate::decode::FrameCtx,
18044 saved: bool,
18045}
18046impl Drop for ReducedRestore<'_> {
18047 fn drop(&mut self) {
18048 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
18049 }
18050}
18051fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
18052 ReducedRestore { fctx, saved }
18053}
18054
18055#[allow(clippy::too_many_arguments)]
18056fn decode_rect4_16_strip(
18057 dec: &mut SymbolDecoder,
18058 cdfs: &mut Cdfs,
18059 neighbours: &mut Neighbours,
18060 lmi: (usize, usize),
18061 horz: bool,
18062 has_chroma: bool,
18063 prev: Option<((usize, usize), usize)>,
18064 y: &mut PlaneBuf<'static>,
18065 u: &mut PlaneBuf<'static>,
18066 v: &mut PlaneBuf<'static>,
18067 enable_filter_intra: bool,
18068 allow_screen_content_tools: bool,
18069 base_q_idx: u8,
18070 tx_select: bool,
18071 reduced_tx_set: bool,
18072 fctx: &crate::decode::FrameCtx,
18073) -> Result<(usize, Option<usize>, (usize, usize))> {
18074 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
18075 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
18076 let (mi_w, mi_h) = (bw / MI, bh / MI);
18077 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
18078 let mut last_uv_mode: Option<usize> = None;
18079 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
18080 // aliases all four strips onto one entry, so the mi-exact map wins and
18081 // the previous strip stands in on the split axis.
18082 let mut above_mode = neighbours.above_mode[c];
18083 let mut left_mode = neighbours.left_mode[r];
18084 if let Some(((pr, pc), pmode)) = prev {
18085 if pc == lmi.1 && lmi.0 == pr + mi_h {
18086 above_mode = pmode;
18087 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
18088 left_mode = pmode;
18089 }
18090 }
18091 let (above_mode, left_mode) =
18092 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
18093 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
18094 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
18095 // off CDF row 0 and every cache hit off an empty cache.
18096 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
18097 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
18098 let (
18099 skip,
18100 mode,
18101 angle_delta_y,
18102 uv_mode,
18103 angle_delta_uv,
18104 alpha,
18105 filter_intra,
18106 palette_y,
18107 palette_uv,
18108 intrabc,
18109 ) = read_intra_mode_rect(
18110 dec,
18111 cdfs,
18112 above_mode,
18113 left_mode,
18114 true,
18115 has_chroma,
18116 bw,
18117 bh,
18118 enable_filter_intra,
18119 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
18120 allow_screen_content_tools,
18121 Some((palette_ctx, &palette_cache)),
18122 &palette_uv_cache,
18123 lmi.0,
18124 lmi.1,
18125 fctx,
18126 )?;
18127 if let Some(dv) = intrabc {
18128 return decode_rect4_16_intrabc(
18129 dec,
18130 cdfs,
18131 neighbours,
18132 lmi,
18133 horz,
18134 has_chroma,
18135 skip,
18136 dv,
18137 y,
18138 u,
18139 v,
18140 base_q_idx,
18141 tx_select,
18142 reduced_tx_set,
18143 fctx,
18144 );
18145 }
18146 if palette_y.is_some() || palette_uv.is_some() {
18147 hit!(RECT4_PALETTE_HITS);
18148 }
18149 // The colour-index map through the base colours IS the prediction.
18150 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
18151 // chroma transform this closing strip codes.
18152 let palette_y_buf: Option<Vec<u16>> = palette_y
18153 .as_ref()
18154 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
18155 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
18156 (
18157 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18158 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18159 )
18160 });
18161 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
18162 if smooth_neighbor {
18163 hit!(SMOOTH_LUMA_HITS);
18164 }
18165 if filter_intra.is_some() {
18166 hit!(FILTER_INTRA_RECT_HITS);
18167 }
18168 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
18169 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
18170 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
18171 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
18172 // lane-av1mixloss: the lossless-segment early return
18173 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
18174 // lossless-segment strip codes no depth symbol here either (class
18175 // sweep of the sub8 leaf's fix).
18176 let depth = if tx_select && !lossless(fctx) {
18177 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
18178 // (`get_tx_size_context`, libaom `pred_common.h:342`).
18179 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
18180 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
18181 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18182 eprintln!(
18183 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
18184 lmi.0,
18185 lmi.1,
18186 dec.debug_state().0
18187 );
18188 }
18189 d
18190 } else {
18191 0
18192 };
18193 if depth != 0 {
18194 hit!(TX_DEPTH_HITS);
18195 hit!(RECT4_16_SPLIT_HITS);
18196 }
18197 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18198 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18199 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18200 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
18201 if depth != 0 || lossless(fctx) {
18202 // [`decode_rect_split`]'s per-unit walk, inlined because the
18203 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
18204 // the strip (that function codes one chroma transform per block).
18205 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
18206 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
18207 // unit predicts off the units before it in raster order.
18208 let rect_unit = tx_w != tx_h;
18209 let zero_tu = vec![0i32; tx_w * tx_h];
18210 for tu_row in 0..bh / tx_h {
18211 for tu_col in 0..bw / tx_w {
18212 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
18213 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
18214 let tu_reach =
18215 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
18216 if let Some(b) = &palette_y_buf {
18217 let tu_buf: Vec<u16> = (0..tx_h)
18218 .flat_map(|i| {
18219 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
18220 b[base..base + tx_w].iter().copied()
18221 })
18222 .collect();
18223 set_palette_pred(tu_buf, fctx);
18224 }
18225 if skip {
18226 push_intra_rect(
18227 0,
18228 tu_px,
18229 tu_py,
18230 tx_w,
18231 tx_h,
18232 mode,
18233 angle_delta_y,
18234 tu_reach,
18235 &zero_tu,
18236 None,
18237 filter_intra,
18238 smooth_neighbor,
18239 fctx,
18240 );
18241 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
18242 } else if rect_unit {
18243 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
18244 // 32 coded positions and the `TX_4X4` `tx_type` row:
18245 // exactly [`TxbSet::LumaRect4x8`].
18246 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
18247 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
18248 let set = if reduced_tx_set {
18249 TxbSet::LumaRect4x8
18250 } else {
18251 TxbSet::LumaRect4x8Set1
18252 };
18253 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
18254 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18255 let (tu_grid, tu_tx_type) = read_coeffs_rect(
18256 dec,
18257 &mut coding,
18258 tu_scan,
18259 tx_w,
18260 tx_h,
18261 tu_skip_ctx,
18262 dc_sign_ctx(tu_around.2),
18263 TxType::DctDct,
18264 0,
18265 )?;
18266 let residual = dequant_and_inverse_typed_wh(
18267 &tu_grid,
18268 tx_w,
18269 tx_h,
18270 crate::decode::bit_depth(fctx),
18271 block_q_idx(fctx),
18272 plane_q_delta(0, fctx).0,
18273 plane_q_delta(0, fctx).1,
18274 tu_tx_type,
18275 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
18276 );
18277 push_intra_rect(
18278 0,
18279 tu_px,
18280 tu_py,
18281 tx_w,
18282 tx_h,
18283 mode,
18284 angle_delta_y,
18285 tu_reach,
18286 &residual,
18287 None,
18288 filter_intra,
18289 smooth_neighbor,
18290 fctx,
18291 );
18292 if tu_grid.iter().any(|&l| l != 0) {
18293 hit!(RECT4_16_COEFF_HITS);
18294 }
18295 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
18296 } else {
18297 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
18298 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
18299 let tu_grid = read_plane(
18300 dec,
18301 cdfs,
18302 txbset_for(tx_w, reduced_tx_set),
18303 default_scan(tx_w),
18304 0,
18305 tu_around,
18306 mode,
18307 mode,
18308 angle_delta_y,
18309 tu_reach,
18310 y,
18311 tu_px,
18312 tu_py,
18313 tx_w,
18314 tx_w,
18315 base_q_idx,
18316 None,
18317 filter_intra,
18318 Some(tu_skip_ctx),
18319 smooth_neighbor,
18320 fctx,
18321 )?;
18322 if tu_grid.iter().any(|&l| l != 0) {
18323 hit!(RECT4_16_COEFF_HITS);
18324 }
18325 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
18326 }
18327 }
18328 }
18329 } else {
18330 let levels = if skip {
18331 let zeros = Grid::Zero(bw * bh);
18332 if let Some(b) = &palette_y_buf {
18333 set_palette_pred(b.clone(), fctx);
18334 }
18335 push_intra_rect(
18336 0,
18337 px,
18338 py,
18339 bw,
18340 bh,
18341 mode,
18342 angle_delta_y,
18343 reach,
18344 &zeros,
18345 None,
18346 filter_intra,
18347 smooth_neighbor,
18348 fctx,
18349 );
18350 zeros
18351 } else {
18352 // The strip's luma TU *is* the strip (`plane_bsize ==
18353 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
18354 // `txb_skip_ctx` at 0.
18355 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
18356 let set = if reduced_tx_set {
18357 TxbSet::LumaRect16x4
18358 } else {
18359 TxbSet::LumaRect16x4Set1
18360 };
18361 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18362 let (levels, tx_type) = read_coeffs_rect(
18363 dec,
18364 &mut coding,
18365 scan,
18366 bw,
18367 bh,
18368 0,
18369 dc_sign_ctx(around.2),
18370 TxType::DctDct,
18371 0,
18372 )?;
18373 let residual = dequant_and_inverse_typed_wh(
18374 &levels,
18375 bw,
18376 bh,
18377 crate::decode::bit_depth(fctx),
18378 block_q_idx(fctx),
18379 plane_q_delta(0, fctx).0,
18380 plane_q_delta(0, fctx).1,
18381 tx_type,
18382 block_iqmatrix(fctx, 0, bw, bh, tx_type),
18383 );
18384 if let Some(b) = &palette_y_buf {
18385 set_palette_pred(b.clone(), fctx);
18386 }
18387 push_intra_rect(
18388 0,
18389 px,
18390 py,
18391 bw,
18392 bh,
18393 mode,
18394 angle_delta_y,
18395 reach,
18396 &residual,
18397 None,
18398 filter_intra,
18399 smooth_neighbor,
18400 fctx,
18401 );
18402 hit!(RECT4_16_COEFF_HITS);
18403 levels
18404 };
18405 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
18406 }
18407 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18408 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18409 // `update_partition_context` writes `partition_context_lookup[
18410 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
18411 // the left (mirrored under VERT_4).
18412 for cell in 0..mi_w {
18413 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18414 *slot = bw as u8;
18415 }
18416 }
18417 for cell in 0..mi_h {
18418 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18419 *slot = bh as u8;
18420 }
18421 }
18422 if has_chroma {
18423 hit!(RECT4_16_CHROMA_HITS);
18424 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
18425 // own chroma reference and codes its own 16x4 / 4x16 chroma
18426 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
18427 // ss 0/0, so the neighbour reads below anchor at the strip.)
18428 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
18429 (lmi, bw, bh)
18430 } else if ss_y(fctx) == 0 && horz {
18431 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
18432 // 16x4 strip is its own chroma reference (`is_chroma_reference`
18433 // at ss(1,0): bh == 1 mi, so the row clause reduces to
18434 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
18435 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
18436 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
18437 // the pair merge below -- its own chroma block
18438 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
18439 // walk proved such leaves exist, and libaom codes the pair's
18440 // chroma from the closing strip; the chunk lives in the
18441 // `chroma422_pair16` arm below.)
18442 (lmi, bw, bh)
18443 } else if horz {
18444 ((lmi.0 - 1, lmi.1), 16, 8)
18445 } else {
18446 ((lmi.0, lmi.1 - 1), 8, 16)
18447 };
18448 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
18449 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
18450 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
18451 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
18452 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
18453 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
18454 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
18455 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
18456 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
18457 // `decode_token_recon_block` walks unit_width =
18458 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
18459 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
18460 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
18461 // walks per unit: `predict_and_reconstruct_intra_block` predicts
18462 // every unit regardless of `skip_txfm`.
18463 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
18464 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18465 DC_PRED
18466 } else {
18467 uv_mode
18468 };
18469 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
18470 hit!(RECT4_16_CHROMA_DIR_HITS);
18471 }
18472 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
18473 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
18474 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
18475 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
18476 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
18477 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
18478 // the pair's top-left luma mi, never this leaf's odd row/column.
18479 // Reading `lmi` here named the leaf directly above (a non-chroma
18480 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
18481 // SMOOTH neighbour: filt_type 0 instead of 1 turned
18482 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
18483 // directional chroma strip, moving 4 samples by 1.
18484 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
18485 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
18486 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
18487 // counter's mirror of the snapping form, and the shipped read offsets
18488 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
18489 //
18490 // lane-av1leftwit: this mirror is NOT evidence about the left read's
18491 // `+ss_y` term, whatever a report once said. It reads the leaf's own
18492 // (odd) mi row, which no decode call site does -- every one of them
18493 // uses the snapping form, whose base row is even -- and its result
18494 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
18495 // and worth keeping (the pair's chroma-reference read against the
18496 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
18497 // so it stays; the decode path's own reach for the `+ss_y` term is
18498 // `uv_left_1mi_split_hits()`.
18499 if smooth_neighbor_uv
18500 != neighbours.smooth_uv_neighbour_unsnapped(
18501 lmi.0,
18502 lmi.1,
18503 r,
18504 c,
18505 ss_x(fctx),
18506 ss_y(fctx),
18507 false,
18508 )
18509 {
18510 hit!(RECT4_16_UV_PAIR_FILT_HITS);
18511 }
18512 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
18513 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
18514 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
18515 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
18516 // the rect here consumed one symbol block too few and desynced
18517 // the next strip's `skip` (measured: lossless sb128 320x240,
18518 // mi(1,20) uv_mode matched, the following skip did not).
18519 let lossless_pair = lossless(fctx);
18520 let (u_levels, v_levels) = if lossless_pair {
18521 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
18522 if skip {
18523 for plane in 1..3usize {
18524 for rr in 0..ch / 4 {
18525 for cc in 0..cw / 4 {
18526 let (ox, oy) = (cc * 4, rr * 4);
18527 // The unit's origin and extent in LUMA pixels: `<< ss`
18528 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
18529 // at 4:4:4 -- the same form as the block-walk sibling
18530 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
18531 // only right at ss (1,1): at 4:4:4 it claims a 4x4
18532 // chroma unit is 8x8 luma, so `of_tu`'s
18533 // `col_off + tx_w < bw` test answers against a
18534 // footprint twice the real one and every unit past
18535 // the block's midpoint wrongly reports
18536 // `above_right = false` -- a directional chroma
18537 // strip then predicts from a neighbour libaom
18538 // never reads (measured: key frame 0, 4:4:4 lossless
18539 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
18540 // entropy bit-identical over 351109 EC_SYMR reads).
18541 let cu_reach = tu_reach(
18542 pw,
18543 ph,
18544 ox << ss_x(fctx),
18545 oy << ss_y(fctx),
18546 4 << ss_x(fctx),
18547 pair_reach,
18548 ppx,
18549 ppy,
18550 y.width,
18551 y.height,
18552 fctx,
18553 );
18554 if let Some((ub, vb)) = &palette_uv_bufs {
18555 let buf = if plane == 1 { ub } else { vb };
18556 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18557 }
18558 push_intra(
18559 plane,
18560 cpx + ox,
18561 cpy + oy,
18562 4,
18563 uv_predict_mode,
18564 angle_delta_uv,
18565 cu_reach,
18566 &ZERO_RESIDUAL[..16],
18567 None,
18568 None,
18569 smooth_neighbor_uv,
18570 fctx,
18571 );
18572 let cu_mi = (
18573 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18574 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18575 );
18576 neighbours.record_mi_chroma(
18577 cu_mi,
18578 4 << ss_x(fctx),
18579 4 << ss_y(fctx),
18580 plane,
18581 &ZERO_RESIDUAL[..16],
18582 );
18583 }
18584 }
18585 }
18586 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18587 } else {
18588 let scan4 = default_scan(4);
18589 // `get_txb_ctx`: offset 10 (our tables store it at +3)
18590 // when the plane block is larger than the transform.
18591 let offset = Some(3usize);
18592 let mut uo = vec![0i32; cw * ch];
18593 let mut vo = vec![0i32; cw * ch];
18594 for plane in 1..3usize {
18595 for rr in 0..ch / 4 {
18596 for cc in 0..cw / 4 {
18597 let (ox, oy) = (cc * 4, rr * 4);
18598 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
18599 continue;
18600 }
18601 // The unit's stamp is its own span: aom
18602 // `av1_set_entropy_contexts` (blockd.c:29)
18603 // memsets exactly `tx_size_wide_unit` x
18604 // `tx_size_high_unit` cells at the unit's own
18605 // `(aoff, loff)` -- for TX_4X4 ONE above cell
18606 // and ONE left cell. `(oy / 2, ox / 2)` +
18607 // `(8, 8)` is the 4:2:0 subsampled form (one
18608 // chroma cell = 8 luma px = 2 mi cells); at
18609 // 4:4:4 a unit is ONE mi cell, and the 2x2
18610 // smear let a 4-wide strip's later units
18611 // overwrite the NEXT COLUMN's above cell with
18612 // their own state -- a column aom never sees
18613 // this block write -- so the following block's
18614 // `all_zero` read the wrong `txb_skip` row
18615 // (frame-0 read #452, the llkf named gap).
18616 let cu_mi = (
18617 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18618 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18619 );
18620 // One luma-mi cell: the chroma entropy arrays
18621 // are subsampled, and our bands replicate that
18622 // one entry over the unit's two cells
18623 // (`read_intra_chroma_lossless`).
18624 let cu_around = neighbours.around_mi(cu_mi, MI);
18625 // Same ss-aware luma footprint as the skip arm
18626 // above -- `ox * 2 / 8` is the 4:2:0-only form and
18627 // mis-answers `of_tu` at 4:4:4 (see there).
18628 let cu_reach = tu_reach(
18629 pw,
18630 ph,
18631 ox << ss_x(fctx),
18632 oy << ss_y(fctx),
18633 4 << ss_x(fctx),
18634 pair_reach,
18635 ppx,
18636 ppy,
18637 y.width,
18638 y.height,
18639 fctx,
18640 );
18641 if let Some((ub, vb)) = &palette_uv_bufs {
18642 let buf = if plane == 1 { ub } else { vb };
18643 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18644 }
18645 let buf: &mut PlaneBuf<'static> =
18646 if plane == 1 { &mut *u } else { &mut *v };
18647 let cu_grid = read_plane(
18648 dec,
18649 cdfs,
18650 TxbSet::Chroma4,
18651 &scan4,
18652 plane,
18653 cu_around[plane],
18654 mode,
18655 uv_predict_mode,
18656 angle_delta_uv,
18657 cu_reach,
18658 buf,
18659 cpx + ox,
18660 cpy + oy,
18661 4,
18662 4,
18663 base_q_idx,
18664 None,
18665 None,
18666 offset,
18667 smooth_neighbor_uv,
18668 fctx,
18669 )?;
18670 neighbours.record_mi_chroma(
18671 cu_mi,
18672 4 << ss_x(fctx),
18673 4 << ss_y(fctx),
18674 plane,
18675 &cu_grid,
18676 );
18677 hit!(CHROMA_SPLIT_TX_HITS);
18678 let dst = if plane == 1 { &mut uo } else { &mut vo };
18679 for row in 0..4 {
18680 let start = (oy + row) * cw + ox;
18681 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
18682 }
18683 }
18684 }
18685 }
18686 (Grid::Own(uo), Grid::Own(vo))
18687 }
18688 } else if skip {
18689 let zeros = Grid::Zero(cw * ch);
18690 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
18691 // ~1000) predicts EVERY plane and only guards the residual on
18692 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
18693 // DC + alpha * luma-AC. Dropping the CfL term here left a
18694 // chroma-only bounded box on ReelC's key frames.
18695 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18696 if alpha.is_some() {
18697 hit!(CHROMA_SKIP_CFL_HITS);
18698 }
18699 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
18700 if chroma422_pair16 {
18701 // lane-av1-422o: two TX_4X8 units, each predicted on
18702 // its own edges (the lower one off the upper one's
18703 // samples); no coefficients are coded, and libaom's
18704 // `set_entropy_context` zeroed the block's own cells,
18705 // so the pair-wide zero stamp below stays correct.
18706 for unit_row in 0..2usize {
18707 let unit_reach = tu_reach_rect(
18708 pw,
18709 ph,
18710 0,
18711 unit_row * 8,
18712 8,
18713 8,
18714 pair_reach,
18715 ppx,
18716 ppy,
18717 y.width,
18718 y.height,
18719 fctx,
18720 );
18721 if let Some((ub, vb)) = &palette_uv_bufs {
18722 let pbuf = if plane == 1 { ub } else { vb };
18723 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18724 }
18725 push_intra_rect(
18726 plane,
18727 cpx,
18728 cpy + unit_row * 8,
18729 4,
18730 8,
18731 uv_predict_mode,
18732 angle_delta_uv,
18733 unit_reach,
18734 &ZERO_RESIDUAL[..4 * 8],
18735 alpha
18736 .zip(ac)
18737 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18738 None,
18739 smooth_neighbor_uv,
18740 fctx,
18741 );
18742 }
18743 } else {
18744 if let Some((ub, vb)) = &palette_uv_bufs {
18745 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18746 }
18747 push_intra_rect(
18748 plane,
18749 cpx,
18750 cpy,
18751 cw,
18752 ch,
18753 uv_predict_mode,
18754 angle_delta_uv,
18755 pair_reach,
18756 &zeros,
18757 alpha
18758 .zip(ac)
18759 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18760 None,
18761 smooth_neighbor_uv,
18762 fctx,
18763 );
18764 }
18765 }
18766 (zeros.clone(), zeros)
18767 } else if chroma422_pair16 {
18768 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
18769 // per plane, plane-major (every U unit, then every V). Each
18770 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
18771 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
18772 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
18773 // offset comes from `num_pels_log2_lookup[plane_bsize] >
18774 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
18775 // BLOCK_INVALID (255), and the byte at that table's +255 in
18776 // the pinned Release oracle is 255 (`cmpb` against the
18777 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
18778 // arm: +3 on the offset-7-first chroma tables. No tx_type
18779 // symbol (only y plane's is transmitted); the unit's type is
18780 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
18781 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
18782 // are computed ONCE per block (`are_parameters_computed`)
18783 // over the pair's luma, shared by both units. Each unit is
18784 // predicted and recorded immediately, so the lower unit
18785 // reads the upper one's coefficient context.
18786 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18787 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
18788 for unit_row in 0..2usize {
18789 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
18790 let unit_reach = tu_reach_rect(
18791 pw,
18792 ph,
18793 0,
18794 unit_row * 8,
18795 8,
18796 8,
18797 pair_reach,
18798 ppx,
18799 ppy,
18800 y.width,
18801 y.height,
18802 fctx,
18803 );
18804 if let Some((ub, vb)) = &palette_uv_bufs {
18805 let pbuf = if plane == 1 { ub } else { vb };
18806 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18807 }
18808 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
18809 let unit_grid = read_rect_chroma_unit(
18810 dec,
18811 cdfs,
18812 TxbSet::ChromaRect8x4,
18813 &SCAN_4X8,
18814 4,
18815 8,
18816 plane,
18817 chroma_around[plane],
18818 uv_predict_mode,
18819 angle_delta_uv,
18820 unit_reach,
18821 buf,
18822 cpx,
18823 cpy + unit_row * 8,
18824 base_q_idx,
18825 // lane-av1-422q: the offset-10 rows -- the same
18826 // measured rule as the 4x32 arm (plane_bsize
18827 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
18828 // num_pels_log2_lookup[255] = 0xff at the
18829 // 0xc0de70 copy -> +3 on the offset-7-first
18830 // chroma tables; see lanes/av1422q.report.md).
18831 Some(3),
18832 alpha
18833 .zip(ac)
18834 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18835 smooth_neighbor_uv,
18836 fctx,
18837 )?;
18838 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
18839 }
18840 }
18841 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18842 } else {
18843 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
18844 // every second luma-mi cell
18845 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
18846 // chroma 4-px column spans two luma mi columns, and the
18847 // plain per-mi gather counts each column's whole-unit dc
18848 // sign twice). The left extent is unsubsampled at ss_y 0,
18849 // so its per-mi cells already line up one-to-one.
18850 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
18851 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
18852 } else {
18853 neighbours.around_mi_rect(pair_mi, pw, ph)
18854 };
18855 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
18856 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
18857 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
18858 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
18859 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
18860 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
18861 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
18862 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
18863 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
18864 // (4,16) never reaches this row; `chroma422_pair16`
18865 // intercepts it above and chunks it into TX_4X8 units.)
18866 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
18867 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
18868 // pair's height: an 8x8 SQUARE chroma block, the same
18869 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
18870 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
18871 // row is unreachable there. It is also the witness arm:
18872 // a restored `/2 chroma height` lands on (8,4) and the
18873 // counter reads 0.
18874 (8, 8) => {
18875 hit!(CHROMA422_SQUARE_HITS);
18876 (TxbSet::Chroma8, default_scan(8))
18877 }
18878 // lane-av1-422o: with the `chroma422_pair16` arm above,
18879 // the (2,16) own-strip shape and the 4:4:4 shapes are the
18880 // only residents; anything else is a named-lane gap.
18881 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
18882 };
18883 let mut planes = Vec::with_capacity(2);
18884 for plane in 1..3 {
18885 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
18886 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
18887 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
18888 let (levels, tx_type) = read_chroma_coeffs_rect(
18889 dec,
18890 &mut coding,
18891 chroma_scan,
18892 cw,
18893 ch,
18894 skip_ctx,
18895 dc_sign_ctx(around[plane].2),
18896 default_tx,
18897 fctx,
18898 plane,
18899 )?;
18900 planes.push((levels, tx_type));
18901 }
18902 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
18903 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
18904 // CfL averages the luma of the WHOLE pair, the region this one
18905 // chroma transform covers.
18906 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18907 for (plane, _buf, levels, tx_type) in [
18908 (1usize, &mut *u, &u_levels, u_tx_type),
18909 (2, &mut *v, &v_levels, v_tx_type),
18910 ] {
18911 let residual = dequant_and_inverse_typed_wh(
18912 levels,
18913 cw,
18914 ch,
18915 crate::decode::bit_depth(fctx),
18916 block_q_idx(fctx),
18917 plane_q_delta(plane, fctx).0,
18918 plane_q_delta(plane, fctx).1,
18919 tx_type,
18920 block_iqmatrix(fctx, plane, cw, ch, tx_type),
18921 );
18922 if let Some((ub, vb)) = &palette_uv_bufs {
18923 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18924 }
18925 push_intra_rect(
18926 plane,
18927 cpx,
18928 cpy,
18929 cw,
18930 ch,
18931 uv_predict_mode,
18932 angle_delta_uv,
18933 pair_reach,
18934 &residual,
18935 alpha
18936 .zip(ac)
18937 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18938 None,
18939 smooth_neighbor_uv,
18940 fctx,
18941 );
18942 }
18943 (u_levels, v_levels)
18944 };
18945 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
18946 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
18947 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
18948 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
18949 // the arm above (libaom's coefficient contexts are per
18950 // 4x4-cell); a pair-wide state would erase the unit boundary the
18951 // next block reads.
18952 if !lossless_pair && !chroma422_pair16 {
18953 // The chroma planes' coefficient context, over the PAIR's mi span
18954 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
18955 // the luma one rounded up to its 4x4 unit).
18956 let u_state = neighbour_state(&u_levels);
18957 let v_state = neighbour_state(&v_levels);
18958 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18959 let bound_h = round_up_even(neighbours.mi_rows);
18960 let bound_w = round_up_even(neighbours.mi_cols);
18961 for cell in 0..(ph / MI) {
18962 if pair_mi.0 + cell < bound_h
18963 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18964 {
18965 slot[1] = u_state;
18966 slot[2] = v_state;
18967 }
18968 }
18969 for cell in 0..(pw / MI) {
18970 if pair_mi.1 + cell < bound_w
18971 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18972 {
18973 slot[1] = u_state;
18974 slot[2] = v_state;
18975 }
18976 }
18977 }
18978 last_uv_mode = Some(uv_predict_mode);
18979 }
18980 if horz {
18981 hit!(RECT4_16_HORZ_HITS);
18982 } else {
18983 hit!(RECT4_16_VERT_HITS);
18984 }
18985 let (pal_y_size, pal_y_colors) = palette_y
18986 .as_ref()
18987 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18988 let (pal_uv_size, pal_uv_colors) = palette_uv
18989 .as_ref()
18990 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18991 record_strip_palette(
18992 neighbours,
18993 lmi,
18994 bw,
18995 bh,
18996 pal_y_size,
18997 pal_y_colors,
18998 pal_uv_size,
18999 pal_uv_colors,
19000 );
19001 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19002 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19003 // frame): the above row records `tx_size_wide` over the block's width and
19004 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19005 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19006 // and it published neither band -- so the block after a 64x16 strip read
19007 // the row's init value 64 as its left transform height and took
19008 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19009 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19010 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19011 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
19012 Ok((mode, last_uv_mode, (tx_w, tx_h)))
19013}
19014
19015/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
19016/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
19017/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
19018/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
19019/// cap, so LUMA needs the same corner truncation [`decode_block`] already
19020/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
19021/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
19022/// this function's own charter/report), so both strips read a real 32x32
19023/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
19024/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
19025/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
19026/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
19027/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
19028/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
19029/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
19030/// that function, only the single-transform-unit (`tx_depth == 0`) case is
19031/// supported: a split transform refuses by name rather than guess-decode.
19032#[allow(clippy::too_many_arguments)]
19033fn decode_block_rect64(
19034 dec: &mut SymbolDecoder,
19035 cdfs: &mut Cdfs,
19036 neighbours: &mut Neighbours,
19037 at: (usize, usize),
19038 bw: usize,
19039 bh: usize,
19040 y: &mut PlaneBuf<'static>,
19041 u: &mut PlaneBuf<'static>,
19042 v: &mut PlaneBuf<'static>,
19043 enable_filter_intra: bool,
19044 allow_screen_content_tools: bool,
19045 base_q_idx: u8,
19046 tx_select: bool,
19047 reduced_tx_set: bool,
19048 fctx: &crate::decode::FrameCtx,
19049) -> Result<()> {
19050 let (r, c) = at;
19051 let (px, py) = (c * SUB, r * SUB);
19052 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
19053 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
19054 let palette_uv_cache = neighbours.palette_uv_cache(at);
19055 let (
19056 skip,
19057 mode,
19058 angle_delta_y,
19059 uv_mode,
19060 angle_delta_uv,
19061 alpha,
19062 filter_intra,
19063 palette_y,
19064 palette_uv,
19065 intrabc,
19066 ) = read_intra_mode_rect(
19067 dec,
19068 cdfs,
19069 nb_above_mode,
19070 nb_left_mode,
19071 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
19072 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
19073 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
19074 // correct), CFL must never be offered here -- passing `true`
19075 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
19076 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
19077 // from this block's very first symbol (lane-sbpart r3 bisect).
19078 false,
19079 true,
19080 bw,
19081 bh,
19082 enable_filter_intra,
19083 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
19084 allow_screen_content_tools,
19085 Some((palette_ctx, &palette_cache)),
19086 &palette_uv_cache,
19087 r * (SUB / MI),
19088 c * (SUB / MI),
19089 fctx,
19090 )?;
19091 if let Some((dv_row, dv_col)) = intrabc {
19092 return decode_intrabc_owned_rect(
19093 dec,
19094 cdfs,
19095 neighbours,
19096 (r * (SUB / MI), c * (SUB / MI)),
19097 (bw, bh),
19098 skip,
19099 (dv_row, dv_col),
19100 y,
19101 u,
19102 v,
19103 base_q_idx,
19104 tx_select,
19105 reduced_tx_set,
19106 fctx,
19107 );
19108 }
19109 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
19110 // lane-t900 r34: a non-skip palette block on a superblock-level strip
19111 // -- counted so its gate cannot go vacuous (this was a refusal until
19112 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
19113 // decodes_pixel_exact`).
19114 hit!(PALETTE_SB_STRIP_HITS);
19115 }
19116 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
19117 if smooth_neighbor {
19118 hit!(SMOOTH_LUMA_HITS);
19119 }
19120 let smooth_neighbor_uv =
19121 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
19122 if filter_intra.is_some() {
19123 // `filter_intra_size_class_rect` already returns `None` for both
19124 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
19125 // 32 on both axes), so this symbol is never read at this level --
19126 // kept only as the same defensive refusal [`decode_block_rect`] has.
19127 return Err(unsupported(
19128 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
19129 av1_filter_intra_allowed_bsize caps at 32x32)",
19130 ));
19131 }
19132 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
19133 DC_PRED
19134 } else {
19135 uv_mode
19136 };
19137 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
19138 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
19139 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
19140 // no depth symbol here either (class sweep of the sub8 leaf's fix).
19141 let depth = if tx_select && !lossless(fctx) {
19142 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
19143 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
19144 // intra-only frame publishes them from every block too
19145 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
19146 // 1920x792 128-superblock stream,
19147 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
19148 // `tx_size_cat2` row 1 where libaom reads row 2.
19149 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
19150 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
19151 // counts `sub_tx_size_map` steps from the block's own max rect
19152 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
19153 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
19154 // steps, so this level's category is 3 (the same one a 64x64 square
19155 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
19156 // here was a wrong-table read of a real symbol.
19157 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
19158 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19159 eprintln!(
19160 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
19161 dec.debug_state().0
19162 );
19163 }
19164 d
19165 } else {
19166 0
19167 };
19168 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
19169 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
19170 publish_txfm_bands_if_in_inter(
19171 neighbours,
19172 (mi_r, mi_c),
19173 depth_to_tx_wh(bw, bh, depth, fctx),
19174 (bw, bh),
19175 fctx,
19176 );
19177 if depth != 0 || lossless(fctx) {
19178 hit!(TX_DEPTH_HITS);
19179 // lane-rectsplit r1/r4: the superblock-level strip splits its
19180 // transform through the very same per-unit path as its 32x32-level
19181 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
19182 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
19183 // measured the old square formula mis-tiling exactly that strip).
19184 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
19185 if bw.max(bh) / bw.min(bh) == 4 {
19186 let which = if depth == 1 {
19187 &RECT4_SPLIT_DEPTH1_HITS
19188 } else {
19189 &RECT4_SPLIT_DEPTH2_HITS
19190 };
19191 hit_do! { which.with(|c| c.set(c.get() + 1)); }
19192 }
19193 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19194 eprintln!(
19195 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
19196 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
19197 angle_y={angle_delta_y}"
19198 );
19199 }
19200 let modes = RectStripModes {
19201 skip,
19202 mode,
19203 angle_delta_y,
19204 uv_predict_mode,
19205 angle_delta_uv,
19206 alpha,
19207 filter_intra,
19208 smooth_neighbor,
19209 smooth_neighbor_uv,
19210 palette_y: palette_y
19211 .as_ref()
19212 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
19213 palette_uv: palette_uv.as_ref().map(|p| {
19214 (
19215 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
19216 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
19217 )
19218 }),
19219 };
19220 if palette_y.is_some() || palette_uv.is_some() {
19221 hit!(PALETTE_SPLIT_TX_HITS);
19222 }
19223 decode_rect_split(
19224 dec,
19225 cdfs,
19226 neighbours,
19227 (mi_r, mi_c),
19228 bw,
19229 bh,
19230 tx_w,
19231 tx_h,
19232 &modes,
19233 y,
19234 u,
19235 v,
19236 base_q_idx,
19237 reduced_tx_set,
19238 fctx,
19239 )?;
19240 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
19241 // (lane-palette2 r10): this return skips the fn's own tail, so a
19242 // split-tx superblock strip would otherwise leave the above/left
19243 // palette arrays holding a dead block's colours.
19244 let (py_size, py_colors) = palette_y
19245 .as_ref()
19246 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19247 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19248 let (puv_size, puv_colors) = palette_uv
19249 .as_ref()
19250 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19251 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19252 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
19253 // return skips the fn's own tail, so a SPLIT superblock-level strip
19254 // published no TXFM_CONTEXT band and the next block read the row's init
19255 // value 64 as its left transform height. Measured on the 10-bit
19256 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
19257 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
19258 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
19259 // bands carry the SPLIT unit's size, not the block's.
19260 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19261 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
19262 hit!(RECT_PARTITION_HITS);
19263 return Ok(());
19264 }
19265 let (tx_w, tx_h) = (bw, bh);
19266 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
19267 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
19268 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19269 if let Some(ref pyv) = palette_y {
19270 let buf: Vec<u16> = pyv
19271 .map
19272 .iter()
19273 .map(|&idx| pyv.colors[idx as usize])
19274 .collect();
19275 set_palette_pred(buf, fctx);
19276 }
19277 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
19278 (
19279 puv.map
19280 .iter()
19281 .map(|&idx| puv.u_colors[idx as usize])
19282 .collect(),
19283 puv.map
19284 .iter()
19285 .map(|&idx| puv.v_colors[idx as usize])
19286 .collect(),
19287 )
19288 });
19289 if skip {
19290 push_intra_rect(
19291 0,
19292 px,
19293 py,
19294 bw,
19295 bh,
19296 mode,
19297 angle_delta_y,
19298 reach,
19299 &ZERO_RESIDUAL[..bw * bh],
19300 None,
19301 filter_intra,
19302 smooth_neighbor,
19303 fctx,
19304 );
19305 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19306 if let Some((ub, _)) = &palette_uv_bufs {
19307 set_palette_pred(ub.clone(), fctx);
19308 }
19309 push_intra_rect(
19310 1,
19311 cpx,
19312 cpy,
19313 chroma_w,
19314 chroma_h,
19315 uv_predict_mode,
19316 angle_delta_uv,
19317 reach,
19318 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19319 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
19320 None,
19321 smooth_neighbor_uv,
19322 fctx,
19323 );
19324 if let Some((_, vb)) = &palette_uv_bufs {
19325 set_palette_pred(vb.clone(), fctx);
19326 }
19327 push_intra_rect(
19328 2,
19329 cpx,
19330 cpy,
19331 chroma_w,
19332 chroma_h,
19333 uv_predict_mode,
19334 angle_delta_uv,
19335 reach,
19336 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19337 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
19338 None,
19339 smooth_neighbor_uv,
19340 fctx,
19341 );
19342 neighbours.record_rect(
19343 at,
19344 bw,
19345 bh,
19346 mode,
19347 uv_predict_mode,
19348 &[
19349 &ZERO_RESIDUAL[..bw * bh],
19350 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19351 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19352 ],
19353 );
19354 } else {
19355 let around = neighbours.around_rect(at, bw, bh);
19356 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
19357 // (see this function's own doc comment). A 64-length axis codes only
19358 // its low 32 coefficients, so the corner is `min(bw, 32)` x
19359 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
19360 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
19361 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
19362 let scan32 = default_scan(TX32);
19363 if coeff_trace_on() {
19364 let (rng, _) = dec.debug_state();
19365 eprintln!(
19366 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
19367 );
19368 }
19369 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
19370 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
19371 read_coeffs(
19372 dec,
19373 &mut luma_coding,
19374 &scan32,
19375 0,
19376 dc_sign_ctx(around[0].2),
19377 TxType::DctDct,
19378 Some((bw, bh)),
19379 )?
19380 } else {
19381 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
19382 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
19383 // (`scan.c`) gives both the very same `default_scan_32x16` /
19384 // `default_scan_16x32` the 2:1 sizes use ("Half of the
19385 // coefficients of tx64 at higher frequencies are set to zeros. So
19386 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
19387 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
19388 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
19389 // 512-position eob group) -- BOTH identical to TX_32X16, so the
19390 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
19391 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
19392 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
19393 // what `base_ctx_rect` computes at (32, 16).
19394 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
19395 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
19396 read_coeffs_rect(
19397 dec,
19398 &mut luma_coding,
19399 luma_scan,
19400 luma_cw,
19401 luma_ch,
19402 0,
19403 dc_sign_ctx(around[0].2),
19404 TxType::DctDct,
19405 0,
19406 )?
19407 };
19408 if coeff_trace_on() {
19409 let (rng, _) = dec.debug_state();
19410 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
19411 }
19412 let mut luma_levels = vec![0i32; bw * bh];
19413 for row in 0..luma_ch {
19414 luma_levels[row * bw..][..luma_cw]
19415 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
19416 }
19417 {
19418 let cur = block_q_idx(fctx);
19419 if cur != i32::from(base_q_idx) {
19420 hit!(RECT64_QIDX_DRIFT_HITS);
19421 }
19422 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19423 eprintln!(
19424 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
19425 );
19426 }
19427 }
19428 let luma_residual = dequant_and_inverse_typed_wh(
19429 &luma_levels,
19430 bw,
19431 bh,
19432 crate::decode::bit_depth(fctx),
19433 block_q_idx(fctx),
19434 plane_q_delta(0, fctx).0,
19435 plane_q_delta(0, fctx).1,
19436 luma_tx_type,
19437 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
19438 );
19439 push_intra_rect(
19440 0,
19441 px,
19442 py,
19443 bw,
19444 bh,
19445 mode,
19446 angle_delta_y,
19447 reach,
19448 &luma_residual,
19449 None,
19450 filter_intra,
19451 smooth_neighbor,
19452 fctx,
19453 );
19454 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19455 let leftcol: Vec<u16> = if px > 0 {
19456 (py..py + bh)
19457 .map(|row| y.data[row * y.width + px - 1])
19458 .collect()
19459 } else {
19460 vec![]
19461 };
19462 eprintln!(
19463 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
19464 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
19465 luma_corner.iter().any(|&v| v != 0),
19466 &y.data[py * y.width + px..][..bw],
19467 leftcol,
19468 );
19469 }
19470 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
19471 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
19472 // is larger than that, so it is tiled into 32-capped units.
19473 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19474 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
19475 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
19476 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
19477 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
19478 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
19479 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
19480 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
19481 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
19482 _ => {
19483 return Err(unsupported(
19484 "a 64-axis strip whose chroma unit has no coefficient table",
19485 ));
19486 }
19487 };
19488 let bigger = nw * nh > 1;
19489 let mut u_levels = vec![0i32; chroma_w * chroma_h];
19490 let mut v_levels = vec![0i32; chroma_w * chroma_h];
19491 // The tiled units below stamp their own coefficient context
19492 // immediately, then the whole-strip `record_rect` rewrite paints
19493 // every chroma cell with ONE whole-strip state and the per-unit DC
19494 // signs and levels are lost (class `override-slot-on-one-arm`, same
19495 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
19496 // here and replayed after that record, the c8 `mu_chroma_units` way.
19497 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
19498 for plane_idx in 1..=2 {
19499 for cu_row in 0..nh {
19500 for cu_col in 0..nw {
19501 let cu_around = if nw == 1 && nh == 1 {
19502 around
19503 } else {
19504 let lsx = uw << ss_x(fctx);
19505 let lsy = uh << ss_y(fctx);
19506 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
19507 neighbours.around_mi_rect(cu_mi, lsx, lsy)
19508 };
19509 let lsx = uw << ss_x(fctx);
19510 let lsy = uh << ss_y(fctx);
19511 let cfl = alpha.map(|(au, av)| {
19512 let a = if plane_idx == 1 { au } else { av };
19513 (
19514 a,
19515 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
19516 )
19517 });
19518 let levels = if uw == uh {
19519 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
19520 if let Some((ub, vb)) = &palette_uv_bufs {
19521 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19522 }
19523 read_plane(
19524 dec,
19525 cdfs,
19526 chroma_set,
19527 chroma_scan,
19528 plane_idx,
19529 cu_around[plane_idx],
19530 mode,
19531 uv_predict_mode,
19532 angle_delta_uv,
19533 reach,
19534 plane,
19535 cpx + cu_col * uw,
19536 cpy + cu_row * uh,
19537 uw,
19538 uw,
19539 base_q_idx,
19540 cfl,
19541 None,
19542 bigger.then_some(3),
19543 smooth_neighbor_uv,
19544 fctx,
19545 )?
19546 } else {
19547 let skip_ctx = usize::from(cu_around[plane_idx].0)
19548 + usize::from(cu_around[plane_idx].1)
19549 + usize::from(bigger) * 3;
19550 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19551 let (levels, tx_type) = read_chroma_coeffs_rect(
19552 dec,
19553 &mut coding,
19554 chroma_scan,
19555 uw,
19556 uh,
19557 skip_ctx,
19558 dc_sign_ctx(cu_around[plane_idx].2),
19559 TxType::DctDct,
19560 fctx,
19561 plane_idx,
19562 )?;
19563 let residual = dequant_and_inverse_typed_wh(
19564 &levels,
19565 uw,
19566 uh,
19567 crate::decode::bit_depth(fctx),
19568 block_q_idx(fctx),
19569 plane_q_delta(plane_idx, fctx).0,
19570 plane_q_delta(plane_idx, fctx).1,
19571 tx_type,
19572 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
19573 );
19574 if let Some((ub, vb)) = &palette_uv_bufs {
19575 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19576 }
19577 push_intra_rect(
19578 plane_idx,
19579 cpx + cu_col * uw,
19580 cpy + cu_row * uh,
19581 uw,
19582 uh,
19583 uv_predict_mode,
19584 angle_delta_uv,
19585 reach,
19586 &residual,
19587 cfl,
19588 None,
19589 smooth_neighbor_uv,
19590 fctx,
19591 );
19592 levels
19593 };
19594 let dst = if plane_idx == 1 {
19595 &mut u_levels
19596 } else {
19597 &mut v_levels
19598 };
19599 for row in 0..uh {
19600 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
19601 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
19602 }
19603 if bigger {
19604 neighbours.record_mi_chroma(
19605 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19606 lsx,
19607 lsy,
19608 plane_idx,
19609 &levels,
19610 );
19611 tiled_chroma_units.push((
19612 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19613 plane_idx,
19614 levels.clone(),
19615 lsx,
19616 lsy,
19617 ));
19618 }
19619 }
19620 }
19621 }
19622 neighbours.record_rect(
19623 at,
19624 bw,
19625 bh,
19626 mode,
19627 uv_predict_mode,
19628 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
19629 );
19630 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
19631 // chroma cells from the assembled grids' one whole-strip state,
19632 // overwriting exactly the stamps the tiled loop just made.
19633 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
19634 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
19635 }
19636 hit!(RECT_COEFF_HITS);
19637 }
19638 let (py_size, py_colors) = palette_y
19639 .as_ref()
19640 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19641 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19642 let (puv_size, puv_colors) = palette_uv
19643 .as_ref()
19644 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19645 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19646 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
19647 neighbours.fill_lf_grid_rect(
19648 (mi_r, mi_c),
19649 bw / MI,
19650 bh / MI,
19651 tx_w as u8,
19652 tx_h as u8,
19653 0,
19654 fctx,
19655 );
19656 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19657 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19658 // frame): the above row records `tx_size_wide` over the block's width and
19659 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19660 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19661 // and it published neither band -- so the block after a 64x16 strip read
19662 // the row's init value 64 as its left transform height and took
19663 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19664 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19665 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19666 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19667 hit!(SB_RECT_HITS);
19668 match (bw, bh) {
19669 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
19670 (16, 64) => hit!(SB_RECT4_VERT_HITS),
19671 _ => {}
19672 }
19673 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19674 let (rng, _) = dec.debug_state();
19675 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
19676 }
19677 Ok(())
19678}
19679
19680/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
19681/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
19682/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
19683/// it lands away from zero, for gate tests to prove a real stream fired one.
19684fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
19685 let symbol = dec.symbol(cdf);
19686 if symbol != ANGLE_DELTA_ZERO {
19687 hit!(ANGLE_DELTA_HITS);
19688 }
19689 symbol as i32 - ANGLE_DELTA_ZERO as i32
19690}
19691
19692#[allow(clippy::too_many_arguments)]
19693fn read_intra_mode(
19694 dec: &mut SymbolDecoder,
19695 cdfs: &mut Cdfs,
19696 above_mode: usize,
19697 left_mode: usize,
19698 cfl: bool,
19699 side: usize,
19700 enable_filter_intra: bool,
19701 skip_ctx: usize,
19702 allow_screen_content_tools: bool,
19703 allow_intrabc: bool,
19704 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
19705 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
19706 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
19707 // `None` at the excluded call sites (the 8x8-leaf path), which still read
19708 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
19709 // decoder reads either way -- but refuse by name the moment it fires,
19710 // exactly the old behaviour.
19711 palette: Option<(usize, &[u16])>,
19712 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
19713 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
19714 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
19715 // `use_palette_y`, not a neighbour lookup).
19716 palette_uv_cache: &[u16],
19717 mi_r: usize,
19718 mi_c: usize,
19719 fctx: &crate::decode::FrameCtx,
19720) -> Result<(
19721 bool,
19722 usize,
19723 i32,
19724 usize,
19725 i32,
19726 Option<(i32, i32)>,
19727 Option<usize>,
19728 Option<PaletteY>,
19729 Option<PaletteUv>,
19730)> {
19731 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
19732 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
19733 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
19734 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
19735 // line against the instrumented aomdec, not just `tell()`.
19736 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
19737 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
19738 if ec_istep {
19739 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
19740 // (decodemv.c:818), printed at the same point: before the first
19741 // mode-info symbol of the block, so a cross-decoder range ladder can
19742 // be keyed on the BLOCK, not just on the symbol sequence.
19743 eprintln!(
19744 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
19745 dec.debug_state().0
19746 );
19747 }
19748 macro_rules! istep {
19749 ($name:literal, $val:expr) => {
19750 if ec_istep {
19751 let (rng, _) = dec.debug_state();
19752 eprintln!(
19753 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
19754 $name, $val
19755 );
19756 }
19757 };
19758 }
19759 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
19760 // point every square caller routes through (see `read_intra_mode_rect`).
19761 let cfl = if cfl && side > 32 {
19762 hit!(NOCFL_UV_MODE_HITS);
19763 false
19764 } else {
19765 cfl
19766 };
19767 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
19768 // `skip` when `SegIdPreSkip`, and after it otherwise.
19769 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
19770 if seg_id_pre_skip(fctx) {
19771 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
19772 }
19773 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
19774 if trace {
19775 eprintln!(
19776 "TRACE skip value={} rng={}",
19777 skip as i32,
19778 dec.debug_state().0
19779 );
19780 }
19781 istep!("skip", skip as i32);
19782 if !seg_id_pre_skip(fctx) {
19783 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
19784 }
19785 // spec order (see the comment below on `read_intrabc_info`): `skip`,
19786 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
19787 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
19788 istep!("cdef", 0);
19789 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
19790 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
19791 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
19792 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
19793 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19794 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19795 istep!("dq", 0);
19796 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
19797 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
19798 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
19799 // intra frame whose header set `allow_intrabc`. Actual intra block copy
19800 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
19801 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
19802 // draws the line at consuming this one flag symbol and refusing by name
19803 // when it fires, so the arithmetic decoder still resyncs for a stream
19804 // that merely allows (but never uses) intrabc.
19805 if allow_intrabc {
19806 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
19807 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19808 eprintln!(
19809 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
19810 u8::from(use_intrabc),
19811 dec.debug_state().0
19812 );
19813 }
19814 if trace {
19815 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
19816 }
19817 if use_intrabc {
19818 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
19819 if trace {
19820 eprintln!("TRACE intrabc dv={dv:?}");
19821 }
19822 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
19823 hit!(INTRABC_HITS);
19824 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
19825 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
19826 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
19827 // `DC_PRED` (which is also what the neighbour mode contexts and
19828 // the loop filter then see).
19829 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
19830 }
19831 }
19832 let above_ctx = INTRA_MODE_CTX[above_mode];
19833 let left_ctx = INTRA_MODE_CTX[left_mode];
19834 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
19835 if trace {
19836 eprintln!(
19837 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
19838 dec.debug_state().0
19839 );
19840 }
19841 istep!("mode", mode as i32);
19842 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
19843 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
19844 if trace {
19845 eprintln!(
19846 "TRACE angle_delta value={}",
19847 delta + ANGLE_DELTA_ZERO as i32
19848 );
19849 }
19850 delta
19851 } else {
19852 0
19853 };
19854 istep!("angle_y", angle_delta_y);
19855 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
19856 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
19857 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
19858 // gates its chroma symbols on.
19859 let has_chroma = !mono(fctx);
19860 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
19861 let uv_mode = if !has_chroma {
19862 DC_PRED
19863 } else if cfl {
19864 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19865 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
19866 } else {
19867 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19868 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
19869 };
19870 if trace {
19871 eprintln!(
19872 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
19873 dec.debug_state().0
19874 );
19875 }
19876 istep!("uv_mode", uv_mode as i32);
19877 let alpha = if cfl && uv_mode == UV_CFL_PRED {
19878 Some(read_cfl_alphas(dec, cdfs))
19879 } else {
19880 None
19881 };
19882 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
19883 // from this lane's directional chroma: a corner block with neither
19884 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
19885 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
19886 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
19887 // bug in that fallback this lane's own scope does not cover. Keep it
19888 // refused here rather than ship a silently-wrong decode.
19889 if (9..=12).contains(&uv_mode) {
19890 hit!(SMOOTH_UV_HITS);
19891 }
19892 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
19893 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
19894 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
19895 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
19896 // the `else` branch below and never reads one either way.
19897 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
19898 hit!(DIRECTIONAL_UV_HITS);
19899 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
19900 } else {
19901 0
19902 };
19903 istep!("angle_uv", angle_delta_uv);
19904 if angle_delta_uv != 0 {
19905 hit!(UV_ANGLE_DELTA_HITS);
19906 }
19907 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
19908 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
19909 // gated by `av1_allow_palette` (blockd.h -- size bound only,
19910 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
19911 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
19912 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
19913 // read the same CDF row whenever every neighbour really is non-palette).
19914 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
19915 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
19916 // neighbour lookup at all), so it is exact even at the excluded call
19917 // sites once Y decodes real syntax there too.
19918 //
19919 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
19920 // inline from `read_palette_mode_info` -- it runs later, from
19921 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
19922 // after the WHOLE mode-info read for the block, including UV palette
19923 // mode_info (`read_palette_mode_info`'s own second half, right below)
19924 // and `read_filter_intra_mode_info`. So this branch now only reads
19925 // mode/size/colours for both planes (deferring the two colour-index-map
19926 // decodes to after `filter_intra`, below) -- r6's range trace pinned
19927 // this exact ordering bug (`compare-range-not-tell`: ranges matched
19928 // bit-for-bit through the Y colours, diverged only at the old inline
19929 // `decode_color_index_map` call).
19930 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
19931 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
19932 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
19933 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
19934 if mode == DC_PRED {
19935 if trace {
19936 let (rng, _) = dec.debug_state();
19937 eprintln!(
19938 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
19939 );
19940 }
19941 }
19942 let use_palette_y =
19943 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
19944 if mode == DC_PRED && trace {
19945 let (rng, _) = dec.debug_state();
19946 eprintln!(
19947 "TRACE palette_y_mode value={} rng={rng}",
19948 use_palette_y as i32
19949 );
19950 }
19951 if use_palette_y {
19952 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
19953 if trace {
19954 let (rng, _) = dec.debug_state();
19955 eprintln!("TRACE palette_y_size n={n} rng={rng}");
19956 }
19957 let colors = read_palette_colors_y(dec, n, cache, fctx);
19958 if trace {
19959 let (rng, _) = dec.debug_state();
19960 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
19961 }
19962 palette_y_pending = Some((n, colors));
19963 }
19964 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
19965 // unconditionally at this bit position whenever `uv_mode ==
19966 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
19967 // scope always reconstructs chroma alongside luma (`decode_block`
19968 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
19969 // is always true here and does not need threading in.
19970 //
19971 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
19972 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
19973 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
19974 // symbol even at this chroma-owning square block.
19975 let palette_uv_mode_ctx = usize::from(use_palette_y);
19976 if has_chroma
19977 && uv_mode == DC_PRED
19978 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
19979 {
19980 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
19981 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
19982 palette_uv_pending = Some((n, u_colors, v_colors));
19983 }
19984 }
19985 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
19986 // `use_filter_intra` symbol this decoder never read at all until
19987 // lane-av1real r10 -- silently skipping it left every bit past a
19988 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
19989 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
19990 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
19991 // symbol's bits were never consumed).
19992 let mut filter_intra = None;
19993 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
19994 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
19995 // `use_filter_intra` symbol for a Y-palette block, and reading one here
19996 // desynced every screen-content stream from the first palette block on
19997 // (it surfaced as a bogus "partition below 8x8" refusal further down the
19998 // tile).
19999 if mode == DC_PRED
20000 && enable_filter_intra
20001 && palette_y_pending.is_none()
20002 && let Some(class) = filter_intra_size_class(side)
20003 {
20004 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
20005 if trace {
20006 eprintln!(
20007 "TRACE use_filter_intra side={side} rng={} value={}",
20008 dec.debug_state().0,
20009 use_filter_intra as i32
20010 );
20011 }
20012 istep!("use_filter_intra", use_filter_intra as i32);
20013 if use_filter_intra {
20014 hit!(FILTER_INTRA_HITS);
20015 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
20016 if trace {
20017 eprintln!("TRACE filter_intra_mode value={fi_mode}");
20018 }
20019 istep!("filter_intra_mode", fi_mode as i32);
20020 filter_intra = Some(fi_mode);
20021 }
20022 }
20023 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
20024 // shared U/V map) -- the same order libaom's own loop visits them in.
20025 let palette_y = palette_y_pending.map(|(n, colors)| {
20026 let map = decode_color_index_map(
20027 dec,
20028 cdfs,
20029 n,
20030 side,
20031 palette_onscreen(mi_r, mi_c, side, side, fctx),
20032 false,
20033 );
20034 hit!(PALETTE_HITS);
20035 if trace {
20036 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
20037 }
20038 PaletteY {
20039 size: n,
20040 colors,
20041 map,
20042 }
20043 });
20044 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
20045 let on = palette_onscreen_uv(
20046 (side, side),
20047 palette_onscreen(mi_r, mi_c, side, side, fctx),
20048 (side >> ss_x(fctx), side >> ss_y(fctx)),
20049 (ss_x(fctx), ss_y(fctx)),
20050 );
20051 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
20052 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
20053 // square call's `(side >> ss_x)`-squared (4x4), which left a
20054 // 16-entry map for a 32-sample unit and panicked the reconstruct.
20055 let map = decode_color_index_map_wh(
20056 dec,
20057 cdfs,
20058 n,
20059 side >> ss_x(fctx),
20060 side >> ss_y(fctx),
20061 on,
20062 true,
20063 );
20064 hit!(PALETTE_UV_HITS);
20065 if trace {
20066 eprintln!(
20067 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
20068 &u_colors[..n],
20069 &v_colors[..n]
20070 );
20071 }
20072 PaletteUv {
20073 size: n,
20074 u_colors,
20075 v_colors,
20076 map,
20077 }
20078 });
20079 Ok((
20080 skip,
20081 mode,
20082 angle_delta_y,
20083 uv_mode,
20084 angle_delta_uv,
20085 alpha,
20086 filter_intra,
20087 palette_y,
20088 palette_uv,
20089 ))
20090}
20091
20092/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
20093/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
20094/// intra modes.
20095const UV_CFL_PRED: usize = 13;
20096
20097/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
20098/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
20099/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
20100/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
20101/// joint sign the same way. Returns each plane's final signed `alpha_q3`
20102/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
20103fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
20104 hit!(CFL_BLOCK_HITS);
20105 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
20106 let sign_u = ((joint_sign + 1) * 11) >> 5;
20107 let sign_v = (joint_sign + 1) - 3 * sign_u;
20108 let alpha_u = if sign_u == 0 {
20109 0
20110 } else {
20111 let ctx_u = (joint_sign + 1 - 3) as usize;
20112 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
20113 if sign_u == 2 { mag } else { -mag }
20114 };
20115 let alpha_v = if sign_v == 0 {
20116 0
20117 } else {
20118 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
20119 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
20120 if sign_v == 2 { mag } else { -mag }
20121 };
20122 (alpha_u, alpha_v)
20123}
20124
20125/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
20126/// the reconstructed luma samples under a `side`-square block, subsampled
20127/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
20128/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
20129/// to give the AC values [`cfl_scaled`] scales by alpha.
20130fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
20131 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
20132 i32::from(y.data[ly * y.width + lx])
20133 })
20134}
20135
20136/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
20137/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
20138/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
20139/// reconstruction through THIS function rather than a second transcription of
20140/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
20141/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
20142/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
20143fn cfl_ac_ss(
20144 y: &PlaneBuf<'_>,
20145 px: usize,
20146 py: usize,
20147 bw: usize,
20148 bh: usize,
20149 ss_x: usize,
20150 ss_y: usize,
20151) -> Vec<i32> {
20152 if ss_x == 0 && ss_y == 0 {
20153 hit!(CFL_AC_444_HITS);
20154 let mut ac = vec![0i32; bw * bh];
20155 let mut sum = 0i32;
20156 for row in 0..bh {
20157 for col in 0..bw {
20158 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
20159 ac[row * bw + col] = q3;
20160 sum += q3;
20161 }
20162 }
20163 let num_pel = (bw * bh) as i32;
20164 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20165 ac.iter_mut().for_each(|v| *v -= avg);
20166 ac
20167 } else if ss_x == 1 && ss_y == 0 {
20168 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
20169 // averages the HORIZONTAL luma pair above it, at full chroma height
20170 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
20171 // is square here, and the 4:2:0 rect/square helpers below would halve
20172 // the height it must keep.
20173 hit!(CFL_AC_422_HITS);
20174 let (cw, ch) = (bw >> 1, bh);
20175 let mut ac = vec![0i32; cw * ch];
20176 let mut sum = 0i32;
20177 for row in 0..ch {
20178 for col in 0..cw {
20179 let (lx, ly) = (px + col * 2, py + row);
20180 let q3 = (i32::from(y.data[ly * y.width + lx])
20181 + i32::from(y.data[ly * y.width + lx + 1]))
20182 << 2;
20183 ac[row * cw + col] = q3;
20184 sum += q3;
20185 }
20186 }
20187 let num_pel = (cw * ch) as i32;
20188 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20189 ac.iter_mut().for_each(|v| *v -= avg);
20190 ac
20191 } else if bw == bh {
20192 hit!(CFL_AC_420_SQ_HITS);
20193 cfl_ac_q3(y, px, py, bw)
20194 } else {
20195 hit!(CFL_AC_420_RECT_HITS);
20196 cfl_ac_q3_rect(y, px, py, bw, bh)
20197 }
20198}
20199
20200pub(crate) fn cfl_ac_q3_at(
20201 px: usize,
20202 py: usize,
20203 bw: usize,
20204 bh: usize,
20205 sample: impl Fn(usize, usize) -> i32,
20206) -> Vec<i32> {
20207 hit!(CFL_AC_Q3_AT_HITS);
20208 if crate::envflags::env_flag!("EC_HALVSWEEP") {
20209 eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
20210 }
20211 let (cw, ch) = (bw / 2, bh / 2);
20212 let mut ac = vec![0i32; cw * ch];
20213 let mut sum = 0i32;
20214 for cy in 0..ch {
20215 for cx in 0..cw {
20216 let (lx, ly) = (px + cx * 2, py + cy * 2);
20217 let q3 =
20218 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
20219 << 1;
20220 ac[cy * cw + cx] = q3;
20221 sum += q3;
20222 }
20223 }
20224 let num_pel = (cw * ch) as i32;
20225 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20226 ac.iter_mut().for_each(|v| *v -= avg);
20227 ac
20228}
20229
20230/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
20231/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
20232/// ties away from zero on the shifted-out sign).
20233pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
20234 let v = alpha_q3 * ac_q3;
20235 if v >= 0 {
20236 (v + 32) >> 6
20237 } else {
20238 -((-v + 32) >> 6)
20239 }
20240}
20241
20242/// One plane's reconstruction buffer, `width * height` samples, and the
20243/// prediction/residual reads and writes into it — the decode-side twin of
20244/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
20245/// (own-edge and reach clamps both), passing what it gathers straight to
20246/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
20247/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
20248/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
20249/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
20250/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
20251/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
20252/// lane-mc64 r1: the decode-order index the stage dumps below key their file
20253/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
20254/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
20255/// without this every frame overwrote `.f0` and a per-frame bisection silently
20256/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
20257#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
20258fn stage_dump_idx() -> usize {
20259 PREFILT_PICTURE_IDX
20260 .load(std::sync::atomic::Ordering::SeqCst)
20261 .saturating_sub(1)
20262}
20263
20264fn dump_stage16(
20265 var: &str,
20266 y: &PlaneBuf<'_>,
20267 u: &PlaneBuf<'_>,
20268 v: &PlaneBuf<'_>,
20269 fw: usize,
20270 fh: usize,
20271) {
20272 use std::io::Write;
20273 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
20274 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
20275 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
20276 // not be read out at all.
20277 if let Ok(path) = crate::envflags::var(var)
20278 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20279 {
20280 for (p, w, h) in [
20281 (y, fw, fh),
20282 (u, fw.div_ceil(2), fh.div_ceil(2)),
20283 (v, fw.div_ceil(2), fh.div_ceil(2)),
20284 ] {
20285 for row in 0..h {
20286 let mut bytes = Vec::with_capacity(w * 2);
20287 for &s in &p.data[row * p.width..][..w] {
20288 bytes.extend_from_slice(&s.to_le_bytes());
20289 }
20290 let _ = f.write_all(&bytes);
20291 }
20292 }
20293 }
20294}
20295
20296/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
20297/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
20298/// every frame overwrote the previous one and only the LAST frame survived,
20299/// which silently defeats any per-frame filter-stage bisection.
20300fn dump_stage_idx(var: &str) -> usize {
20301 use std::collections::HashMap;
20302 use std::sync::{Mutex, OnceLock};
20303 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
20304 let mut m = IDX
20305 .get_or_init(|| Mutex::new(HashMap::new()))
20306 .lock()
20307 .unwrap();
20308 let e = m.entry(var.to_string()).or_insert(0);
20309 let i = *e;
20310 *e += 1;
20311 i
20312}
20313
20314fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20315 use std::io::Write;
20316 if let Ok(path) = crate::envflags::var(var)
20317 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20318 {
20319 for p in [y, u, v] {
20320 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
20321 let _ = f.write_all(&narrow);
20322 }
20323 }
20324}
20325
20326/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
20327/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
20328/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
20329/// `uv_width`/`uv_height`), so the two can be diffed directly.
20330///
20331/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
20332/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
20333/// measurement traps, and the second one is why the first went unnoticed:
20334/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
20335/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
20336/// inter frame had no pre-filter rung to compare against and got attributed to
20337/// reconstruction when the oracle could not see it. The `static` also restarted
20338/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
20339/// per-frame bisection silently compared the LAST decoded frame. The counter
20340/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
20341/// the inter path (skipped when the filter pipeline is active, which has
20342/// already deblocked by the time the tile tail runs -- same condition
20343/// `capture_filter_replay` guards itself with).
20344fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20345 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
20346 return;
20347 };
20348 use std::io::Write;
20349 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
20350 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
20351 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
20352 for row in 0..plane.true_height {
20353 out.extend(
20354 plane.data[row * plane.width..][..plane.true_width]
20355 .iter()
20356 .map(|&s| s as u8),
20357 );
20358 }
20359 out
20360 };
20361 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
20362 let _ = f.write_all(&crop(y));
20363 let _ = f.write_all(&crop(u));
20364 let _ = f.write_all(&crop(v));
20365 }
20366}
20367
20368/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
20369/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
20370/// at most 4095), so a decode that hashes identically under the flag proves
20371/// the output does not depend on the plane buffer's initial content.
20372const PLANE_SENTINEL: u16 = 0xDEAD;
20373
20374/// A frame plane's own backing store, `n` samples, UNINITIALISED.
20375///
20376/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
20377/// by the tile walk's reconstruction before anything reads it, so the
20378/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
20379/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
20380/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
20381/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
20382/// ways (see the lane report) and the two agree, which is the proof that no
20383/// unwritten sample reaches the output.
20384fn fresh_plane(n: usize) -> Vec<u16> {
20385 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
20386 return vec![PLANE_SENTINEL; n];
20387 }
20388 let mut v: Vec<u16> = Vec::with_capacity(n);
20389 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
20390 // capacity was just reserved, so the vector owns `n` initialised-or-not
20391 // `u16` slots. Every one is written by reconstruction before it is read
20392 // (proven by the sentinel gate above).
20393 #[allow(unsafe_code)]
20394 unsafe {
20395 v.set_len(n);
20396 }
20397 v
20398}
20399
20400#[derive(Clone)]
20401struct PlaneBuf<'a> {
20402 data: std::borrow::Cow<'a, [u16]>,
20403 width: usize,
20404 height: usize,
20405 /// The frame's true, decodable extent in this plane's own units — past
20406 /// this, samples are the padded coding surface's invented tail, never a
20407 /// real decoder's edge or reach reads.
20408 true_width: usize,
20409 true_height: usize,
20410 /// This plane's own tile's top-left pixel origin (spec: intra prediction
20411 /// never reaches across a tile boundary even though an earlier-decoded
20412 /// tile's real pixels sit right there in the shared buffer) — set via
20413 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
20414 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
20415 /// is threaded (the two-tile column-split stage 1 fixture's tile always
20416 /// ends at the frame's own right/bottom edge); a non-last tile's own
20417 /// right/bottom reach bound is still open, tracked in the report.
20418 tile_x0: usize,
20419 tile_y0: usize,
20420 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
20421 /// (exclusive) -- a non-last tile column/row's own reach must stop at
20422 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
20423 /// full padded extent) for the single-tile/last-tile case, matching the
20424 /// old unclipped behaviour exactly.
20425 tile_x1: usize,
20426 tile_y1: usize,
20427}
20428
20429/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
20430/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
20431/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
20432/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
20433/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
20434/// `ALTREF2`/`ALTREF`).
20435// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
20436// prints one PIXWRITE line per reconstruction store landing on that sample,
20437// naming the store site, the value it replaces and the one it leaves. Re-anchored
20438// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
20439// now live in `reconstruct_mc_rect`).
20440static PIXPROBE_ON: std::sync::LazyLock<bool> =
20441 std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
20442
20443static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> = std::sync::LazyLock::new(|| {
20444 crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
20445 let (x, y) = v.split_once(',')?;
20446 Some((
20447 x.trim().parse::<usize>().ok()?,
20448 y.trim().parse::<usize>().ok()?,
20449 ))
20450 })
20451});
20452
20453#[inline]
20454fn pix_write(
20455 site: &str,
20456 bx: usize,
20457 by: usize,
20458 bside: usize,
20459 x: usize,
20460 y: usize,
20461 prev: u16,
20462 val: u16,
20463) {
20464 if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
20465 eprintln!(
20466 "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
20467 std::panic::Location::caller()
20468 );
20469 }
20470}
20471
20472impl PlaneBuf<'_> {
20473 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
20474 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
20475 /// are already in this plane's own units (luma pixels for `y`, chroma
20476 /// pixels — halved — for `u`/`v`).
20477 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
20478 self.tile_x0 = x0;
20479 self.tile_y0 = y0;
20480 self.tile_x1 = x1;
20481 self.tile_y1 = y1;
20482 }
20483
20484 fn edges(
20485 &self,
20486 x: usize,
20487 y: usize,
20488 side: usize,
20489 reach: Reach,
20490 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20491 let own_across = x + side.min(self.true_width.saturating_sub(x));
20492 let across = if reach.above_right {
20493 own_across + side.min(self.true_width.saturating_sub(own_across))
20494 } else {
20495 own_across
20496 }
20497 .min(self.width)
20498 .min(self.tile_x1);
20499 let own_down = y + side.min(self.true_height.saturating_sub(y));
20500 let down = if reach.below_left {
20501 own_down + side.min(self.true_height.saturating_sub(own_down))
20502 } else {
20503 own_down
20504 }
20505 .min(self.height)
20506 .min(self.tile_y1);
20507 let above = (y > self.tile_y0 && across > x)
20508 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20509 let left = (x > self.tile_x0 && down > y).then(|| {
20510 (y..down)
20511 .map(|row| self.data[row * self.width + x - 1])
20512 .collect::<Vec<_>>()
20513 });
20514 let corner =
20515 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20516 (above, left, corner)
20517 }
20518
20519 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
20520 /// the above/left reach each extend by their OWN axis (`bw` across,
20521 /// `bh` down), not one shared `side`.
20522 fn edges_rect(
20523 &self,
20524 x: usize,
20525 y: usize,
20526 bw: usize,
20527 bh: usize,
20528 reach: Reach,
20529 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20530 let own_across = x + bw.min(self.true_width.saturating_sub(x));
20531 let across = if reach.above_right {
20532 own_across + bw.min(self.true_width.saturating_sub(own_across))
20533 } else {
20534 own_across
20535 }
20536 .min(self.width)
20537 .min(self.tile_x1);
20538 let own_down = y + bh.min(self.true_height.saturating_sub(y));
20539 let down = if reach.below_left {
20540 own_down + bh.min(self.true_height.saturating_sub(own_down))
20541 } else {
20542 own_down
20543 }
20544 .min(self.height)
20545 .min(self.tile_y1);
20546 let above = (y > self.tile_y0 && across > x)
20547 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20548 let left = (x > self.tile_x0 && down > y).then(|| {
20549 (y..down)
20550 .map(|row| self.data[row * self.width + x - 1])
20551 .collect::<Vec<_>>()
20552 });
20553 let corner =
20554 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20555 if matches!((bw, bh), (16, 8) | (8, 16)) {
20556 hit!(RECT_STRIP_PRED_HITS);
20557 if across > own_across || down > own_down {
20558 hit!(RECT_STRIP_REACH_HITS);
20559 }
20560 }
20561 (above, left, corner)
20562 }
20563
20564 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
20565 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
20566 /// already-rect-capable `(bw, bh)` pair.
20567 #[allow(clippy::too_many_arguments)]
20568 #[track_caller]
20569 fn reconstruct_rect(
20570 &mut self,
20571 x: usize,
20572 y: usize,
20573 bw: usize,
20574 bh: usize,
20575 mode: usize,
20576 angle_delta: i32,
20577 reach: Reach,
20578 residual: &[i32],
20579 cfl: Option<(i32, &[i32])>,
20580 filter_intra: Option<usize>,
20581 smooth_neighbor: bool,
20582 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20583 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20584 // than by this replay.
20585 pred: Option<Vec<u16>>,
20586 fctx: &crate::decode::FrameCtx,
20587 ) {
20588 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
20589 // (lane-palette2 r4): a palette block's prediction is the
20590 // reconstructed colour-index map, needing no edge pixels at all.
20591 let prediction = if let Some(buf) = pred {
20592 buf
20593 } else {
20594 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
20595 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20596 eprintln!(
20597 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
20598 above.as_ref().map(|a| (a.len(), a[0])),
20599 left.as_ref().map(|l| l.len()),
20600 left.as_ref().map(|l| l[0]),
20601 self.tile_x0,
20602 self.tile_y0,
20603 self.true_width,
20604 self.true_height
20605 );
20606 }
20607 let mut prediction = vec![0u16; bw * bh];
20608 if let Some(fi_mode) = filter_intra {
20609 crate::intra::predict_filter_intra(
20610 fi_mode,
20611 above.as_deref(),
20612 left.as_deref(),
20613 corner,
20614 bw,
20615 bh,
20616 &mut prediction,
20617 fctx,
20618 );
20619 } else {
20620 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20621 predict(
20622 mode as u8,
20623 angle_delta,
20624 above.as_deref(),
20625 left.as_deref(),
20626 corner,
20627 bw,
20628 bh,
20629 enable_edge_filter,
20630 smooth_neighbor,
20631 &mut prediction,
20632 fctx,
20633 );
20634 }
20635 prediction
20636 };
20637 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20638 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20639 if crate::envflags::env_flag!("EC_PRED") {
20640 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20641 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20642 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
20643 eprintln!(
20644 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20645 std::panic::Location::caller(),
20646 recon_plane(),
20647 i32::from(smooth_neighbor)
20648 );
20649 }
20650 let residual = dense_residual(residual, bw * bh);
20651 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20652 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
20653 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20654 eprintln!(
20655 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
20656 );
20657 }
20658 for row in 0..bh {
20659 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
20660 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
20661 // whose padded width is not superblock aligned hangs past it.
20662 if y + row >= self.height {
20663 break;
20664 }
20665 for col in 0..bw {
20666 if x + col >= self.width {
20667 break;
20668 }
20669 let idx = row * bw + col;
20670 let mut base = i32::from(prediction[idx]);
20671 if let Some((alpha_q3, ac_q3)) = cfl {
20672 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20673 }
20674 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20675 pix_write(
20676 "reconstruct_rect",
20677 x,
20678 y,
20679 bw,
20680 x + col,
20681 y + row,
20682 self.data[(y + row) * self.width + x + col],
20683 sample,
20684 );
20685 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20686 }
20687 }
20688 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
20689 // -- a block whose prediction matches the oracle's but whose written
20690 // samples do not is either a residual defect or a later overwrite, and
20691 // only this print separates the two.
20692 if crate::envflags::env_flag!("EC_PRED") {
20693 let row0: Vec<u16> = (0..bw.min(8))
20694 .map(|c| self.data[y * self.width + x + c])
20695 .collect();
20696 let col0: Vec<u16> = (0..bh.min(8))
20697 .map(|r| self.data[(y + r) * self.width + x])
20698 .collect();
20699 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
20700 }
20701 }
20702
20703 /// Predicts under `mode` then adds `residual` (side*side, raster),
20704 /// writing the clamped reconstruction back into the plane at `(x, y)`.
20705 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
20706 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
20707 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
20708 /// order (cfl.c).
20709 #[track_caller]
20710 fn reconstruct(
20711 &mut self,
20712 x: usize,
20713 y: usize,
20714 side: usize,
20715 mode: usize,
20716 angle_delta: i32,
20717 reach: Reach,
20718 residual: &[i32],
20719 cfl: Option<(i32, &[i32])>,
20720 filter_intra: Option<usize>,
20721 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
20722 // libaom `get_filt_type`): true when the block's above OR left
20723 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
20724 // Callers pass their own plane's neighbour-mode check
20725 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
20726 // callers until a smooth/paeth `uv_mode` can reach this call at all
20727 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
20728 // keeps `false` exact for chroma without this fn needing to know why.
20729 smooth_neighbor: bool,
20730 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20731 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20732 // than by this replay.
20733 pred: Option<Vec<u16>>,
20734 fctx: &crate::decode::FrameCtx,
20735 ) {
20736 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
20737 // takes priority over `predict()`/`predict_filter_intra` entirely --
20738 // palette prediction needs no edge pixels at all.
20739 let prediction = if let Some(buf) = pred {
20740 buf
20741 } else {
20742 let (above, left, corner) = self.edges(x, y, side, reach);
20743 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20744 eprintln!(
20745 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
20746 above.as_deref(),
20747 left.as_deref(),
20748 );
20749 }
20750 let mut prediction = vec![0u16; side * side];
20751 if let Some(fi_mode) = filter_intra {
20752 crate::intra::predict_filter_intra(
20753 fi_mode,
20754 above.as_deref(),
20755 left.as_deref(),
20756 corner,
20757 side,
20758 side,
20759 &mut prediction,
20760 fctx,
20761 );
20762 } else {
20763 // `enable_intra_edge_filter` is the sequence header's own flag
20764 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
20765 // call, never per-block) -- threading it through every
20766 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
20767 // dozen sites for a value that never changes mid-decode, so it
20768 // rides a thread-local instead (this decoder is single-threaded
20769 // per stream).
20770 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20771 predict(
20772 mode as u8,
20773 angle_delta,
20774 above.as_deref(),
20775 left.as_deref(),
20776 corner,
20777 side,
20778 side,
20779 enable_edge_filter,
20780 smooth_neighbor,
20781 &mut prediction,
20782 fctx,
20783 );
20784 }
20785 prediction
20786 };
20787 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20788 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20789 if crate::envflags::env_flag!("EC_PRED") {
20790 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20791 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
20792 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
20793 eprintln!(
20794 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20795 std::panic::Location::caller(),
20796 recon_plane(),
20797 i32::from(smooth_neighbor)
20798 );
20799 }
20800 let residual = dense_residual(residual, side * side);
20801 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20802 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
20803 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
20804 eprintln!(
20805 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
20806 cfl.is_some()
20807 );
20808 }
20809 for row in 0..side {
20810 // lane-sb128c r8: libaom's frame buffer is superblock
20811 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
20812 // transform unit of a 128x64 block at the BOTTOM frame edge
20813 // can hang past the last padded row (1920x792: a unit at
20814 // y=768 wants 832 rows of an 800-row buffer, which panicked
20815 // the film's key frames). Those samples are outside the
20816 // frame: never output, and no block below ever references
20817 // them.
20818 if y + row >= self.height {
20819 break;
20820 }
20821 for col in 0..side {
20822 if x + col >= self.width {
20823 break;
20824 }
20825 let idx = row * side + col;
20826 let mut base = i32::from(prediction[idx]);
20827 if let Some((alpha_q3, ac_q3)) = cfl {
20828 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20829 }
20830 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20831 pix_write(
20832 "reconstruct",
20833 x,
20834 y,
20835 side,
20836 x + col,
20837 y + row,
20838 self.data[(y + row) * self.width + x + col],
20839 sample,
20840 );
20841 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20842 }
20843 }
20844 }
20845}
20846
20847/// Reads one plane's transform block, reconstructs it into `plane` at
20848/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
20849#[allow(clippy::too_many_arguments)]
20850
20851fn read_plane(
20852 dec: &mut SymbolDecoder,
20853 cdfs: &mut Cdfs,
20854 set: TxbSet,
20855 scan: &[u16],
20856 plane_idx: usize,
20857 around: (bool, bool, i32),
20858 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
20859 // it for every plane's `txb` lookup (it is what an intra transform type's
20860 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
20861 tx_mode: usize,
20862 predict_mode: usize,
20863 angle_delta: i32,
20864 reach: Reach,
20865 // lane-wave1 step (i): unread -- this reader records its write
20866 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
20867 // stays in the signature so every call site still proves the plane is
20868 // exclusively held while its coefficients are parsed.
20869 _plane: &mut PlaneBuf<'static>,
20870 x: usize,
20871 y: usize,
20872 side: usize,
20873 tx_side: usize,
20874 base_q_idx: u8,
20875 cfl: Option<(i32, CflSrc)>,
20876 filter_intra: Option<usize>,
20877 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
20878 // smaller than its own block (spec `get_txb_ctx_general`'s
20879 // `plane_bsize != tx_size` branch), carrying the already-looked-up
20880 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
20881 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
20882 // formula below.
20883 luma_skip_ctx: Option<usize>,
20884 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
20885 smooth_neighbor: bool,
20886 fctx: &crate::decode::FrameCtx,
20887) -> Result<Grid> {
20888 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
20889 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
20890 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
20891 // no chroma write is recorded. Return the all-zero grid the caller's
20892 // neighbour bookkeeping reads, without consuming a bit.
20893 if plane_idx > 0 && mono(fctx) {
20894 return Ok(Grid::Zero(side * side));
20895 }
20896 // lane-av1readcensus: the units read from here on are this plane's.
20897 set_census_plane(plane_idx);
20898 let skip_ctx = if plane_idx == 0 {
20899 luma_skip_ctx.unwrap_or(0)
20900 } else {
20901 // libaom `get_txb_ctx`: a chroma unit's context is
20902 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
20903 // plane block is bigger than the transform. Our chroma tables hold the
20904 // offset-7 rows first, so the caller adds 3 for the bigger-block case
20905 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
20906 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
20907 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
20908 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
20909 };
20910 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
20911 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
20912 // not by the block's ordinary `mode` (which is always DC_PRED whenever
20913 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
20914 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
20915 // filter-intra in AV1).
20916 let tx_mode = if plane_idx == 0 {
20917 fi_tx_row(tx_mode, filter_intra)
20918 } else {
20919 tx_mode
20920 };
20921 let mut coding = cdfs.txb(set, tx_mode);
20922 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
20923 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
20924 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
20925 // plane of a lossless block (the residual then goes through the WHT, so
20926 // the type only picks the scan, which is the default one).
20927 if lossless(fctx) {
20928 coding.tx_type = None;
20929 }
20930 // Luma's `default_tx_type` is only a fallback for the sizes whose
20931 // `TxbSet` carries no symbol at all (32-point and up), which the spec
20932 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
20933 // *never* its own coded symbol (`coding.tx_type` is always `None` for
20934 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
20935 // the plane's own predicted mode (`default_intra_tx_type`) -- except
20936 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
20937 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
20938 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
20939 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
20940 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
20941 // narrows there — only `Chroma32` and up do).
20942 let default_tx_type = if plane_idx == 0 || side >= 32 {
20943 TxType::DctDct
20944 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
20945 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
20946 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
20947 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
20948 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
20949 // [`read_inter_plane`]'s own `side < 32` guard).
20950 inherited
20951 } else {
20952 default_intra_tx_type(predict_mode as u8)
20953 };
20954 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
20955 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
20956 let default_tx_type = if lossless(fctx) {
20957 TxType::DctDct
20958 } else {
20959 default_tx_type
20960 };
20961 let (grid, tx_type) = read_coeffs(
20962 dec,
20963 &mut coding,
20964 scan,
20965 skip_ctx,
20966 dc_sign_ctx(around.2),
20967 default_tx_type,
20968 None,
20969 )?;
20970 note_chroma_class1(plane_idx, tx_type);
20971 if plane_idx == 0 {
20972 fctx.luma_tx_type.with(|c| c.set(tx_type));
20973 }
20974 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
20975 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
20976 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
20977 // guard also assumes.
20978 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
20979 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
20980 // keyed by that true size, not the coded corner's -- so the corner
20981 // goes into the top-left of a `side`-sized grid, not the reverse.
20982 let levels = extend_corner(grid, tx_side, tx_side, side, side);
20983 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
20984 let tx = TxParams {
20985 w: side,
20986 h: side,
20987 bit_depth: bit_depth(fctx),
20988 q_idx: block_q_idx(fctx),
20989 dc_delta,
20990 ac_delta,
20991 tx_type,
20992 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
20993 stride: 0,
20994 lossless: lossless(fctx),
20995 };
20996 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20997 let residual = tx.run(&levels);
20998 eprintln!(
20999 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
21000 &*levels,
21001 );
21002 }
21003 push_intra_tx(
21004 plane_idx,
21005 x,
21006 y,
21007 side,
21008 side,
21009 false,
21010 predict_mode,
21011 angle_delta,
21012 reach,
21013 tx,
21014 &levels,
21015 cfl,
21016 filter_intra,
21017 smooth_neighbor,
21018 fctx,
21019 );
21020 // `record`'s neighbour state only reads whether *the coded grid* (not the
21021 // residual) has nonzero entries, so the levels this function already
21022 // built are what it wants back -- both arms of the old `tx_side == side`
21023 // branch returned exactly that, one of them through a full `to_vec` copy
21024 // of the grid per intra transform unit (lane-coefbuf).
21025 Ok(levels)
21026}
21027
21028/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
21029/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
21030/// block's own rect shape, and the `rect` flag selects
21031/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
21032#[allow(clippy::too_many_arguments)]
21033fn push_intra_unit(
21034 plane: usize,
21035 x: usize,
21036 y: usize,
21037 w: usize,
21038 h: usize,
21039 mode: usize,
21040 angle_delta: i32,
21041 reach: Reach,
21042 residual: &[i32],
21043 cfl: Option<(i32, CflSrc)>,
21044 filter_intra: Option<usize>,
21045 smooth_neighbor: bool,
21046 fctx: &crate::decode::FrameCtx,
21047) {
21048 if w == h {
21049 push_intra(
21050 plane,
21051 x,
21052 y,
21053 w,
21054 mode,
21055 angle_delta,
21056 reach,
21057 residual,
21058 cfl,
21059 filter_intra,
21060 smooth_neighbor,
21061 fctx,
21062 );
21063 } else {
21064 push_intra_rect(
21065 plane,
21066 x,
21067 y,
21068 w,
21069 h,
21070 mode,
21071 angle_delta,
21072 reach,
21073 residual,
21074 cfl,
21075 filter_intra,
21076 smooth_neighbor,
21077 fctx,
21078 );
21079 }
21080}
21081
21082/// ONE RECT chroma transform unit of a square block's uv plane
21083/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
21084/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
21085/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
21086/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
21087/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
21088/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
21089/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
21090/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
21091/// predicted mode supplies the mode-derived default `tx_type` unless an armed
21092/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
21093/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
21094/// ([`read_plane`]'s `side >= 32` clamp).
21095#[allow(clippy::too_many_arguments)]
21096fn read_rect_chroma_unit(
21097 dec: &mut SymbolDecoder,
21098 cdfs: &mut Cdfs,
21099 set: TxbSet,
21100 scan: &[u16],
21101 w: usize,
21102 h: usize,
21103 plane_idx: usize,
21104 around: (bool, bool, i32),
21105 uv_predict_mode: usize,
21106 angle_delta_uv: i32,
21107 reach: Reach,
21108 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
21109 // the plane exclusively while the unit's coefficients are parsed.
21110 _plane: &mut PlaneBuf<'static>,
21111 x: usize,
21112 y: usize,
21113 // Signature parity with [`read_plane`]; the dequant reads its q index
21114 // off `block_q_idx(fctx)` like every other reader here.
21115 _base_q_idx: u8,
21116 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
21117 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
21118 // where `ctx_offset` is 10 when the plane block is bigger than the
21119 // transform and 7 otherwise. The port stores the offset-7 rows at
21120 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
21121 // (lane-av1-422b), so a unit SMALLER than its plane block passes
21122 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
21123 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
21124 // rect unit except in the chunk arms.
21125 chroma_skip_offset: Option<usize>,
21126 cfl: Option<(i32, CflSrc)>,
21127 smooth_neighbor_uv: bool,
21128 fctx: &crate::decode::FrameCtx,
21129) -> Result<Grid> {
21130 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
21131 hit!(CHROMA422_RECT_HITS);
21132 }
21133 let default_tx = if w.max(h) >= 32 {
21134 TxType::DctDct
21135 } else {
21136 fctx.intrabc_chroma_tx
21137 .with(std::cell::Cell::get)
21138 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8))
21139 };
21140 let mut coding = cdfs.txb(set, uv_predict_mode);
21141 let (levels, tx_type) = read_coeffs_rect(
21142 dec,
21143 &mut coding,
21144 scan,
21145 w,
21146 h,
21147 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
21148 dc_sign_ctx(around.2),
21149 default_tx,
21150 plane_idx,
21151 )?;
21152 let residual = dequant_and_inverse_typed_wh(
21153 &levels,
21154 w,
21155 h,
21156 crate::decode::bit_depth(fctx),
21157 block_q_idx(fctx),
21158 plane_q_delta(plane_idx, fctx).0,
21159 plane_q_delta(plane_idx, fctx).1,
21160 tx_type,
21161 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
21162 );
21163 push_intra_rect(
21164 plane_idx,
21165 x,
21166 y,
21167 w,
21168 h,
21169 uv_predict_mode,
21170 angle_delta_uv,
21171 reach,
21172 &residual,
21173 cfl,
21174 None,
21175 smooth_neighbor_uv,
21176 fctx,
21177 );
21178 Ok(levels)
21179}
21180
21181/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
21182/// three planes, reconstructing them into `y`/`u`/`v` and updating
21183/// `neighbours`.
21184#[allow(clippy::too_many_arguments)]
21185fn decode_block(
21186 dec: &mut SymbolDecoder,
21187 cdfs: &mut Cdfs,
21188 neighbours: &mut Neighbours,
21189 at: (usize, usize),
21190 side: usize,
21191 luma_set: TxbSet,
21192 chroma_set: TxbSet,
21193 luma_tx: usize,
21194 chroma_tx: usize,
21195 scans: (&[u16], &[u16]),
21196 cfl: bool,
21197 y: &mut PlaneBuf<'static>,
21198 u: &mut PlaneBuf<'static>,
21199 v: &mut PlaneBuf<'static>,
21200 base_q_idx: u8,
21201 enable_filter_intra: bool,
21202 allow_screen_content_tools: bool,
21203 allow_intrabc: bool,
21204 scan32: &[u16],
21205 scan16: &[u16],
21206 scan8: &[u16],
21207 scan4: &[u16],
21208 tx_select: bool,
21209 reduced_tx_set: bool,
21210 fctx: &crate::decode::FrameCtx,
21211) -> Result<()> {
21212 let (r, c) = at;
21213 let (px, py) = (c * SUB, r * SUB);
21214 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
21215 let palette_uv_cache = neighbours.palette_uv_cache(at);
21216 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
21217 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
21218 let (
21219 skip,
21220 mode,
21221 angle_delta_y,
21222 uv_mode,
21223 angle_delta_uv,
21224 alpha,
21225 filter_intra,
21226 palette_y,
21227 palette_uv,
21228 ) = read_intra_mode(
21229 dec,
21230 cdfs,
21231 nb_above_mode,
21232 nb_left_mode,
21233 cfl,
21234 side,
21235 enable_filter_intra,
21236 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
21237 allow_screen_content_tools,
21238 allow_intrabc,
21239 Some((palette_ctx, &palette_cache)),
21240 &palette_uv_cache,
21241 r * (SUB / MI),
21242 c * (SUB / MI),
21243 fctx,
21244 )?;
21245 if at_tile_left && palette_y.is_some() {
21246 hit!(PALETTE_TILE_LEFT_HITS);
21247 }
21248 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
21249 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
21250 // tables/scans are replaced by the 4x4 ones and the block always takes the
21251 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
21252 // sit at the TOP of the function -- before `read_intra_mode`, which is
21253 // where the block's own `segment_id` is read -- so a mixed frame resolved
21254 // every block's geometry against the PREVIOUS block's segment (a lossless
21255 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
21256 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
21257 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
21258 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
21259 // rewrite (which sat above `read_intra_mode`) rides along here -- same
21260 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
21261 // segment like the lossless arm above it.
21262 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
21263 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
21264 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
21265 let tx = if side >= 64 { 32 } else { side };
21266 let (set, scan): (TxbSet, &[u16]) = match tx {
21267 32 => (TxbSet::Chroma32, scan32),
21268 16 => (TxbSet::Chroma16, scan16),
21269 8 => (TxbSet::Chroma8, scan8),
21270 _ => (TxbSet::Chroma4, scan4),
21271 };
21272 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
21273 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21274 // lane-av1-422f: the uv plane block is the (side/2, side) rect
21275 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
21276 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
21277 // the RECT that fills the plane block, NOT the square transform of
21278 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
21279 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
21280 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
21281 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
21282 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
21283 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
21284 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
21285 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
21286 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
21287 let (tx_w, tx_h) = match side {
21288 4 => (4, 4),
21289 8 => (4, 8),
21290 16 => (8, 16),
21291 32 => (16, 32),
21292 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
21293 _ => (32, 32),
21294 };
21295 let (set, scan): (TxbSet, &[u16]) = match side {
21296 4 => (TxbSet::Chroma4, scan4),
21297 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
21298 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
21299 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
21300 _ => (TxbSet::Chroma32, scan32),
21301 };
21302 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
21303 } else {
21304 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
21305 };
21306 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
21307 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
21308 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
21309 // actual chroma-from-luma correlation, same as this decoder always did.
21310 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
21311 DC_PRED
21312 } else {
21313 uv_mode
21314 };
21315 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
21316 if smooth_neighbor {
21317 hit!(SMOOTH_LUMA_HITS);
21318 }
21319 let smooth_neighbor_uv =
21320 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
21321 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21322 eprintln!(
21323 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
21324 angle_delta_uv={angle_delta_uv}"
21325 );
21326 }
21327 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
21328 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
21329 // block, skipped or not. `logical_tx` is what the loop filter's edge
21330 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
21331 // transform size -- 64 even for the 64x64 corner-scanned case, spec
21332 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
21333 // which only differs from it at that one corner case.
21334 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
21335 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
21336 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
21337 // intrabc block reads NO tx-size symbol at all -- it takes
21338 // `maxRectTxSize` -- while every ordinary skipped intra block does read
21339 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
21340 // the tile from that block on (class `equal-range-means-unread`).
21341 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
21342 // tree instead (`read_var_tx_size`), the same syntax the inter block path
21343 // has always read -- libaom's `parse_decode_block` dispatches on
21344 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
21345 // intrabc block as inter.
21346 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
21347 // libaom `parse_decode_block`'s var-tx tree condition carries
21348 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
21349 // block inside a LOSSLESS segment of a mixed frame reads NO
21350 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
21351 // hands back TX_4X4. Invisible while every lossless frame was also
21352 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
21353 // is why the mixed frame is the first stream to reach it.
21354 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
21355 let intrabc_leaves = if intrabc_vartx {
21356 let max_tx = side.min(64);
21357 // `max_block_wide`/`max_block_high`: the frame's own mi grid
21358 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
21359 // right/bottom edge reads no split symbol for the units outside it.
21360 let mi_cols = 2 * y.true_width.div_ceil(8);
21361 let mi_rows = 2 * y.true_height.div_ceil(8);
21362 let side_mi = side / MI;
21363 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
21364 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
21365 let mut leaves = Vec::new();
21366 for row in (0..side_mi).step_by(max_tx / MI) {
21367 for col in (0..side_mi).step_by(max_tx / MI) {
21368 read_var_tx_size(
21369 dec,
21370 cdfs,
21371 neighbours,
21372 (mi_r, mi_c),
21373 side,
21374 (max_w_mi, max_h_mi),
21375 (max_tx, max_tx),
21376 0,
21377 row,
21378 col,
21379 &mut leaves,
21380 );
21381 }
21382 }
21383 hit!(INTRABC_VARTX_HITS);
21384 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
21385 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
21386 // longer refused -- the luma reconstruct below walks the tree's own
21387 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
21388 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
21389 // transform unit), so mixed sizes reconstruct at their own stride.
21390 // The counter marks the shape so a gate can prove a witness actually
21391 // carries a mixed tree and not merely another uniform one.
21392 let uniform = leaves.first().is_some_and(|f| {
21393 leaves
21394 .iter()
21395 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
21396 });
21397 if !uniform {
21398 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
21399 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
21400 eprintln!(
21401 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
21402 dv={intrabc_dv:?} leaves={leaves:?}"
21403 );
21404 }
21405 }
21406 Some(leaves)
21407 } else {
21408 None
21409 };
21410 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
21411 (tx, if tx == 64 { 32 } else { tx })
21412 } else if tx_select && !intrabc_skip_tx {
21413 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
21414 (resolved, if resolved == 64 { 32 } else { resolved })
21415 } else {
21416 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
21417 // TX_64X64, so a 128x128 block is always FOUR luma transform units
21418 // even with `tx_select` off -- the TU loop below, never the
21419 // single-unit path.
21420 (lossless_tx(side.min(64), fctx), luma_tx)
21421 };
21422 if tx_select && logical_tx < side && uv_mode != DC_PRED {
21423 hit!(SQ_CHROMA_TX_HITS);
21424 }
21425 let luma_set = if tx_select {
21426 txbset_for(logical_tx, reduced_tx_set)
21427 } else {
21428 luma_set
21429 };
21430 let luma_set = if intrabc_dv.is_some() {
21431 inter_txbset_for(logical_tx, reduced_tx_set)
21432 } else {
21433 luma_set
21434 };
21435 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
21436 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
21437 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
21438 let chroma_side = side >> ss_x(fctx);
21439 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
21440 // `side / 2` at 4:2:0.
21441 let chroma_height = side >> ss_y(fctx);
21442 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
21443 // frame's own pre-loop-filter reconstruction (all loop filters are off
21444 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
21445 // block vector, with the BILINEAR kernel libaom forces for intrabc --
21446 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
21447 // odd, which is exactly what the bilinear taps then interpolate.
21448 flush_recon(fctx, y, u, v);
21449 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
21450 let mut yb = vec![0u16; side * side];
21451 mc::predict_with_filter(
21452 &y.data,
21453 y.width,
21454 y.true_width,
21455 y.true_height,
21456 mv_to_q4(px, dv_col, 0),
21457 mv_to_q4(py, dv_row, 0),
21458 side,
21459 side,
21460 mc::InterpFilterKind::Bilinear,
21461 &mut yb,
21462 fctx,
21463 );
21464 let mut ub = vec![0u16; chroma_side * chroma_height];
21465 mc::predict_with_filter(
21466 &u.data,
21467 u.width,
21468 u.true_width,
21469 u.true_height,
21470 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21471 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21472 chroma_side,
21473 chroma_height,
21474 mc::InterpFilterKind::Bilinear,
21475 &mut ub,
21476 fctx,
21477 );
21478 let mut vb = vec![0u16; chroma_side * chroma_height];
21479 mc::predict_with_filter(
21480 &v.data,
21481 v.width,
21482 v.true_width,
21483 v.true_height,
21484 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21485 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21486 chroma_side,
21487 chroma_height,
21488 mc::InterpFilterKind::Bilinear,
21489 &mut vb,
21490 fctx,
21491 );
21492 (yb, ub, vb)
21493 });
21494 // A palette-Y block's own prediction is the reconstructed colour-index
21495 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
21496 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
21497 // parameter through this function's dozen `y.reconstruct`/`read_plane`
21498 // sites. A split luma transform (`tx_select && logical_tx != side`)
21499 // would need the map sliced per-TU -- untested against a real
21500 // `--enable-palette=1` stream this round, so refuse by name rather than
21501 // guess at the slicing (charter's own named-acceptable fallback).
21502 let palette_y_buf: Option<Vec<u16>> = palette_y
21503 .as_ref()
21504 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
21505 // lane-t900 r32: the intrabc luma prediction rides the very same
21506 // whole-block override slot, so the multi-TU loop below windows it per
21507 // transform unit exactly like a palette map -- setting it once up front
21508 // handed the whole `side`x`side` buffer to the FIRST unit and left every
21509 // later one predicting off block edges (the var-tx tree above is what
21510 // first makes `logical_tx < side` reachable for an intrabc block).
21511 let palette_y_buf = match &intrabc_bufs {
21512 Some((yb, _, _)) => Some(yb.clone()),
21513 None => palette_y_buf,
21514 };
21515 // With one luma transform unit the whole `side`x`side` map is the
21516 // prediction; with several (`logical_tx != side`) each unit takes its own
21517 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
21518 // below (lane-palette2 r7) -- setting the full-block buffer here would be
21519 // taken by the FIRST unit and indexed at the wrong stride.
21520 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
21521 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
21522 // `split_tx_skip` walk), so its map must be armed here even when the
21523 // transform is split. Gating the arm on `logical_tx == side` alone left a
21524 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
21525 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
21526 // key frame; class override-slot-on-one-arm). Neither prediction is
21527 // edge-derived, so the whole-block buffer at the block's own stride is
21528 // exactly what that single call wants.
21529 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
21530 // that reaches this block apart from one that never does (class
21531 // gate-blind-to-feature).
21532 if palette_y_buf.is_some() && skip && logical_tx < side {
21533 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
21534 }
21535 if let Some(buf) = &palette_y_buf
21536 && (logical_tx == side || skip)
21537 {
21538 set_palette_pred(buf.clone(), fctx);
21539 }
21540 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
21541 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
21542 // plane's own `reconstruct`/`read_plane` call below (never both planes at
21543 // once), since Y's own set-then-take already emptied the slot by the time
21544 // either of these run.
21545 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
21546 (
21547 puv.map
21548 .iter()
21549 .map(|&idx| puv.u_colors[idx as usize])
21550 .collect(),
21551 puv.map
21552 .iter()
21553 .map(|&idx| puv.v_colors[idx as usize])
21554 .collect(),
21555 )
21556 });
21557 // The chroma half of the intrabc prediction rides the same per-plane
21558 // override slot the UV-palette buffers do (set fresh before each plane's
21559 // own `reconstruct`/`read_plane` call below).
21560 let palette_uv_bufs = match &intrabc_bufs {
21561 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
21562 None => palette_uv_bufs,
21563 };
21564 if skip {
21565 // A skipped block codes no residual syntax at all (spec 5.11.34):
21566 // straight prediction, on every plane.
21567 //
21568 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
21569 // is skipped (only an INTER skip forces the largest transform), and
21570 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
21571 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
21572 // already written left/above of it inside this same block. Predicting
21573 // the whole `side`x`side` at once gives a different (uniformly off by
21574 // ~1) answer, which is exactly the residue this lane was chasing.
21575 // The palette/intrabc override path keeps the single-call shape (its
21576 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
21577 // untested for skip and unreachable in these streams).
21578 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
21579 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
21580 // per-unit prediction is keyed on the transform being smaller than
21581 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
21582 // narrower meaning (a READ split tx depth).
21583 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
21584 if split_tx_skip {
21585 if tx_select {
21586 hit!(SKIP_SPLIT_TX_HITS);
21587 }
21588 let n_axis = side / logical_tx;
21589 for tu_row in 0..n_axis {
21590 for tu_col in 0..n_axis {
21591 let tu_px = px + tu_col * logical_tx;
21592 let tu_py = py + tu_row * logical_tx;
21593 if tu_px >= y.true_width || tu_py >= y.true_height {
21594 continue;
21595 }
21596 let tu_reach = tu_reach(
21597 side,
21598 side,
21599 tu_col * logical_tx,
21600 tu_row * logical_tx,
21601 logical_tx,
21602 reach,
21603 px,
21604 py,
21605 y.width,
21606 y.height,
21607 fctx,
21608 );
21609 push_intra(
21610 0,
21611 tu_px,
21612 tu_py,
21613 logical_tx,
21614 mode,
21615 angle_delta_y,
21616 tu_reach,
21617 &ZERO_RESIDUAL[..logical_tx * logical_tx],
21618 None,
21619 filter_intra,
21620 smooth_neighbor,
21621 fctx,
21622 );
21623 }
21624 }
21625 } else {
21626 push_intra(
21627 0,
21628 px,
21629 py,
21630 side,
21631 mode,
21632 angle_delta_y,
21633 reach,
21634 &ZERO_RESIDUAL[..side * side],
21635 None,
21636 filter_intra,
21637 smooth_neighbor,
21638 fctx,
21639 );
21640 }
21641 let ac = alpha.map(|_| cfl_src(px, py, side));
21642 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
21643 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
21644 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
21645 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
21646 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
21647 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
21648 // reads ONE unit per plane, the whole plane block).
21649 let cn_cols = (chroma_side / chroma_tx).max(1);
21650 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21651 let luma_span_x = chroma_tx << ss_x(fctx);
21652 let luma_span_y = chroma_tx_h << ss_y(fctx);
21653 for cu_row in 0..cn_rows {
21654 for cu_col in 0..cn_cols {
21655 let cu_r = if cn_rows == 1 && cn_cols == 1 {
21656 reach
21657 } else {
21658 tu_reach_rect(
21659 side,
21660 side,
21661 cu_col * luma_span_x,
21662 cu_row * luma_span_y,
21663 luma_span_x,
21664 luma_span_y,
21665 reach,
21666 px,
21667 py,
21668 y.width,
21669 y.height,
21670 fctx,
21671 )
21672 };
21673 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21674 if let Some((ub, _)) = &palette_uv_bufs {
21675 set_palette_pred(ub.clone(), fctx);
21676 }
21677 push_intra_unit(
21678 1,
21679 cu_x,
21680 cu_y,
21681 chroma_tx,
21682 chroma_tx_h,
21683 uv_predict_mode,
21684 angle_delta_uv,
21685 cu_r,
21686 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21687 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21688 None,
21689 smooth_neighbor_uv,
21690 fctx,
21691 );
21692 if let Some((_, vb)) = &palette_uv_bufs {
21693 set_palette_pred(vb.clone(), fctx);
21694 }
21695 push_intra_unit(
21696 2,
21697 cu_x,
21698 cu_y,
21699 chroma_tx,
21700 chroma_tx_h,
21701 uv_predict_mode,
21702 angle_delta_uv,
21703 cu_r,
21704 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21705 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21706 None,
21707 smooth_neighbor_uv,
21708 fctx,
21709 );
21710 }
21711 }
21712 let luma_grid = vec![0i32; side * side];
21713 let u_grid = vec![0i32; chroma_side * chroma_side];
21714 let v_grid = vec![0i32; chroma_side * chroma_side];
21715 neighbours.record(
21716 at,
21717 side,
21718 mode,
21719 uv_predict_mode,
21720 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21721 );
21722 } else if logical_tx == side {
21723 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
21724 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
21725 // that arm was redundant -- and wrong at 128, where
21726 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
21727 // block is four units whether or not `tx_select` is on.
21728 // A single luma transform unit -- the old path, unchanged (including
21729 // the 64x64 corner case, `logical_tx == side == 64` with
21730 // `coeff_tx_side == 32`).
21731 let around = neighbours.around(at, side);
21732 let luma_grid = read_plane(
21733 dec,
21734 cdfs,
21735 luma_set,
21736 luma_scan,
21737 0,
21738 around[0],
21739 mode,
21740 mode,
21741 angle_delta_y,
21742 reach,
21743 y,
21744 px,
21745 py,
21746 side,
21747 coeff_tx_side,
21748 base_q_idx,
21749 None,
21750 filter_intra,
21751 None,
21752 smooth_neighbor,
21753 fctx,
21754 )?;
21755 let ac = alpha.map(|_| cfl_src(px, py, side));
21756 // Armed for exactly this block's two chroma reads (see
21757 // [`INTRABC_CHROMA_TX`]); the luma call above just set
21758 // [`LUMA_TX_TYPE`] to the type it coded.
21759 if intrabc_dv.is_some() {
21760 fctx.intrabc_chroma_tx
21761 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
21762 }
21763 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
21764 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
21765 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
21766 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
21767 // (every U, then every V) — the same loop the multi-TU arm runs.
21768 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
21769 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
21770 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
21771 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
21772 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
21773 // unit is the plane block's own rect.
21774 let cn_cols = (chroma_side / chroma_tx).max(1);
21775 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21776 let luma_span_x = chroma_tx << ss_x(fctx);
21777 let luma_span_y = chroma_tx_h << ss_y(fctx);
21778 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
21779 if chroma_tx == chroma_tx_h {
21780 if let Some((ub, _)) = &palette_uv_bufs {
21781 set_palette_pred(ub.clone(), fctx);
21782 }
21783 let u_grid = read_plane(
21784 dec,
21785 cdfs,
21786 chroma_set,
21787 scans.1,
21788 1,
21789 around[1],
21790 mode,
21791 uv_predict_mode,
21792 angle_delta_uv,
21793 reach,
21794 u,
21795 cpx,
21796 cpy,
21797 chroma_side,
21798 chroma_tx,
21799 base_q_idx,
21800 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21801 None,
21802 None,
21803 smooth_neighbor_uv,
21804 fctx,
21805 )?;
21806 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21807 eprintln!(
21808 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
21809 &u.data[cpy * u.width + cpx..][..chroma_side]
21810 );
21811 }
21812 if let Some((_, vb)) = &palette_uv_bufs {
21813 set_palette_pred(vb.clone(), fctx);
21814 }
21815 let v_grid = read_plane(
21816 dec,
21817 cdfs,
21818 chroma_set,
21819 scans.1,
21820 2,
21821 around[2],
21822 mode,
21823 uv_predict_mode,
21824 angle_delta_uv,
21825 reach,
21826 v,
21827 cpx,
21828 cpy,
21829 chroma_side,
21830 chroma_tx,
21831 base_q_idx,
21832 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21833 None,
21834 None,
21835 smooth_neighbor_uv,
21836 fctx,
21837 )?;
21838 (u_grid, v_grid, Vec::new())
21839 } else {
21840 // lane-av1-422f: the one unit is a RECT filling the plane
21841 // block -- the square-shaped [`read_plane`] cannot express
21842 // it, so both planes go through [`read_rect_chroma_unit`]
21843 // (U, then V, the same order the square arm reads). The
21844 // chroma context reads per chroma 4-px cell (see
21845 // [`Neighbours::around_mi_422_chroma`]).
21846 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
21847 if let Some((ub, _)) = &palette_uv_bufs {
21848 set_palette_pred(ub.clone(), fctx);
21849 }
21850 let u_grid = read_rect_chroma_unit(
21851 dec,
21852 cdfs,
21853 chroma_set,
21854 scans.1,
21855 chroma_tx,
21856 chroma_tx_h,
21857 1,
21858 chroma_around[1],
21859 uv_predict_mode,
21860 angle_delta_uv,
21861 reach,
21862 u,
21863 cpx,
21864 cpy,
21865 base_q_idx,
21866 None,
21867 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21868 smooth_neighbor_uv,
21869 fctx,
21870 )?;
21871 if let Some((_, vb)) = &palette_uv_bufs {
21872 set_palette_pred(vb.clone(), fctx);
21873 }
21874 let v_grid = read_rect_chroma_unit(
21875 dec,
21876 cdfs,
21877 chroma_set,
21878 scans.1,
21879 chroma_tx,
21880 chroma_tx_h,
21881 2,
21882 chroma_around[2],
21883 uv_predict_mode,
21884 angle_delta_uv,
21885 reach,
21886 v,
21887 cpx,
21888 cpy,
21889 base_q_idx,
21890 None,
21891 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21892 smooth_neighbor_uv,
21893 fctx,
21894 )?;
21895 (u_grid, v_grid, Vec::new())
21896 }
21897 } else {
21898 let chroma_ctx_offset = Some(3);
21899 let mut u_pass: Vec<Grid> = Vec::new();
21900 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21901 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21902 for plane_pass in 1..=2usize {
21903 let mut pass_idx = 0usize;
21904 for cu_row in 0..cn_rows {
21905 for cu_col in 0..cn_cols {
21906 let cu_mi = (
21907 mi_r + cu_row * (luma_span_y / MI),
21908 mi_c + cu_col * (luma_span_x / MI),
21909 );
21910 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21911 // lane-av1-422f: chroma-only loop; per-chroma-cell
21912 // above votes (see [`Neighbours::around_mi_422_chroma`]).
21913 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21914 } else {
21915 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21916 };
21917 let cu_reach = tu_reach_rect(
21918 side,
21919 side,
21920 cu_col * luma_span_x,
21921 cu_row * luma_span_y,
21922 luma_span_x,
21923 luma_span_y,
21924 reach,
21925 px,
21926 py,
21927 y.width,
21928 y.height,
21929 fctx,
21930 );
21931 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21932 if let Some((ub, vb)) = &palette_uv_bufs {
21933 let pbuf = if plane_pass == 1 { ub } else { vb };
21934 set_palette_pred(
21935 palette_window(
21936 pbuf,
21937 chroma_side,
21938 cu_col * chroma_tx,
21939 cu_row * chroma_tx_h,
21940 chroma_tx,
21941 chroma_tx_h,
21942 ),
21943 fctx,
21944 );
21945 }
21946 let buf: &mut PlaneBuf<'static> =
21947 if plane_pass == 1 { &mut *u } else { &mut *v };
21948 let cu_grid = read_plane(
21949 dec,
21950 cdfs,
21951 chroma_set,
21952 scans.1,
21953 plane_pass,
21954 cu_around[plane_pass],
21955 mode,
21956 uv_predict_mode,
21957 angle_delta_uv,
21958 cu_reach,
21959 buf,
21960 cu_x,
21961 cu_y,
21962 chroma_tx,
21963 chroma_tx,
21964 base_q_idx,
21965 alpha
21966 .zip(ac)
21967 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
21968 None,
21969 chroma_ctx_offset,
21970 smooth_neighbor_uv,
21971 fctx,
21972 )?;
21973 hit!(CHROMA_SPLIT_TX_HITS);
21974 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21975 hit!(CHROMA422_SQUARE_HITS);
21976 }
21977 // Immediately, so the next unit of this block reads this
21978 // one's coefficient context. `record` below stamps one
21979 // chroma state across the whole block; the replay after
21980 // it puts the per-unit state back.
21981 neighbours.record_mi_chroma(
21982 cu_mi,
21983 luma_span_x,
21984 luma_span_y,
21985 plane_pass,
21986 &cu_grid,
21987 );
21988 if plane_pass == 1 {
21989 u_pass.push(cu_grid);
21990 } else {
21991 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
21992 units.push((
21993 cu_mi,
21994 luma_span_x,
21995 luma_span_y,
21996 u_grid.clone(),
21997 cu_grid.clone(),
21998 ));
21999 last_grids = [u_grid, cu_grid];
22000 }
22001 pass_idx += 1;
22002 }
22003 }
22004 }
22005 (last_grids[0].clone(), last_grids[1].clone(), units)
22006 };
22007 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22008 neighbours.record(
22009 at,
22010 side,
22011 mode,
22012 uv_predict_mode,
22013 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22014 );
22015 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
22016 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
22017 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
22018 }
22019 } else {
22020 // Several luma transform units, raster order (spec
22021 // `transform_block`'s loop): the block's resolved transform is
22022 // genuinely smaller than its own side, so each tile of it predicts
22023 // and codes independently, its own context read fresh off whatever
22024 // the earlier tiles in this same block already wrote -- the same
22025 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
22026 let n_axis = side / logical_tx;
22027 // lane-av1-422f: unit width/height per axis, like walk 2 above --
22028 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
22029 // chunk, the whole plane block.
22030 let cn_cols = (chroma_side / chroma_tx).max(1);
22031 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22032 let luma_span_x = chroma_tx << ss_x(fctx);
22033 let luma_span_y = chroma_tx_h << ss_y(fctx);
22034 // libaom's transform-block loop is over 64x64 luma "mu" chunks
22035 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
22036 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
22037 // before moving to the next one. Below 128 a block is a single chunk,
22038 // so this is byte-for-byte the all-luma-then-all-chroma order that has
22039 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
22040 // and reading all four luma units first desyncs the tile at the second
22041 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
22042 let nchunk = (side / 64).max(1);
22043 // `cn > 1` means the uv plane block is larger than the uv transform,
22044 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
22045 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
22046 let tpc = (n_axis / nchunk).max(1);
22047 let cpc_rows = (cn_rows / nchunk).max(1);
22048 let cpc_cols = (cn_cols / nchunk).max(1);
22049 // The block's luma transform units, raster order inside each mu
22050 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
22051 // tree's own leaf list -- mixed sizes included, exactly what libaom's
22052 // `decode_token_recon_block` token loop reconstructs (one
22053 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
22054 // while every other block's list is the uniform `logical_tx` grid
22055 // this loop has always walked, generated here in the same order.
22056 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
22057 if let Some(leaves) = &intrabc_leaves {
22058 for &(lr, lc, tw, _th) in leaves {
22059 let (off_y, off_x) = (lr * MI, lc * MI);
22060 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
22061 }
22062 } else {
22063 for tu_row in 0..n_axis {
22064 for tu_col in 0..n_axis {
22065 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
22066 tu_row * logical_tx,
22067 tu_col * logical_tx,
22068 logical_tx,
22069 ));
22070 }
22071 }
22072 }
22073 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22074 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22075 for ch_row in 0..nchunk {
22076 for ch_col in 0..nchunk {
22077 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
22078 // type of the co-located luma position (`av1_get_tx_type`,
22079 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
22080 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
22081 // luma unit covering it). Inside a mu chunk that is the chunk's
22082 // FIRST luma unit in raster order (the chunk origin is always the
22083 // first leaf's own origin). Captured right after that unit's read;
22084 // the single-TU arm below does the same for a whole-block unit.
22085 let mut first_leaf_tx: Option<TxType> = None;
22086 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
22087 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
22088 let tu_px = px + tu_off_x;
22089 let tu_py = py + tu_off_y;
22090 // Same libaom clip as `decode_rect_split`'s loop above; a
22091 // square block only hangs off the frame when the frame's mi
22092 // dimensions are odd at the block's own level.
22093 if tu_px >= y.true_width || tu_py >= y.true_height {
22094 continue;
22095 }
22096 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
22097 // A transform unit inside a block is NOT a block at that
22098 // position (lane-palette2 r12): `Reach::of` granted the
22099 // top-right 8x8 unit of a 16x16 D203 block bottom-left
22100 // pixels libaom refuses outright (`col_off > 0`), which is
22101 // the diagonal wedge seed 46 reconstructed wrong.
22102 let tu_reach = tu_reach(
22103 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
22104 fctx,
22105 );
22106 // This transform unit's own bsize (`tu_tx`) is smaller
22107 // than the block it sits in (`side`), so `txb_skip_ctx` is
22108 // the neighbour-magnitude table, not the lone-TU 0 (spec
22109 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
22110 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
22111 // An intrabc unit's CDF set and scan follow the unit's OWN
22112 // resolved size (`get_txsize_entropy_ctx` /
22113 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
22114 // uniform grid's precomputed pair already matches because
22115 // `tu_tx == logical_tx` there.
22116 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
22117 (
22118 inter_txbset_for(tu_tx, reduced_tx_set),
22119 scan_for(
22120 if tu_tx == 64 { 32 } else { tu_tx },
22121 scan32,
22122 scan16,
22123 scan8,
22124 scan4,
22125 ),
22126 )
22127 } else {
22128 (luma_set, luma_scan)
22129 };
22130 if let Some(buf) = &palette_y_buf {
22131 hit!(PALETTE_SPLIT_TX_HITS);
22132 let mut window = vec![0u16; tu_tx * tu_tx];
22133 for row in 0..tu_tx {
22134 let src = (tu_off_y + row) * side + tu_off_x;
22135 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
22136 }
22137 set_palette_pred(window, fctx);
22138 }
22139 let tu_grid = read_plane(
22140 dec,
22141 cdfs,
22142 tu_set,
22143 tu_scan,
22144 0,
22145 tu_around,
22146 mode,
22147 mode,
22148 angle_delta_y,
22149 tu_reach,
22150 y,
22151 tu_px,
22152 tu_py,
22153 tu_tx,
22154 // The unit's own COEFFICIENT grid, half its side at
22155 // TX_64X64 (a 64-point transform codes nothing past 32);
22156 // identical to `tu_tx` at every smaller size
22157 // (lane-sb128b r1).
22158 if tu_tx == 64 { 32 } else { tu_tx },
22159 base_q_idx,
22160 None,
22161 filter_intra,
22162 Some(tu_skip_ctx),
22163 smooth_neighbor,
22164 fctx,
22165 )?;
22166 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22167 eprintln!(
22168 "TRACE tu_bitpos mi=({},{}) tell={}",
22169 tu_mi.0,
22170 tu_mi.1,
22171 dec.debug_bitpos()
22172 );
22173 }
22174 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
22175 if first_leaf_tx.is_none() {
22176 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
22177 }
22178 }
22179 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
22180 // this still runs after every luma unit of the block.
22181 let ac = alpha.map(|_| cfl_src(px, py, side));
22182 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
22183 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
22184 // branch sets before its own chroma reads.
22185 if intrabc_dv.is_some() {
22186 if let Some(t) = first_leaf_tx {
22187 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
22188 }
22189 }
22190 // The block's uv plane block is `chroma_side` across but its uv
22191 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
22192 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
22193 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
22194 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
22195 // FOUR units (lane-sb128b r2) -- one per mu chunk.
22196 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
22197 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
22198 // the chunk, then every V unit. At one unit per plane per chunk --
22199 // every non-lossless case this decoder reaches -- that is the same
22200 // symbol order as the interleaved pair this loop used to read; a
22201 // lossless frame's 4x4 chroma units are the case where it differs
22202 // (lane-lossless2).
22203 let mut u_pass: Vec<Grid> = Vec::new();
22204 for plane_pass in 1..=2usize {
22205 let mut pass_idx = 0usize;
22206 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
22207 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
22208 // libaom `decode_reconstruct_tx`'s frame-edge clip
22209 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
22210 // >= max_blocks_wide` returns before ANY symbol is read): a
22211 // transform unit whose 4x4 origin sits outside the frame's mi
22212 // grid is not coded at all. The luma loop above carries the
22213 // same clip; its absence here read `txb_skip` (+coeffs) for
22214 // chroma units libaom never wrote -- the lossless 64x64 block
22215 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
22216 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
22217 // eight (lane-av1-loss64; 48 chroma units per plane in
22218 // aomdec's EC_COEFF census vs the 64 this loop read).
22219 // `max_block_wide/high` (av1_common_int.h:1565): the plane
22220 // block's pixel span (4:2:0 halves the luma span, clamped to
22221 // 4 by `set_plane_n4`) plus the negative overhang
22222 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
22223 // units.
22224 let span_mi = side / MI;
22225 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
22226 - mi_c as i32
22227 - span_mi as i32;
22228 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
22229 - mi_r as i32
22230 - span_mi as i32;
22231 // `max_block_wide/high` in chroma pixels: the plane block's
22232 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
22233 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
22234 // block's coded units and desynced the tile) plus the
22235 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
22236 // chroma-px scale is `MI >> ss` per mi.
22237 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
22238 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
22239 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
22240 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
22241 // lane-av1-422f: the shared halved formula in the `else` counts
22242 // the plane span in 4-px units through the 2-px-per-mi
22243 // subsampled height, which a 4:2:2 plane does not have (ss_y
22244 // 0) -- its span is the full luma mi count, so a keyed
22245 // formula clips the same units libaom's `max_block_high`
22246 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
22247 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
22248 // pre-ss form spelled).
22249 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22250 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
22251 } else {
22252 ((plane_px + over_h_px) >> 2).max(0) as usize
22253 };
22254 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
22255 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
22256 hit!(CHROMA_EDGE_TU_CLIP_HITS);
22257 continue;
22258 }
22259 // The chroma context arrays are indexed in LUMA mi, so this
22260 // unit's anchor is its own luma quadrant (lane-av1-422b: the
22261 // quadrant spans `chroma_tx << ss_x` luma px wide by
22262 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
22263 // one unit's quadrant is the whole block).
22264 let cu_mi = (
22265 mi_r + cu_row * (luma_span_y / MI),
22266 mi_c + cu_col * (luma_span_x / MI),
22267 );
22268 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22269 // lane-av1-422f: chroma-only loop; per-chroma-cell above
22270 // votes (see [`Neighbours::around_mi_422_chroma`]).
22271 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
22272 } else {
22273 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
22274 };
22275 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
22276 reach
22277 } else {
22278 tu_reach_rect(
22279 side,
22280 side,
22281 cu_col * luma_span_x,
22282 cu_row * luma_span_y,
22283 luma_span_x,
22284 luma_span_y,
22285 reach,
22286 px,
22287 py,
22288 y.width,
22289 y.height,
22290 fctx,
22291 )
22292 };
22293 let (cu_x, cu_y) =
22294 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22295 if let Some((ub, vb)) = &palette_uv_bufs {
22296 let pbuf = if plane_pass == 1 { ub } else { vb };
22297 set_palette_pred(
22298 palette_window(
22299 pbuf,
22300 chroma_side,
22301 cu_col * chroma_tx,
22302 cu_row * chroma_tx_h,
22303 chroma_tx,
22304 chroma_tx_h,
22305 ),
22306 fctx,
22307 );
22308 }
22309 let buf: &mut PlaneBuf<'static> =
22310 if plane_pass == 1 { &mut *u } else { &mut *v };
22311 let cu_grid = if chroma_tx == chroma_tx_h {
22312 read_plane(
22313 dec,
22314 cdfs,
22315 chroma_set,
22316 scans.1,
22317 plane_pass,
22318 cu_around[plane_pass],
22319 mode,
22320 uv_predict_mode,
22321 angle_delta_uv,
22322 cu_reach,
22323 buf,
22324 cu_x,
22325 cu_y,
22326 chroma_tx,
22327 chroma_tx,
22328 base_q_idx,
22329 alpha.zip(ac).map(|((au, av), ac)| {
22330 (if plane_pass == 1 { au } else { av }, ac)
22331 }),
22332 None,
22333 chroma_ctx_offset,
22334 smooth_neighbor_uv,
22335 fctx,
22336 )?
22337 } else {
22338 // lane-av1-422f: the whole plane block as one rect unit;
22339 // `chroma_ctx_offset` is `None` there (the unit covers
22340 // the plane block, so the offset-7 skip rows are right).
22341 read_rect_chroma_unit(
22342 dec,
22343 cdfs,
22344 chroma_set,
22345 scans.1,
22346 chroma_tx,
22347 chroma_tx_h,
22348 plane_pass,
22349 cu_around[plane_pass],
22350 uv_predict_mode,
22351 angle_delta_uv,
22352 cu_reach,
22353 buf,
22354 cu_x,
22355 cu_y,
22356 base_q_idx,
22357 None,
22358 alpha.zip(ac).map(|((au, av), ac)| {
22359 (if plane_pass == 1 { au } else { av }, ac)
22360 }),
22361 smooth_neighbor_uv,
22362 fctx,
22363 )?
22364 };
22365 if cn_rows * cn_cols > 1 {
22366 hit!(CHROMA_SPLIT_TX_HITS);
22367 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22368 hit!(CHROMA422_SQUARE_HITS);
22369 }
22370 // Immediately, so the NEXT unit of this same block reads
22371 // this one's coefficient context (libaom's chroma
22372 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
22373 // 1 from this left neighbour -- measured against aomdec).
22374 // The same writes are replayed after `record_split_luma`
22375 // below, which would otherwise clobber them whole-block.
22376 neighbours.record_mi_chroma(
22377 cu_mi,
22378 luma_span_x,
22379 luma_span_y,
22380 plane_pass,
22381 &cu_grid,
22382 );
22383 }
22384 if plane_pass == 1 {
22385 u_pass.push(cu_grid);
22386 } else {
22387 let u_grid =
22388 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22389 if cn_rows * cn_cols > 1 {
22390 units.push((
22391 cu_mi,
22392 luma_span_x,
22393 luma_span_y,
22394 u_grid.clone(),
22395 cu_grid.clone(),
22396 ));
22397 }
22398 last_grids = [u_grid, cu_grid];
22399 }
22400 pass_idx += 1;
22401 }
22402 }
22403 }
22404 }
22405 if intrabc_dv.is_some() {
22406 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22407 }
22408 }
22409 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
22410 // context write; at `cn > 1` the per-unit writes above are what the
22411 // next block reads, so they run after this (last writer wins).
22412 neighbours.record_split_luma(
22413 at,
22414 side,
22415 mode,
22416 uv_predict_mode,
22417 [&last_grids[0], &last_grids[1]],
22418 );
22419 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
22420 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
22421 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
22422 }
22423 }
22424 // Unconditional, `size == 0` for a non-palette block: clears any stale
22425 // neighbour palette state the same way [`Neighbours::record`] always
22426 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
22427 // (the split-luma-TU branch above always refuses before reaching here
22428 // when `palette_y` is `Some`, so it is never live for that branch).
22429 let (py_size, py_colors) = palette_y
22430 .as_ref()
22431 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22432 neighbours.record_palette_y(at, side, py_size, py_colors);
22433 let (puv_size, puv_colors) = palette_uv
22434 .as_ref()
22435 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22436 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
22437 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
22438 neighbours.fill_lf_grid(
22439 (r * (SUB / MI), c * (SUB / MI)),
22440 side / MI,
22441 logical_tx as u8,
22442 0,
22443 fctx,
22444 );
22445 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
22446 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
22447 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
22448 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
22449 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
22450 // intrabc block publish its BLOCK size instead, intrabc being the only
22451 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
22452 // stays the authority wherever one can appear; with `allow_intrabc` unset
22453 // it writes exactly what the grid already did.
22454 if allow_intrabc {
22455 set_txfm_ctxs(
22456 neighbours,
22457 (mi_r, mi_c),
22458 logical_tx,
22459 side / MI,
22460 side / MI,
22461 skip && intrabc_dv.is_some(),
22462 );
22463 }
22464 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
22465 Ok(())
22466}
22467
22468thread_local! {
22469 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
22470 /// root's HORZ arm, and 64x128 ones at its VERT arm.
22471 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22472 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22473 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
22474 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
22475 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
22476 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
22477 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
22478 /// inter frame) -- (128x64, 64x128).
22479 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
22480 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
22481 /// handed back var-tx leaves, so the per-transform-unit luma publication
22482 /// loop never ran and the block has to clear its own luma coefficient
22483 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
22484 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
22485 /// non-vacuous.
22486 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22487 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
22488 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
22489 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
22490 /// shape non-vacuous -- a stream that never codes one reads 0.
22491 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22492 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
22493 /// intra block re-stamped by the end-of-block replay
22494 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
22495 /// walk published, so every unit replays its own state after it). A
22496 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
22497 /// of them, so this reads 0 on any stream that never codes one -- the
22498 /// non-vacuity anchor for the replay's own gate.
22499 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22500 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
22501 /// height differs from the unit's own LUMA-MI height -- the signature of the
22502 /// width passed to both axes (`luma_span` where the in-loop stamp used
22503 /// `luma_span_h`). Zero on every stream this decoder admits: both
22504 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
22505 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
22506 /// at the sequence header (`stream::decode_frame`), so the arm is
22507 /// defensive until that format is ported. The counter turns a future
22508 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
22509 /// of silent mi-state corruption.
22510 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22511}
22512
22513/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
22514pub fn skip_vartx_luma_reset_hits() -> usize {
22515 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
22516}
22517
22518/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
22519pub(crate) fn intra128_lossless_hits() -> usize {
22520 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
22521}
22522
22523/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
22524pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
22525 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
22526}
22527
22528/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
22529/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
22530pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
22531 (
22532 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
22533 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
22534 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
22535 )
22536}
22537
22538/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
22539/// `decode_block_128rect`'s end-of-block replay) and
22540/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
22541/// not the unit's own), for a gate's own before/after delta.
22542pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
22543 (
22544 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
22545 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
22546 )
22547}
22548
22549/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
22550/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
22551/// `decode_inter_block`'s own rect path).
22552///
22553/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
22554/// transform unit, with the 128-specific geometry:
22555/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
22556/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
22557/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
22558/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
22559/// same CDF a 64x64 square block reads).
22560/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
22561/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
22562/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
22563/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
22564/// a chunk before moving to the next (the interleave lane-sb128b r3
22565/// measured at the 128x128 NONE root).
22566/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
22567/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
22568/// No CfL, no filter intra (both cap at 32x32) and no palette
22569/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
22570/// reader's own size gates already say so, and the guard below is defensive.
22571///
22572/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
22573/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
22574/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
22575/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
22576/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
22577/// units, plane-major inside each 64x64 mu chunk exactly as
22578/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
22579/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
22580/// this lane closed); the geometry and the unit walks below are normalized on
22581/// `lossless_frame`.
22582#[allow(clippy::too_many_arguments)]
22583fn decode_block_128rect(
22584 dec: &mut SymbolDecoder,
22585 cdfs: &mut Cdfs,
22586 neighbours: &mut Neighbours,
22587 at: (usize, usize),
22588 bw: usize,
22589 bh: usize,
22590 y: &mut PlaneBuf<'static>,
22591 u: &mut PlaneBuf<'static>,
22592 v: &mut PlaneBuf<'static>,
22593 base_q_idx: u8,
22594 enable_filter_intra: bool,
22595 allow_screen_content_tools: bool,
22596 tx_select: bool,
22597 reduced_tx_set: bool,
22598 fctx: &crate::decode::FrameCtx,
22599) -> Result<()> {
22600 let (r, c) = at;
22601 let (px, py) = (c * SUB, r * SUB);
22602 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
22603 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22604 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
22605 let palette_uv_cache = neighbours.palette_uv_cache(at);
22606 let (
22607 skip,
22608 mode,
22609 angle_delta_y,
22610 uv_mode,
22611 angle_delta_uv,
22612 alpha,
22613 filter_intra,
22614 palette_y,
22615 palette_uv,
22616 intrabc,
22617 ) = read_intra_mode_rect(
22618 dec,
22619 cdfs,
22620 nb_above_mode,
22621 nb_left_mode,
22622 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
22623 // 13-symbol no-CFL CDF here, never the 14-symbol one.
22624 false,
22625 true,
22626 bw,
22627 bh,
22628 enable_filter_intra,
22629 neighbours.skip_txfm_ctx(mi_r, mi_c),
22630 allow_screen_content_tools,
22631 Some((palette_ctx, &palette_cache)),
22632 &palette_uv_cache,
22633 mi_r,
22634 mi_c,
22635 fctx,
22636 )?;
22637 if let Some((dv_row, dv_col)) = intrabc {
22638 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
22639 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
22640 // from this frame's own reconstruction and runs the INTER residual
22641 // walk (`decode_token_recon_block`'s else arm) over it.
22642 return decode_intrabc_128rect(
22643 dec,
22644 cdfs,
22645 neighbours,
22646 (mi_r, mi_c),
22647 (bw, bh),
22648 skip,
22649 (dv_row, dv_col),
22650 y,
22651 u,
22652 v,
22653 base_q_idx,
22654 fctx,
22655 );
22656 }
22657 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
22658 return Err(unsupported(
22659 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
22660 their size gates caps at 64x64 or below, so none of these symbols exists there)",
22661 ));
22662 }
22663 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22664 DC_PRED
22665 } else {
22666 uv_mode
22667 };
22668 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22669 if smooth_neighbor {
22670 hit!(SMOOTH_LUMA_HITS);
22671 }
22672 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
22673 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
22674 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
22675 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
22676 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
22677 // before the symbol is even considered (`decodeframe.c:141`) and
22678 // `read_tx_size` returns `TX_4X4` before it looks at anything
22679 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
22680 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
22681 let lossless_frame = lossless(fctx);
22682 let in_inter = fctx
22683 .intra_in_inter_mode
22684 .with(std::cell::Cell::get)
22685 .is_some();
22686 let depth = if tx_select && !lossless_frame {
22687 // lane-inter128intra r1: `get_tx_size_context` compares the bands
22688 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
22689 // TX_64X64 for every 128-axis block, hence the `min(64)`.
22690 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
22691 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
22692 } else {
22693 0
22694 };
22695 if depth != 0 {
22696 hit!(TX_DEPTH_HITS);
22697 }
22698 hit_do! {
22699 INTRA_SB128_DEPTH_HITS.with(|c| {
22700 let mut h = c.get();
22701 h[depth.min(2)] += 1;
22702 c.set(h);
22703 });
22704 }
22705 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
22706 if lossless_frame {
22707 hit!(INTRA128_LOSSLESS_HITS);
22708 }
22709 // A 64-point transform codes nothing past its low 32 coefficients.
22710 let coeff_tx_side = logical_tx.min(32);
22711 let luma_set = if lossless_frame {
22712 TxbSet::Luma4
22713 } else {
22714 txbset_for(logical_tx, reduced_tx_set)
22715 };
22716 let luma_scan = default_scan(coeff_tx_side);
22717 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
22718 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
22719 let chroma_tx = if lossless_frame { 4 } else { 32 };
22720 let chroma_set = if lossless_frame {
22721 TxbSet::Chroma4
22722 } else {
22723 TxbSet::Chroma32
22724 };
22725 let chroma_scan = default_scan(chroma_tx);
22726 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22727 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
22728 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
22729 let (nch_x, nch_y) = (bw / 64, bh / 64);
22730 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
22731 // `decode_token_recon_block` clips each vector's walk to
22732 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
22733 // codes nothing.
22734 let mi_cols = 2 * y.true_width.div_ceil(8);
22735 let mi_rows = 2 * y.true_height.div_ceil(8);
22736 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
22737 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
22738 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
22739 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
22740 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
22741 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
22742 debug_assert!(
22743 lossless_frame
22744 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
22745 == (
22746 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
22747 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
22748 )
22749 );
22750 let tpc = 64 / logical_tx;
22751 let zero_tu = vec![0i32; logical_tx * logical_tx];
22752 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
22753 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22754 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
22755 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
22756 // every chunk shares this luma span (2 chroma pixels per luma unit).
22757 let luma_span = chroma_tx << ss_x(fctx);
22758 let luma_span_h = chroma_tx << ss_y(fctx);
22759 for ch_row in 0..nch_y {
22760 for ch_col in 0..nch_x {
22761 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
22762 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
22763 let tu_mi = (
22764 mi_r + tu_row * (logical_tx / MI),
22765 mi_c + tu_col * (logical_tx / MI),
22766 );
22767 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
22768 // libaom clips the transform loop to
22769 // `max_blocks_wide/high`: a unit whose top-left sample is
22770 // outside the frame is never coded.
22771 if tu_px >= y.true_width || tu_py >= y.true_height {
22772 continue;
22773 }
22774 // Edge availability of a unit INSIDE a block, with the
22775 // 128 geometry -- `has_top_right` is false for a block
22776 // whose largest side is > 64, which [`Reach::of_rect`]
22777 // already answered for the block and [`tu_reach`] carries
22778 // down to the units on its own top row.
22779 let tu_r = tu_reach(
22780 bw,
22781 bh,
22782 tu_col * logical_tx,
22783 tu_row * logical_tx,
22784 logical_tx,
22785 reach,
22786 px,
22787 py,
22788 y.width,
22789 y.height,
22790 fctx,
22791 );
22792 if skip {
22793 push_intra(
22794 0,
22795 tu_px,
22796 tu_py,
22797 logical_tx,
22798 mode,
22799 angle_delta_y,
22800 tu_r,
22801 &zero_tu,
22802 None,
22803 None,
22804 smooth_neighbor,
22805 fctx,
22806 );
22807 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
22808 continue;
22809 }
22810 // The unit is smaller than its block, so `txb_skip_ctx`
22811 // is the neighbour-magnitude table, never the lone-TU 0.
22812 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
22813 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
22814 let tu_grid = read_plane(
22815 dec,
22816 cdfs,
22817 luma_set,
22818 &luma_scan,
22819 0,
22820 tu_around,
22821 mode,
22822 mode,
22823 angle_delta_y,
22824 tu_r,
22825 y,
22826 tu_px,
22827 tu_py,
22828 logical_tx,
22829 coeff_tx_side,
22830 base_q_idx,
22831 None,
22832 None,
22833 Some(tu_skip_ctx),
22834 smooth_neighbor,
22835 fctx,
22836 )?;
22837 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
22838 }
22839 }
22840 // Transform units per axis inside this mu chunk's chroma span:
22841 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
22842 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
22843 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
22844 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
22845 // chroma plane block is 32x64 there, so the two axes' counts
22846 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
22847 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
22848 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
22849 // libaom's per-chunk `unit_width/height` (plane-mi units of the
22850 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
22851 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
22852 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
22853 let stepc = (chroma_tx / 4).max(1);
22854 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
22855 // unit of the chunk, then every V unit. At one unit per plane per
22856 // chunk (every non-lossless 128-axis block) that is the same
22857 // symbol order the interleaved pair used to read; a lossless
22858 // frame's 4x4 chroma units are where it becomes observable.
22859 for plane_pass in 1..=2usize {
22860 for ci_row in 0..cn_h {
22861 for ci_col in 0..cn {
22862 // The clamp strides are the CHUNK's chroma mi extent
22863 // per axis: 16 luma mi >> the axis's own ss.
22864 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
22865 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
22866 {
22867 continue;
22868 }
22869 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
22870 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
22871 let cu_mi = (
22872 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
22873 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
22874 );
22875 let cu_r = tu_reach_rect(
22876 bw,
22877 bh,
22878 ch_col * 64 + ci_col * luma_span,
22879 ch_row * 64 + ci_row * luma_span_h,
22880 luma_span,
22881 luma_span_h,
22882 reach,
22883 px,
22884 py,
22885 y.width,
22886 y.height,
22887 fctx,
22888 );
22889 if skip {
22890 push_intra(
22891 plane_pass,
22892 cu_x,
22893 cu_y,
22894 chroma_tx,
22895 uv_predict_mode,
22896 angle_delta_uv,
22897 cu_r,
22898 &zero_cu,
22899 None,
22900 None,
22901 smooth_neighbor_uv,
22902 fctx,
22903 );
22904 continue;
22905 }
22906 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
22907 let buf: &mut PlaneBuf<'static> =
22908 if plane_pass == 1 { &mut *u } else { &mut *v };
22909 let grid = read_plane(
22910 dec,
22911 cdfs,
22912 chroma_set,
22913 &chroma_scan,
22914 plane_pass,
22915 cu_around[plane_pass],
22916 mode,
22917 uv_predict_mode,
22918 angle_delta_uv,
22919 cu_r,
22920 buf,
22921 cu_x,
22922 cu_y,
22923 chroma_tx,
22924 chroma_tx,
22925 base_q_idx,
22926 None,
22927 None,
22928 Some(3),
22929 smooth_neighbor_uv,
22930 fctx,
22931 )?;
22932 last_grids[plane_pass - 1] = grid.clone();
22933 // Immediately, so the NEXT unit of this same block
22934 // reads this one's coefficient context; replayed after
22935 // `record_split_luma_rect` below, which would otherwise
22936 // clobber them whole-block.
22937 neighbours.record_mi_chroma(
22938 cu_mi,
22939 luma_span,
22940 luma_span_h,
22941 plane_pass,
22942 &grid,
22943 );
22944 units.push((plane_pass, cu_mi, grid));
22945 }
22946 }
22947 }
22948 if !skip {
22949 hit!(CHROMA_SPLIT_TX_HITS);
22950 }
22951 }
22952 }
22953 if skip {
22954 neighbours.record_rect(
22955 at,
22956 bw,
22957 bh,
22958 mode,
22959 uv_predict_mode,
22960 &[
22961 &ZERO_RESIDUAL[..bw * bh],
22962 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22963 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22964 ],
22965 );
22966 } else {
22967 neighbours.record_split_luma_rect(
22968 at,
22969 bw,
22970 bh,
22971 mode,
22972 uv_predict_mode,
22973 [&last_grids[0], &last_grids[1]],
22974 );
22975 // lane-av1-128rectspan: the replay must re-stamp each unit over the
22976 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
22977 // height drives `left[]` and its width `above[]`, and the walk used
22978 // the per-axis `luma_span_h`. Passing the width on both axes doubled
22979 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
22980 // rows below the block on the last unit of a 128x64/64x128 strip and
22981 // smearing a neighbour chunk's unit over its neighbour's rows.
22982 //
22983 // DEFENSIVE at the decoder's current capability set: both admitted
22984 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
22985 // (0,0)), so the two spans are equal and this line is a no-op on
22986 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
22987 // format where they differ -- is refused by name at the sequence
22988 // header, so the arm is unreachable there. It stays per-axis because
22989 // the walk it replays is per-axis, and a 4:2:2 port must not have to
22990 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
22991 // day that changes.
22992 if luma_span != luma_span_h {
22993 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
22994 }
22995 for (plane, cu_mi, grid) in &units {
22996 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
22997 hit!(SB128RECT_CHROMA_REPLAY_HITS);
22998 }
22999 }
23000 // No palette exists at this size; the unconditional stamp clears any
23001 // stale neighbour palette state, as every other block path does.
23002 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
23003 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
23004 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
23005 neighbours.fill_lf_grid_rect(
23006 (mi_r, mi_c),
23007 bw / MI,
23008 bh / MI,
23009 logical_tx as u8,
23010 logical_tx as u8,
23011 0,
23012 fctx,
23013 );
23014 if in_inter || allow_intrabc_frame(fctx) {
23015 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
23016 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
23017 // inter frame, intra ones included: an intra block stamps its
23018 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
23019 // A key frame reads those bands only when it allows intrabc
23020 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
23021 // stamps here too -- lane-av1-intrabc r3.
23022 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
23023 }
23024 if in_inter {
23025 hit_do! {
23026 INTRA128_IN_INTER_HITS.with(|c| {
23027 let mut h = c.get();
23028 h[usize::from(bw < bh)] += 1;
23029 c.set(h);
23030 });
23031 }
23032 } else if bw > bh {
23033 hit!(INTRA_SB128_HORZ_HITS);
23034 } else {
23035 hit!(INTRA_SB128_VERT_HITS);
23036 }
23037 Ok(())
23038}
23039
23040/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
23041/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
23042/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
23043/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
23044/// just-decoded mode, not the enclosing slot's stale one, is the true
23045/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
23046/// units, which is what its coefficient context (finer than [`SUB`]) is read
23047/// at. Returns the mode this leaf decoded, for the caller's own
23048/// `prev_leaf`/final mode-writeback bookkeeping.
23049#[allow(clippy::too_many_arguments)]
23050/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
23051/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
23052/// `above_mode[col]`, and its true above neighbour is the mi directly above
23053/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
23054/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
23055/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
23056/// (bottom-right) into both, as this path did, is right only when all four
23057/// leaves happen to share a mode. `done` may be short at the true frame edge
23058/// (the straddle caller filters positions off the frame), so each side falls
23059/// back to the last leaf actually decoded.
23060fn write_back_split_modes(
23061 neighbours: &mut Neighbours,
23062 done: &[((usize, usize), usize)],
23063 parent_mi: (usize, usize),
23064 slot: (usize, usize),
23065) {
23066 let (sr, sc) = slot;
23067 let Some(&(_, last)) = done.last() else {
23068 return;
23069 };
23070 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
23071 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
23072 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
23073}
23074
23075fn decode_leaf8(
23076 dec: &mut SymbolDecoder,
23077 cdfs: &mut Cdfs,
23078 neighbours: &mut Neighbours,
23079 outer_at: (usize, usize),
23080 leaf_mi: (usize, usize),
23081 scans: (&[u16], &[u16]),
23082 prev_leaf: Option<((usize, usize), usize)>,
23083 y: &mut PlaneBuf<'static>,
23084 u: &mut PlaneBuf<'static>,
23085 v: &mut PlaneBuf<'static>,
23086 base_q_idx: u8,
23087 enable_filter_intra: bool,
23088 allow_screen_content_tools: bool,
23089 allow_intrabc: bool,
23090 tx_select: bool,
23091 reduced_tx_set: bool,
23092 fctx: &crate::decode::FrameCtx,
23093) -> Result<usize> {
23094 let (r, c) = outer_at;
23095 // lane-modectx r1: the group's own availability-correct fallback pair, not
23096 // the raw coarse bands (which leak across a tile edge -- see
23097 // `modes_above_left`).
23098 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
23099 if let Some(((pr, pc), pmode)) = prev_leaf {
23100 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
23101 above_mode = pmode;
23102 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
23103 left_mode = pmode;
23104 }
23105 }
23106 // The mi-exact neighbour wins over both the coarse 16x16 slot and
23107 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
23108 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
23109 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
23110 // lane-rectsplitx r2 swept this arm into
23111 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
23112 // "no neighbour" at a tile edge, where the coarse cell holds the block
23113 // above/left of it inside the same 16x16.
23114 let (above_mode, left_mode) =
23115 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
23116 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
23117 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
23118 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
23119 // this leaf's `smooth_neighbor` is built from -- passing `false` here
23120 // filtered a directional chroma block's edge at the wrong strength
23121 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
23122 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
23123 // with the coarse [`SUB`] slot as the fallback when no block recorded
23124 // that exact mi cell.
23125 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
23126 if smooth_neighbor {
23127 hit!(SMOOTH_LUMA_HITS);
23128 }
23129 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
23130 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
23131 // `decode_block` caller at 16x16 and up.
23132 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
23133 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
23134 // `read_palette_mode_info`), at its REAL mi position -- passing
23135 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
23136 // moment a real 8x8 palette block fired, which is where every 8-bit
23137 // `--tune-content=screen --min-partition-size=8` stream stopped.
23138 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
23139 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
23140 let (
23141 skip,
23142 mode,
23143 angle_delta_y,
23144 uv_mode,
23145 angle_delta_uv,
23146 alpha,
23147 filter_intra,
23148 palette_y,
23149 palette_uv,
23150 ) = read_intra_mode(
23151 dec,
23152 cdfs,
23153 above_mode,
23154 left_mode,
23155 true,
23156 8,
23157 enable_filter_intra,
23158 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
23159 allow_screen_content_tools,
23160 allow_intrabc,
23161 Some((palette_ctx, &palette_cache)),
23162 &palette_uv_cache,
23163 leaf_mi.0,
23164 leaf_mi.1,
23165 fctx,
23166 )?;
23167 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
23168 // `read_intra_mode` and then decoded the block as if it were ordinary
23169 // intra. libaom's `is_inter_block` counts an intrabc block
23170 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
23171 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
23172 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
23173 // same value with a different interval, so the tile desynced at the very
23174 // next symbol (class `wrong-alphabet-same-value`). Everything below
23175 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
23176 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
23177 if intrabc_dv.is_some() {
23178 hit!(LEAF8_INTRABC_HITS);
23179 }
23180 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
23181 // index map, mapped through the base colours, IS the block's prediction --
23182 // carried to the next `reconstruct`/`read_plane` through the same
23183 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
23184 let palette_y_buf: Option<Vec<u16>> = palette_y
23185 .as_ref()
23186 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
23187 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
23188 (
23189 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
23190 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
23191 )
23192 });
23193 let (pal_y_size, pal_y_colors) = palette_y
23194 .as_ref()
23195 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
23196 let (pal_uv_size, pal_uv_colors) = palette_uv
23197 .as_ref()
23198 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
23199 if palette_y.is_some() || palette_uv.is_some() {
23200 hit!(PALETTE_LEAF8_HITS);
23201 }
23202 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23203 DC_PRED
23204 } else {
23205 uv_mode
23206 };
23207 neighbours.above_uv_mode[c] = uv_predict_mode;
23208 neighbours.left_uv_mode[r] = uv_predict_mode;
23209 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
23210 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
23211 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
23212 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
23213 // transform units, same raster-order per-TU pattern `decode_block`'s
23214 // multi-TU branch runs).
23215 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
23216 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
23217 // intrabc block, so a SKIPPED one takes the largest transform and an
23218 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
23219 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
23220 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
23221 // `parse_decode_block`'s tree condition carries
23222 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
23223 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
23224 // `read_tx_size`'s first line (lane-av1mixloss).
23225 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
23226 let mut leaves = Vec::new();
23227 let mi_cols = 2 * y.true_width.div_ceil(8);
23228 let mi_rows = 2 * y.true_height.div_ceil(8);
23229 read_var_tx_size(
23230 dec,
23231 cdfs,
23232 neighbours,
23233 leaf_mi,
23234 8,
23235 (
23236 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
23237 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
23238 ),
23239 (8, 8),
23240 0,
23241 0,
23242 0,
23243 &mut leaves,
23244 );
23245 hit!(INTRABC_VARTX_HITS);
23246 leaves.first().map_or(8, |l| l.2)
23247 } else if tx_select && intrabc_dv.is_none() {
23248 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
23249 } else {
23250 // lane-lossless: TX_4X4 on a lossless frame, no symbol
23251 // (libaom `read_tx_size`).
23252 lossless_tx(8, fctx)
23253 };
23254 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
23255 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
23256 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
23257 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
23258 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
23259 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
23260 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
23261 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
23262 // TX_4X8): one txb_skip + one scan per plane in the
23263 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
23264 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
23265 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
23266 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
23267 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
23268 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
23269 let (csz, cset, cscan) = if chroma_444 {
23270 (8usize, TxbSet::Chroma8, scans.0)
23271 } else {
23272 (4usize, TxbSet::Chroma4, scans.1)
23273 };
23274 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
23275 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
23276 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
23277 // the full-pel block vector, with the BILINEAR kernel libaom forces.
23278 flush_recon(fctx, y, u, v);
23279 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
23280 let mut yb = vec![0u16; 8 * 8];
23281 mc::predict_with_filter(
23282 &y.data,
23283 y.width,
23284 y.true_width,
23285 y.true_height,
23286 mv_to_q4(px, dv_col, 0),
23287 mv_to_q4(py, dv_row, 0),
23288 8,
23289 8,
23290 mc::InterpFilterKind::Bilinear,
23291 &mut yb,
23292 fctx,
23293 );
23294 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
23295 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
23296 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
23297 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
23298 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
23299 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
23300 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
23301 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
23302 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
23303 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
23304 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
23305 // so all three heal with this one sizing.
23306 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
23307 let mut ub = vec![0u16; cw * ch];
23308 mc::predict_with_filter(
23309 &u.data,
23310 u.width,
23311 u.true_width,
23312 u.true_height,
23313 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23314 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23315 cw,
23316 ch,
23317 mc::InterpFilterKind::Bilinear,
23318 &mut ub,
23319 fctx,
23320 );
23321 let mut vb = vec![0u16; cw * ch];
23322 mc::predict_with_filter(
23323 &v.data,
23324 v.width,
23325 v.true_width,
23326 v.true_height,
23327 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23328 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23329 cw,
23330 ch,
23331 mc::InterpFilterKind::Bilinear,
23332 &mut vb,
23333 fctx,
23334 );
23335 (yb, ub, vb)
23336 });
23337 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
23338 // `decode_block` uses: set fresh right before each plane's own
23339 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
23340 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
23341 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
23342 // first shape that reaches that loop with an override set).
23343 let palette_y_buf = match &intrabc_bufs {
23344 Some((yb, _, _)) => Some(yb.clone()),
23345 None => palette_y_buf,
23346 };
23347 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
23348 // `decode_block` does the same for its own `palette_uv_bufs`
23349 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
23350 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
23351 // chroma reads with the override unset: the unit predicted INTRA from
23352 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
23353 // R5 first differing pixel U(184,4), block mi (2,92).
23354 let palette_uv_bufs = match &intrabc_bufs {
23355 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
23356 None => palette_uv_bufs,
23357 };
23358 let (luma_grid, u_grid, v_grid);
23359 if skip {
23360 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
23361 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
23362 // transform units, each off the units already written left/above of
23363 // it inside this same leaf -- an intra block's transform size is read
23364 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
23365 // A palette block's prediction is the whole-block index map, never
23366 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
23367 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
23368 // even when `tx_depth` resolved to TX_4X4.
23369 if resolved == 4 && palette_y_buf.is_none() {
23370 hit!(SKIP_SPLIT_TX_HITS);
23371 for tu_row in 0..2 {
23372 for tu_col in 0..2 {
23373 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
23374 if tu_px >= y.true_width || tu_py >= y.true_height {
23375 continue;
23376 }
23377 let tu_reach = tu_reach(
23378 8,
23379 8,
23380 tu_col * 4,
23381 tu_row * 4,
23382 4,
23383 reach,
23384 px,
23385 py,
23386 y.width,
23387 y.height,
23388 fctx,
23389 );
23390 push_intra(
23391 0,
23392 tu_px,
23393 tu_py,
23394 4,
23395 mode,
23396 angle_delta_y,
23397 tu_reach,
23398 &ZERO_RESIDUAL[..16],
23399 None,
23400 filter_intra,
23401 smooth_neighbor,
23402 fctx,
23403 );
23404 }
23405 }
23406 } else {
23407 if let Some(buf) = &palette_y_buf {
23408 set_palette_pred(buf.clone(), fctx);
23409 }
23410 push_intra(
23411 0,
23412 px,
23413 py,
23414 8,
23415 mode,
23416 angle_delta_y,
23417 reach,
23418 &ZERO_RESIDUAL[..64],
23419 None,
23420 filter_intra,
23421 smooth_neighbor,
23422 fctx,
23423 );
23424 }
23425 let ac = alpha.map(|_| cfl_src(px, py, 8));
23426 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
23427 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
23428 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
23429 // skip-arm rule); no coefficient symbol exists, so the entropy
23430 // context never enters the rect read.
23431 if chroma_422 {
23432 u_grid = leaf8_chroma422_unit(
23433 dec,
23434 cdfs,
23435 (false, false, 0),
23436 uv_predict_mode,
23437 angle_delta_uv,
23438 reach,
23439 1,
23440 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23441 true,
23442 intrabc_bufs
23443 .as_ref()
23444 .map(|(_, ub, _)| ub.clone())
23445 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23446 u,
23447 cpx,
23448 cpy,
23449 smooth_neighbor_uv,
23450 fctx,
23451 )?;
23452 v_grid = leaf8_chroma422_unit(
23453 dec,
23454 cdfs,
23455 (false, false, 0),
23456 uv_predict_mode,
23457 angle_delta_uv,
23458 reach,
23459 2,
23460 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23461 true,
23462 intrabc_bufs
23463 .as_ref()
23464 .map(|(_, _, vb)| vb.clone())
23465 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23466 v,
23467 cpx,
23468 cpy,
23469 smooth_neighbor_uv,
23470 fctx,
23471 )?;
23472 luma_grid = Grid::Zero(64);
23473 } else {
23474 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
23475 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
23476 // plane), so a skipped leaf predicts per unit -- each from its own
23477 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
23478 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
23479 // chroma plane block is 8x8), and intrabc/palette keep the
23480 // whole-plane-block prediction they already run. The guard also
23481 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
23482 let chroma_units_444 =
23483 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
23484 if let Some((_, ub, _)) = &intrabc_bufs {
23485 set_palette_pred(ub.clone(), fctx);
23486 } else if let Some((ub, _)) = &palette_uv_bufs {
23487 set_palette_pred(ub.clone(), fctx);
23488 }
23489 if chroma_units_444 {
23490 for cu_row in 0..2 {
23491 for cu_col in 0..2 {
23492 let cu_reach = tu_reach(
23493 8,
23494 8,
23495 cu_col * 4,
23496 cu_row * 4,
23497 4,
23498 reach,
23499 px,
23500 py,
23501 y.width,
23502 y.height,
23503 fctx,
23504 );
23505 push_intra(
23506 1,
23507 cpx + cu_col * 4,
23508 cpy + cu_row * 4,
23509 4,
23510 uv_predict_mode,
23511 angle_delta_uv,
23512 cu_reach,
23513 &ZERO_RESIDUAL[..16],
23514 None,
23515 None,
23516 smooth_neighbor_uv,
23517 fctx,
23518 );
23519 }
23520 }
23521 } else {
23522 push_intra(
23523 1,
23524 cpx,
23525 cpy,
23526 csz,
23527 uv_predict_mode,
23528 angle_delta_uv,
23529 reach,
23530 &ZERO_RESIDUAL[..csz * csz],
23531 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23532 None,
23533 smooth_neighbor_uv,
23534 fctx,
23535 );
23536 }
23537 if let Some((_, _, vb)) = &intrabc_bufs {
23538 set_palette_pred(vb.clone(), fctx);
23539 } else if let Some((_, vb)) = &palette_uv_bufs {
23540 set_palette_pred(vb.clone(), fctx);
23541 }
23542 if chroma_units_444 {
23543 for cu_row in 0..2 {
23544 for cu_col in 0..2 {
23545 let cu_reach = tu_reach(
23546 8,
23547 8,
23548 cu_col * 4,
23549 cu_row * 4,
23550 4,
23551 reach,
23552 px,
23553 py,
23554 y.width,
23555 y.height,
23556 fctx,
23557 );
23558 push_intra(
23559 2,
23560 cpx + cu_col * 4,
23561 cpy + cu_row * 4,
23562 4,
23563 uv_predict_mode,
23564 angle_delta_uv,
23565 cu_reach,
23566 &ZERO_RESIDUAL[..16],
23567 None,
23568 None,
23569 smooth_neighbor_uv,
23570 fctx,
23571 );
23572 }
23573 }
23574 } else {
23575 push_intra(
23576 2,
23577 cpx,
23578 cpy,
23579 csz,
23580 uv_predict_mode,
23581 angle_delta_uv,
23582 reach,
23583 &ZERO_RESIDUAL[..csz * csz],
23584 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23585 None,
23586 smooth_neighbor_uv,
23587 fctx,
23588 );
23589 }
23590 luma_grid = Grid::Zero(64);
23591 u_grid = Grid::Zero(csz * csz);
23592 v_grid = Grid::Zero(csz * csz);
23593 }
23594 } else if resolved != 4 {
23595 let around = neighbours.around_mi(leaf_mi, 8);
23596 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
23597 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
23598 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
23599 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
23600 // the doubled sum crosses zero (the same class
23601 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
23602 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
23603 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
23604 let chroma_around = if chroma_422 {
23605 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23606 } else {
23607 around
23608 };
23609 if let Some(buf) = &palette_y_buf {
23610 set_palette_pred(buf.clone(), fctx);
23611 }
23612 luma_grid = read_plane(
23613 dec,
23614 cdfs,
23615 if intrabc_dv.is_some() {
23616 inter_txbset_for(8, reduced_tx_set)
23617 } else if reduced_tx_set {
23618 TxbSet::Luma8
23619 } else {
23620 TxbSet::Luma8Set1
23621 },
23622 scans.0,
23623 0,
23624 around[0],
23625 mode,
23626 mode,
23627 angle_delta_y,
23628 reach,
23629 y,
23630 px,
23631 py,
23632 8,
23633 TX8,
23634 base_q_idx,
23635 None,
23636 filter_intra,
23637 None,
23638 smooth_neighbor,
23639 fctx,
23640 )?;
23641 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
23642 // an intrabc block's chroma tx_type is the colocated LUMA transform's
23643 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
23644 if intrabc_dv.is_some() {
23645 fctx.intrabc_chroma_tx
23646 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
23647 }
23648 let ac = alpha.map(|_| cfl_src(px, py, 8));
23649 if chroma_422 {
23650 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
23651 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
23652 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
23653 u_grid = leaf8_chroma422_unit(
23654 dec,
23655 cdfs,
23656 chroma_around[1],
23657 uv_predict_mode,
23658 angle_delta_uv,
23659 reach,
23660 1,
23661 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23662 false,
23663 intrabc_bufs
23664 .as_ref()
23665 .map(|(_, ub, _)| ub.clone())
23666 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23667 u,
23668 cpx,
23669 cpy,
23670 smooth_neighbor_uv,
23671 fctx,
23672 )?;
23673 v_grid = leaf8_chroma422_unit(
23674 dec,
23675 cdfs,
23676 chroma_around[2],
23677 uv_predict_mode,
23678 angle_delta_uv,
23679 reach,
23680 2,
23681 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23682 false,
23683 intrabc_bufs
23684 .as_ref()
23685 .map(|(_, _, vb)| vb.clone())
23686 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23687 v,
23688 cpx,
23689 cpy,
23690 smooth_neighbor_uv,
23691 fctx,
23692 )?;
23693 } else {
23694 if let Some((_, ub, _)) = &intrabc_bufs {
23695 set_palette_pred(ub.clone(), fctx);
23696 } else if let Some((ub, _)) = &palette_uv_bufs {
23697 set_palette_pred(ub.clone(), fctx);
23698 }
23699 u_grid = read_plane(
23700 dec,
23701 cdfs,
23702 cset,
23703 cscan,
23704 1,
23705 around[1],
23706 mode,
23707 uv_predict_mode,
23708 angle_delta_uv,
23709 reach,
23710 u,
23711 cpx,
23712 cpy,
23713 csz,
23714 csz,
23715 base_q_idx,
23716 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23717 None,
23718 None,
23719 smooth_neighbor_uv,
23720 fctx,
23721 )?;
23722 if let Some((_, _, vb)) = &intrabc_bufs {
23723 set_palette_pred(vb.clone(), fctx);
23724 } else if let Some((_, vb)) = &palette_uv_bufs {
23725 set_palette_pred(vb.clone(), fctx);
23726 }
23727 v_grid = read_plane(
23728 dec,
23729 cdfs,
23730 cset,
23731 cscan,
23732 2,
23733 around[2],
23734 mode,
23735 uv_predict_mode,
23736 angle_delta_uv,
23737 reach,
23738 v,
23739 cpx,
23740 cpy,
23741 csz,
23742 csz,
23743 base_q_idx,
23744 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23745 None,
23746 None,
23747 smooth_neighbor_uv,
23748 fctx,
23749 )?;
23750 }
23751 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
23752 // two chroma reads (`decode_block`'s own tail does the same) -- left
23753 // set, every later chroma block would inherit this luma tx_type,
23754 // which picks the scan and the inverse transform.
23755 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23756 } else {
23757 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
23758 // grid of 4x4 transform units, each predicted from the leaf's own
23759 // 8x8 `mode` and reading its own fresh context off the earlier
23760 // units in this same leaf (the same per-TU pattern `decode_block`'s
23761 // multi-TU branch runs at bigger blocks).
23762 let mut first_leaf_tx: Option<TxType> = None;
23763 for tu_row in 0..2 {
23764 for tu_col in 0..2 {
23765 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
23766 let tu_px = px + tu_col * 4;
23767 let tu_py = py + tu_row * 4;
23768 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
23769 if crate::encode::Reach::in_vert_ab() {
23770 hit!(VERT_AB_TX4_HITS);
23771 }
23772 let tu_reach = tu_reach(
23773 8,
23774 8,
23775 tu_col * 4,
23776 tu_row * 4,
23777 4,
23778 reach,
23779 px,
23780 py,
23781 y.width,
23782 y.height,
23783 fctx,
23784 );
23785 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
23786 // Each 4x4 unit predicts from its own window of the block's
23787 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
23788 // 16x16 and up) -- the whole-block buffer would be taken by
23789 // the FIRST unit and indexed at the wrong stride.
23790 if let Some(buf) = &palette_y_buf {
23791 hit!(PALETTE_SPLIT_TX_HITS);
23792 let mut window = vec![0u16; 16];
23793 for row in 0..4 {
23794 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
23795 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
23796 }
23797 set_palette_pred(window, fctx);
23798 }
23799 let tu_grid = read_plane(
23800 dec,
23801 cdfs,
23802 if intrabc_dv.is_some() {
23803 inter_txbset_for(4, reduced_tx_set)
23804 } else if reduced_tx_set {
23805 TxbSet::Luma4
23806 } else {
23807 TxbSet::Luma4Set1
23808 },
23809 scans.1,
23810 0,
23811 tu_around,
23812 mode,
23813 mode,
23814 angle_delta_y,
23815 tu_reach,
23816 y,
23817 tu_px,
23818 tu_py,
23819 4,
23820 4,
23821 base_q_idx,
23822 None,
23823 filter_intra,
23824 Some(tu_skip_ctx),
23825 smooth_neighbor,
23826 fctx,
23827 )?;
23828 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23829 eprintln!(
23830 "TRACE tu_bitpos mi=({},{}) tell={}",
23831 tu_mi.0,
23832 tu_mi.1,
23833 dec.debug_bitpos()
23834 );
23835 }
23836 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
23837 // The FIRST (top-left, co-located with this group's chroma)
23838 // TU's coded tx_type is what the group's chroma inherits --
23839 // the same capture [`decode_block`]'s multi-TU branch makes
23840 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
23841 // an inter-classified block's `PLANE_TYPE_UV` reads
23842 // `tx_type_map`, and intrabc is inter-classified).
23843 if first_leaf_tx.is_none() {
23844 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
23845 }
23846 }
23847 }
23848 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
23849 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
23850 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
23851 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
23852 // the inherited luma type's (R5's first fork: mi (36,66), luma
23853 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
23854 // decoded its `eob` from the wrong CDF row). Same arm the
23855 // `resolved != 4` branch above runs for its whole-leaf unit.
23856 if intrabc_dv.is_some() {
23857 if let Some(t) = first_leaf_tx {
23858 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
23859 }
23860 }
23861 let ac = alpha.map(|_| cfl_src(px, py, 8));
23862 // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm
23863 // above -- the doubled above sum crosses zero at mi(2,24) plane 2.
23864 let chroma_around = if chroma_422 {
23865 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23866 } else {
23867 neighbours.around_mi(leaf_mi, 8)
23868 };
23869 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
23870 // by this arm's chroma reads means the frame-copy + inherited-type
23871 // route ran; zero at gate time means the fixture stopped reaching it.
23872 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
23873 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
23874 }
23875 if chroma_422 {
23876 // lane-av1-422d: the chroma unit does NOT follow the luma var-tx
23877 // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block,
23878 // still the one 4x8 rect unit per plane at ss (1,0).
23879 u_grid = leaf8_chroma422_unit(
23880 dec,
23881 cdfs,
23882 chroma_around[1],
23883 uv_predict_mode,
23884 angle_delta_uv,
23885 reach,
23886 1,
23887 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23888 false,
23889 intrabc_bufs
23890 .as_ref()
23891 .map(|(_, ub, _)| ub.clone())
23892 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23893 u,
23894 cpx,
23895 cpy,
23896 smooth_neighbor_uv,
23897 fctx,
23898 )?;
23899 v_grid = leaf8_chroma422_unit(
23900 dec,
23901 cdfs,
23902 chroma_around[2],
23903 uv_predict_mode,
23904 angle_delta_uv,
23905 reach,
23906 2,
23907 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23908 false,
23909 intrabc_bufs
23910 .as_ref()
23911 .map(|(_, _, vb)| vb.clone())
23912 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23913 v,
23914 cpx,
23915 cpy,
23916 smooth_neighbor_uv,
23917 fctx,
23918 )?;
23919 } else if chroma_444 && lossless(fctx) {
23920 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
23921 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
23922 // lossless forces TX_4X4 on EVERY plane) -- the same walk
23923 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
23924 // TX_8X8 unit here panicked before: the lossless inverse is the
23925 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
23926 // invariant), and the unit count desyncs the tile either way.
23927 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
23928 // inside, which is why the tail's whole-leaf chroma stamp below
23929 // is skipped for this shape.
23930 let (mut uo, mut vo) = (Vec::new(), Vec::new());
23931 read_intra_chroma_lossless(
23932 dec,
23933 cdfs,
23934 neighbours,
23935 u,
23936 v,
23937 leaf_mi,
23938 (px, py),
23939 (cpx, cpy),
23940 8,
23941 (8, 8),
23942 (0, 0),
23943 (8, 8),
23944 8,
23945 reach,
23946 (y.width, y.height),
23947 mode,
23948 uv_predict_mode,
23949 angle_delta_uv,
23950 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
23951 smooth_neighbor_uv,
23952 base_q_idx,
23953 &mut uo,
23954 &mut vo,
23955 fctx,
23956 )?;
23957 u_grid = if uo.is_empty() {
23958 Grid::Zero(64)
23959 } else {
23960 Grid::Own(uo)
23961 };
23962 v_grid = if vo.is_empty() {
23963 Grid::Zero(64)
23964 } else {
23965 Grid::Own(vo)
23966 };
23967 } else {
23968 if let Some((ub, _)) = &palette_uv_bufs {
23969 set_palette_pred(ub.clone(), fctx);
23970 }
23971 u_grid = read_plane(
23972 dec,
23973 cdfs,
23974 cset,
23975 cscan,
23976 1,
23977 chroma_around[1],
23978 mode,
23979 uv_predict_mode,
23980 angle_delta_uv,
23981 reach,
23982 u,
23983 cpx,
23984 cpy,
23985 csz,
23986 csz,
23987 base_q_idx,
23988 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23989 None,
23990 None,
23991 smooth_neighbor_uv,
23992 fctx,
23993 )?;
23994 if let Some((_, vb)) = &palette_uv_bufs {
23995 set_palette_pred(vb.clone(), fctx);
23996 }
23997 v_grid = read_plane(
23998 dec,
23999 cdfs,
24000 cset,
24001 cscan,
24002 2,
24003 chroma_around[2],
24004 mode,
24005 uv_predict_mode,
24006 angle_delta_uv,
24007 reach,
24008 v,
24009 cpx,
24010 cpy,
24011 csz,
24012 csz,
24013 base_q_idx,
24014 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24015 None,
24016 None,
24017 smooth_neighbor_uv,
24018 fctx,
24019 )?;
24020 }
24021 // The two chroma reads above are the only consulters of this leaf's
24022 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
24023 // leaf's chroma inherit this leaf's luma type instead of its own
24024 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
24025 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
24026 // luma's `V_ADST` for its chroma eob row).
24027 if intrabc_dv.is_some() {
24028 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24029 }
24030 // `record_split_luma` expects a `record`-style `(r, c)` position in
24031 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
24032 // already in mi units, so calling it here double-scaled the
24033 // position. Plane 0 is already correct per-TU from the
24034 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
24035 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
24036 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
24037 // leaf's own 8x8 side over `MI`).
24038 let side_mi = 2;
24039 for cell in 0..side_mi {
24040 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
24041 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
24042 }
24043 let round_up_even = |n: usize| n.div_ceil(2) * 2;
24044 let bound_h = round_up_even(neighbours.mi_rows);
24045 let bound_w = round_up_even(neighbours.mi_cols);
24046 let u_state = neighbour_state(&u_grid);
24047 let v_state = neighbour_state(&v_grid);
24048 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
24049 // (its raster-order last writer per cell is exactly libaom's
24050 // per-entry last update); this whole-leaf aggregate would clobber
24051 // four distinct unit states with one, so it runs only for the shapes
24052 // whose chroma really is one unit.
24053 if !(chroma_444 && lossless(fctx)) {
24054 for cell in 0..side_mi {
24055 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
24056 neighbours.left[leaf_mi.0 + cell][1] = u_state;
24057 neighbours.left[leaf_mi.0 + cell][2] = v_state;
24058 }
24059 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
24060 neighbours.above[leaf_mi.1 + cell][1] = u_state;
24061 neighbours.above[leaf_mi.1 + cell][2] = v_state;
24062 }
24063 }
24064 }
24065 // This leaf's own palette state into the mi-granular above/left bands
24066 // (sizes 0 when it used none, which is what clears a previous block's
24067 // palette out of the next block's ctx and colour cache).
24068 {
24069 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
24070 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
24071 }
24072 neighbours.fill_skip_grid(leaf_mi, 2, skip);
24073 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
24074 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
24075 // own copy; only an intrabc var-tx read consumes these bands on the intra
24076 // path, so the write is armed by `allow_intrabc`.
24077 if allow_intrabc {
24078 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
24079 }
24080 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
24081 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
24082 return Ok(mode);
24083 }
24084 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
24085 // This leaf's own palette state into the mi-granular above/left bands
24086 // (sizes 0 when it used none, which is what clears a previous block's
24087 // palette out of the next block's ctx and colour cache).
24088 {
24089 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
24090 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
24091 }
24092 hit!(INTER8_SKIP_BAND_HITS);
24093 neighbours.fill_skip_grid(leaf_mi, 2, skip);
24094 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
24095 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
24096 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
24097 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
24098 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
24099 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
24100 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
24101 // wrong CDF row, so the msac range diverged mid-frame with no refusal
24102 // (class `wrong-alphabet-same-value`; the ReelB key frame at
24103 // -ss 900, first bad luma sample row 186 col 1803).
24104 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
24105 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
24106 // `decode_block`'s own copy for why this stays beside
24107 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
24108 // BLOCK-size term).
24109 if allow_intrabc {
24110 set_txfm_ctxs(
24111 neighbours,
24112 leaf_mi,
24113 resolved,
24114 2,
24115 2,
24116 skip && intrabc_dv.is_some(),
24117 );
24118 }
24119 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
24120 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
24121 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
24122 // publish its own cells exactly like `decode_block` does.
24123 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
24124 Ok(mode)
24125}
24126
24127/// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf
24128/// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and
24129/// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to
24130/// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is
24131/// a single rect unit -- one txb_skip + one scan per plane in the
24132/// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
24133/// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved
24134/// position: the entropy context is the leaf's own 8x8 luma-span
24135/// above/left state (the `chroma_tiled` arm's convention; no `+3`
24136/// plane-block-bigger term -- the unit covers the plane block exactly), the
24137/// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted
24138/// mode supplies the mode-derived default `tx_type` unless an armed
24139/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller
24140/// arms and disarms it, exactly as it does around its square reads).
24141#[allow(clippy::too_many_arguments)]
24142fn leaf8_chroma422_unit(
24143 dec: &mut SymbolDecoder,
24144 cdfs: &mut Cdfs,
24145 around: (bool, bool, i32),
24146 uv_predict_mode: usize,
24147 angle_delta_uv: i32,
24148 reach: Reach,
24149 plane_idx: usize,
24150 cfl: Option<(i32, CflSrc)>,
24151 skip: bool,
24152 // The prediction override the square arms feed through
24153 // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes
24154 // priority over a palette block's colour-index map.
24155 pred_override: Option<Vec<u16>>,
24156 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
24157 // the plane exclusively while the unit's coefficients are parsed.
24158 _plane: &mut PlaneBuf<'static>,
24159 cpx: usize,
24160 cpy: usize,
24161 smooth_neighbor_uv: bool,
24162 fctx: &crate::decode::FrameCtx,
24163) -> Result<Grid> {
24164 // The unit's prediction runs whether or not a residual follows it -- a
24165 // skipped leaf still predicts (the CfL contribution survives a skip),
24166 // and a skipped intrabc leaf still copies the frame at its DV.
24167 if let Some(buf) = pred_override {
24168 set_palette_pred(buf, fctx);
24169 }
24170 if skip {
24171 push_intra_rect(
24172 plane_idx,
24173 cpx,
24174 cpy,
24175 4,
24176 8,
24177 uv_predict_mode,
24178 angle_delta_uv,
24179 reach,
24180 &ZERO_RESIDUAL[..4 * 8],
24181 cfl,
24182 None,
24183 smooth_neighbor_uv,
24184 fctx,
24185 );
24186 return Ok(Grid::Zero(4 * 8));
24187 }
24188 let default_tx = fctx
24189 .intrabc_chroma_tx
24190 .with(std::cell::Cell::get)
24191 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8));
24192 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
24193 let (levels, tx_type) = read_coeffs_rect(
24194 dec,
24195 &mut coding,
24196 &SCAN_4X8,
24197 4,
24198 8,
24199 usize::from(around.0) + usize::from(around.1),
24200 dc_sign_ctx(around.2),
24201 default_tx,
24202 plane_idx,
24203 )?;
24204 let residual = dequant_and_inverse_typed_wh(
24205 &levels,
24206 4,
24207 8,
24208 crate::decode::bit_depth(fctx),
24209 block_q_idx(fctx),
24210 plane_q_delta(plane_idx, fctx).0,
24211 plane_q_delta(plane_idx, fctx).1,
24212 tx_type,
24213 block_iqmatrix(fctx, plane_idx, 4, 8, tx_type),
24214 );
24215 push_intra_rect(
24216 plane_idx,
24217 cpx,
24218 cpy,
24219 4,
24220 8,
24221 uv_predict_mode,
24222 angle_delta_uv,
24223 reach,
24224 &residual,
24225 cfl,
24226 None,
24227 smooth_neighbor_uv,
24228 fctx,
24229 );
24230 Ok(levels)
24231}
24232
24233/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
24234/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
24235/// bottom, where no partition symbol is read at all -- `decode_block` runs
24236/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
24237/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
24238/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
24239/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
24240/// of the 2x2 4x4 group carries chroma syntax at all.
24241#[allow(clippy::too_many_arguments)]
24242fn read_intra_mode_sub8(
24243 dec: &mut SymbolDecoder,
24244 cdfs: &mut Cdfs,
24245 above_mode: usize,
24246 left_mode: usize,
24247 has_chroma: bool,
24248 enable_filter_intra: bool,
24249 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
24250 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
24251 // from the wrong row is the same VALUE with a different interval, so it
24252 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
24253 fi_class: usize,
24254 skip_ctx: usize,
24255 allow_intrabc: bool,
24256 mi_r: usize,
24257 mi_c: usize,
24258 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
24259 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
24260 // left the second mi column at segment 0, which reads back as a
24261 // neighbour's `cdf_index`/prediction two blocks later.
24262 seg_w_mi: usize,
24263 seg_h_mi: usize,
24264 fctx: &crate::decode::FrameCtx,
24265) -> Result<(
24266 bool,
24267 usize,
24268 i32,
24269 Option<(usize, i32, Option<(i32, i32)>)>,
24270 Option<usize>,
24271 Option<(i32, i32)>,
24272)> {
24273 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
24274 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
24275 let has_chroma = has_chroma && !mono(fctx);
24276 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
24277 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
24278 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
24279 if ec_istep {
24280 eprintln!(
24281 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}",
24282 dec.debug_state().0
24283 );
24284 }
24285 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
24286 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
24287 macro_rules! istep {
24288 ($name:literal, $val:expr) => {
24289 if ec_istep {
24290 eprintln!(
24291 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}",
24292 $name,
24293 $val,
24294 dec.debug_state().0
24295 );
24296 }
24297 };
24298 }
24299 // lane-seg2: same `intra_segment_id` placement as the square and rect
24300 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
24301 // like any other block, over its own 1x1 mi footprint. Dropping it here
24302 // both ate a symbol (the tile desynced at the frame's first sub-8x8
24303 // split) and left `cur_segment_id` on the previous block, so the leaf
24304 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
24305 if seg_id_pre_skip(fctx) {
24306 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
24307 }
24308 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
24309 if trace {
24310 eprintln!(
24311 "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}",
24312 skip as i32,
24313 dec.debug_state().0
24314 );
24315 }
24316 istep!("skip", skip as i32);
24317 if !seg_id_pre_skip(fctx) {
24318 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
24319 }
24320 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
24321 istep!("cdef", 0);
24322 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
24323 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
24324 istep!("dq", 0);
24325 if allow_intrabc {
24326 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
24327 if ec_istep {
24328 eprintln!(
24329 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
24330 u8::from(use_intrabc),
24331 dec.debug_state().0
24332 );
24333 }
24334 if use_intrabc {
24335 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
24336 // vector right after the flag and RETURNS -- no y/uv mode, angle
24337 // delta, palette, CfL or filter-intra syntax follows, and the
24338 // block is reconstructed by the INTER path (libaom's
24339 // `is_inter_block` counts an intrabc block), so the caller takes
24340 // the frame-copy prediction + inter residual.
24341 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
24342 // lane-av1txr: the DV travels back in the RETURN value -- it is
24343 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
24344 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
24345 // then

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