forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbede77eTahinli2 months ago3534 commits

decode.rs24435 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}
4712
4713/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4714/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4715#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4716pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4717 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4718}
4719
4720/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4721/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4722#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4723pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4724 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4725}
4726
4727/// Current value of [`INTRABC_RECT_HITS`].
4728#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4729pub fn intrabc_rect_hits() -> usize {
4730 INTRABC_RECT_HITS.with(|c| c.get())
4731}
4732
4733/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4734#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4735pub(crate) fn reset_intrabc_rect_hits() {
4736 INTRABC_RECT_HITS.with(|c| c.set(0));
4737 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4738 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4739 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4740}
4741
4742/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4743#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4744pub fn ibc_rect_chroma_footprint_444_hits() -> usize {
4745 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4746}
4747
4748/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4749#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4750pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() {
4751 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4752}
4753
4754/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4755#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4756pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
4757 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
4758}
4759
4760/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4761#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4762pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
4763 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
4764}
4765
4766/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4767#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4768pub fn intrabc_rect_vartx_hits() -> usize {
4769 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4770}
4771
4772thread_local! {
4773 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4774 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4775 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4776 /// guard (`decode_block_128rect`). A refused block bumps
4777 /// [`INTRABC_HITS`] but never this one.
4778 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4779 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4780 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4781 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4782 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4783 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4784 /// side` model walked the 4:2:0 count on every axis, so this counter is
4785 /// the reach/arm witness for the per-axis walk.
4786 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4787 const { std::cell::Cell::new(0) };
4788 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4789 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4790 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4791 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4792 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4793 const { std::cell::Cell::new(0) };
4794}
4795
4796/// Current value of [`INTRABC_128RECT_HITS`].
4797#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4798pub fn intrabc_128rect_hits() -> usize {
4799 INTRABC_128RECT_HITS.with(|c| c.get())
4800}
4801
4802/// Zeroes [`INTRABC_128RECT_HITS`].
4803#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4804pub(crate) fn reset_intrabc_128rect_hits() {
4805 INTRABC_128RECT_HITS.with(|c| c.set(0));
4806}
4807
4808/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
4809#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4810pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
4811 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
4812}
4813
4814/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
4815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4816pub fn intrabc_128rect_chunk_shape() -> usize {
4817 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
4818}
4819
4820/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
4821/// [`INTRABC_128RECT_CHUNK_SHAPE`].
4822#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4823pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
4824 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
4825 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
4826}
4827
4828/// Current value of [`INTRABC_VARTX_HITS`].
4829pub fn intrabc_vartx_hits() -> usize {
4830 INTRABC_VARTX_HITS.with(|c| c.get())
4831}
4832
4833/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4834pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4835 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4836}
4837
4838/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4839#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4840pub(crate) fn reset_intrabc_vartx_hits() {
4841 INTRABC_VARTX_HITS.with(|c| c.set(0));
4842}
4843
4844/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4845/// decode).
4846#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4847pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4848 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4849}
4850
4851/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4852#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4853pub fn rect_intrabc_vartx_hits() -> usize {
4854 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4855}
4856
4857/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4858/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4859/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4860/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4861fn record_intrabc_mi(
4862 mi_r: usize,
4863 mi_c: usize,
4864 n4: usize,
4865 dv: Option<(i32, i32)>,
4866 n: &mut Neighbours,
4867 fctx: &crate::decode::FrameCtx,
4868) {
4869 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4870}
4871
4872/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4873/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4874/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4875///
4876/// Also stamps libaom's `is_inter_block` verdict for this block into the
4877/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4878/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4879/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4880/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4881/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4882/// every block runs; this runs after it (class leaked-band otherwise).
4883fn record_intrabc_mi_rect(
4884 mi_r: usize,
4885 mi_c: usize,
4886 n4_w: usize,
4887 n4_h: usize,
4888 dv: Option<(i32, i32)>,
4889 n: &mut Neighbours,
4890 fctx: &crate::decode::FrameCtx,
4891) {
4892 if dv.is_some() {
4893 for i in 0..n4_w {
4894 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4895 *cell = true;
4896 }
4897 }
4898 for i in 0..n4_h {
4899 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4900 *cell = true;
4901 }
4902 }
4903 }
4904 fctx.intrabc_mi_grid.with(|g| {
4905 let mut g = g.borrow_mut();
4906 let Some((grid, _, _)) = g.as_mut() else {
4907 return;
4908 };
4909 let info = crate::mvstack::MiInfo {
4910 is_inter: dv.is_some(),
4911 ref_frame: 0,
4912 ref_frame1: NO_REF1,
4913 mv: mv16(dv.unwrap_or((0, 0))),
4914 mv1: (0, 0),
4915 is_new_mv: dv.is_some(),
4916 is_global_mv0: false,
4917 is_global_mv1: false,
4918 size: n4_w as u8,
4919 size_h: n4_h as u8,
4920 };
4921 for r in mi_r..mi_r + n4_h {
4922 for c in mi_c..mi_c + n4_w {
4923 grid.set(r, c, info);
4924 }
4925 }
4926 });
4927}
4928
4929// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4930// proves a real `skip_mode_present` stream actually reached a block that
4931// picked it, not just that the frame header bit was set.
4932thread_local! {
4933 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4934 const { std::cell::Cell::new(0) };
4935}
4936
4937/// Current value of [`SKIP_MODE_HITS`].
4938#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4939pub(crate) fn skip_mode_hits() -> usize {
4940 SKIP_MODE_HITS.with(|c| c.get())
4941}
4942
4943// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4944// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4945// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4946// reached [`obmc_blend`], not just the header bit.
4947thread_local! {
4948 static OBMC_HITS: std::cell::Cell<usize> =
4949 const { std::cell::Cell::new(0) };
4950}
4951
4952// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4953// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4954// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4955// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4956// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
4957// decoder used to read with the wrong alphabet, so a gate that asserts this
4958// counter advanced proves the fixed path fired (class
4959// `gate-blind-to-feature`).
4960thread_local! {
4961 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4962}
4963
4964/// Current value of [`FIMV_ALPHABET_HITS`].
4965pub fn fimv_alphabet_hits() -> usize {
4966 FIMV_ALPHABET_HITS.with(|c| c.get())
4967}
4968
4969// lane-fimv r1: how many frame headers this decoder has decoded with
4970// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
4971// prove the encoder really produced the header state under test rather than
4972// assume it.
4973thread_local! {
4974 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4975}
4976
4977/// Current value of [`FIMV_FRAME_HITS`].
4978pub fn fimv_frame_hits() -> usize {
4979 FIMV_FRAME_HITS.with(|c| c.get())
4980}
4981
4982/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
4983/// `force_integer_mv` bit is set.
4984pub fn note_force_integer_mv_frame() {
4985 hit!(FIMV_FRAME_HITS);
4986}
4987
4988/// Current value of [`OBMC_HITS`].
4989#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4990pub(crate) fn obmc_hits() -> usize {
4991 OBMC_HITS.with(|c| c.get())
4992}
4993
4994// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
4995// off the neighbour band -- the positive half of the proof for "an OBMC
4996// neighbour whose switchable interp filter was never recorded". A
4997// fixed-filter frame returns before this point (its neighbours legitimately
4998// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
4999// `interp_filter` symbols were published by `record_inter_rect_mi`.
5000thread_local! {
5001 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5002}
5003
5004/// Current value of [`OBMC_FILTER_BAND_READS`].
5005#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5006pub(crate) fn obmc_filter_band_reads() -> usize {
5007 OBMC_FILTER_BAND_READS.with(|c| c.get())
5008}
5009
5010// lane-scaledref r1: per-case firing counts for the scaled-reference gate
5011// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
5012// reference would pass just as well and prove nothing, so the gate
5013// hard-asserts each combination this round lifts actually occurred:
5014// a compound block with a scaled tap, a warp block whose warp libaom
5015// suppresses because the reference is scaled, an OBMC block, an interintra
5016// block, and an 8x8 leaf.
5017thread_local! {
5018 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5019 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5020 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5021 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5022 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5023 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5024 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5025}
5026
5027/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5028/// scaled and one unscaled tap.
5029#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5030pub(crate) fn mixed_scale_compound_hits() -> usize {
5031 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5032}
5033
5034/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5035/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5036/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5037/// `blockd.h:1484`).
5038#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5039pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5040 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5041}
5042
5043/// Current value of [`SCALED_COMPOUND_HITS`].
5044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5045pub(crate) fn scaled_compound_hits() -> usize {
5046 SCALED_COMPOUND_HITS.with(|c| c.get())
5047}
5048
5049/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5050pub fn scaled_warp_fallback_hits() -> usize {
5051 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5052}
5053
5054/// Current value of [`SCALED_OBMC_HITS`].
5055#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5056pub(crate) fn scaled_obmc_hits() -> usize {
5057 SCALED_OBMC_HITS.with(|c| c.get())
5058}
5059
5060/// Current value of [`SCALED_INTERINTRA_HITS`].
5061#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5062pub(crate) fn scaled_interintra_hits() -> usize {
5063 SCALED_INTERINTRA_HITS.with(|c| c.get())
5064}
5065
5066/// Current value of [`SCALED_BLOCK8_HITS`].
5067#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5068pub(crate) fn scaled_block8_hits() -> usize {
5069 SCALED_BLOCK8_HITS.with(|c| c.get())
5070}
5071
5072// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5073// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5074// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5075// 8x8-leaf OBMC block apart from a 16x16+ one.
5076thread_local! {
5077 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5078}
5079
5080// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5081// pair whose two directions differ (`enable_dual_filter` only -- with dual
5082// filter off both directions take the single symbol, so this can never fire).
5083// A gate asserting it proves the stream really carries dual-filter blocks.
5084thread_local! {
5085 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5086}
5087
5088// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5089// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5090// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5091// no-filter sentinel that made a neighbouring OBMC block panic).
5092thread_local! {
5093 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5094}
5095
5096/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5097#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5098pub(crate) fn dual_filter_diff_hits() -> usize {
5099 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5100}
5101
5102/// Current value of [`COMPOUND8_FILTER_HITS`].
5103#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5104pub(crate) fn compound8_filter_hits() -> usize {
5105 COMPOUND8_FILTER_HITS.with(|c| c.get())
5106}
5107
5108// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5109// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5110// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5111// -- the gate's proof that a fixture really exercises the alphabet this
5112// round changed, even though the block itself still refuses (warp
5113// estimation/filter not ported).
5114thread_local! {
5115 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5116 const { std::cell::Cell::new(0) };
5117}
5118
5119/// Current value of [`WARP_SELECTED_HITS`].
5120#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5121pub(crate) fn warp_selected_hits() -> usize {
5122 WARP_SELECTED_HITS.with(|c| c.get())
5123}
5124
5125// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5126// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5127// into the compound intermediate) rather than translationally -- the
5128// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5129// really reached [`crate::warp::warp_affine_compound`].
5130// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5131// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5132// counter is frame-global. These two are the same arms restricted to blocks
5133// whose top mode-info row is in the frame's upper half, which is the half
5134// this lane's evidence covers.
5135thread_local! {
5136 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5137 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5138}
5139
5140/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5141/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5142///
5143/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5144/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5145/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5146/// The figure quoted for that fixture comes from a patch-run-restore build
5147/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5148/// is the same discipline every 4:2:2 lane in this family uses.
5149#[allow(dead_code)]
5150pub(crate) fn top_half_compound_hits() -> usize {
5151 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5152}
5153
5154/// How many inter blocks in the frame's upper half satisfy libaom's
5155/// `is_global_mv_block` on at least one reference slot -- mode
5156/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5157/// model > `TRANSLATION`. This is the block set whose prediction goes
5158/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5159/// as computed at the increment site; it is NOT merely "some slot has a
5160/// non-TRANSLATION model", which also counts blocks that are not global-mv
5161/// blocks.
5162///
5163/// Like [`top_half_compound_hits`], no committed test reads it: with the
5164/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5165/// these numbers describe.
5166#[allow(dead_code)]
5167pub(crate) fn top_half_warp_hits() -> usize {
5168 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5169}
5170
5171thread_local! {
5172 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5173 const { std::cell::Cell::new(0) };
5174}
5175
5176/// Current value of [`COMPOUND_WARP_HITS`].
5177#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5178pub(crate) fn compound_warp_hits() -> usize {
5179 COMPOUND_WARP_HITS.with(|c| c.get())
5180}
5181
5182// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5183// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5184// translationally until r3, so a gate needs to tell a warped 8x8 compound
5185// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5186thread_local! {
5187 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5188 const { std::cell::Cell::new(0) };
5189}
5190
5191/// Current value of [`COMPOUND_WARP_HITS_8`].
5192#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5193pub(crate) fn compound_warp_hits_8() -> usize {
5194 COMPOUND_WARP_HITS_8.with(|c| c.get())
5195}
5196
5197// lane-gmaffine r1: how many blocks built their prediction from a
5198// SIX-parameter (`AFFINE`) global-motion model through
5199// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5200// carried an AFFINE `global_motion_params` AND that a block was predicted
5201// with it, not merely that the header parsed one.
5202thread_local! {
5203 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5204 const { std::cell::Cell::new(0) };
5205}
5206
5207/// Current value of [`AFFINE_GM_HITS`].
5208#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5209pub(crate) fn affine_gm_hits() -> usize {
5210 AFFINE_GM_HITS.with(|c| c.get())
5211}
5212
5213// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5214// combine rather than the simple average -- `compound_idx == 0` under
5215// `enable_jnt_comp`, whose weights come from
5216// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5217// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5218// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5219// stream that carries `enable_jnt_comp = true` in its sequence header but
5220// codes every compound block with `compound_idx == 1` leaves this at 0 and
5221// decoded identically without the whole distance-weight path.
5222thread_local! {
5223 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5224 const { std::cell::Cell::new(0) };
5225}
5226
5227/// Current value of [`DIST_WTD_COMP_HITS`].
5228#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5229pub(crate) fn dist_wtd_comp_hits() -> usize {
5230 DIST_WTD_COMP_HITS.with(|c| c.get())
5231}
5232
5233/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5234#[allow(dead_code)] // test-only
5235pub(crate) fn reset_dist_wtd_comp_hits() {
5236 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5237}
5238
5239// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5240// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5241// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5242// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5243// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5244// side build and its own counter, [`AFFINE_GM_HITS`]).
5245thread_local! {
5246 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5247 const { std::cell::Cell::new(0) };
5248}
5249
5250/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5251#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5252pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5253 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5254}
5255
5256// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5257// differently at the block's WIDTH than at libaom's
5258// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5259// pick the wrong motion_mode alphabet.
5260thread_local! {
5261 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5262}
5263
5264/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5265pub fn tr_reach_longer_side_hits() -> usize {
5266 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5267}
5268
5269// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5270// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5271// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5272// reads its interp-filter symbol. Counts the blocks where that guard flips
5273// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5274// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5275// entropy desync one symbol wide).
5276thread_local! {
5277 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5278}
5279
5280/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5281pub fn gm_nontrans_small_side_hits() -> usize {
5282 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5283}
5284
5285// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5286// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5287// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5288// only once `find_projection` returned a usable model, unlike
5289// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5290// proof that the leaf path itself fired, not the 16x16+ one.
5291thread_local! {
5292 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5293 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5294}
5295
5296/// Current value of [`GLOBALMV_HITS_8`].
5297#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5298pub(crate) fn globalmv_hits_8() -> usize {
5299 GLOBALMV_HITS_8.with(|c| c.get())
5300}
5301
5302/// Current value of [`WARP_HITS_8`].
5303#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5304pub(crate) fn warp_hits_8() -> usize {
5305 WARP_HITS_8.with(|c| c.get())
5306}
5307
5308// How many blocks decoded `interintra == 1` with the non-wedge blended
5309// prediction applied (lane-interintra r1) -- the gate's proof that a
5310// stream actually exercised interintra.
5311thread_local! {
5312 static INTERINTRA_HITS: std::cell::Cell<usize> =
5313 const { std::cell::Cell::new(0) };
5314}
5315
5316/// Current value of [`INTERINTRA_HITS`].
5317#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5318pub(crate) fn interintra_hits() -> usize {
5319 INTERINTRA_HITS.with(|c| c.get())
5320}
5321
5322// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5323// -- the shape `interintra_blend` used to build a square `side x side` intra
5324// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5325// pre-existing interintra gate passed with that bug, so the rect arm needs
5326// its own counter to stop being vacuous.
5327thread_local! {
5328 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5329}
5330
5331/// Current value of [`INTERINTRA_RECT_HITS`].
5332pub fn interintra_rect_hits() -> usize {
5333 INTERINTRA_RECT_HITS.with(|c| c.get())
5334}
5335
5336// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5337// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5338// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5339// gate fixture actually exercises this alphabet, even though the block
5340// still refuses (the mask blend itself is unported).
5341thread_local! {
5342 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5343 const { std::cell::Cell::new(0) };
5344}
5345
5346/// Current value of [`MASKED_COMPOUND_HITS`].
5347#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5348pub(crate) fn masked_compound_hits() -> usize {
5349 MASKED_COMPOUND_HITS.with(|c| c.get())
5350}
5351
5352// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5353// masked-compound block whose true footprint is rectangular, i.e. the case
5354// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5355// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5356// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5357thread_local! {
5358 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5359 const { std::cell::Cell::new(0) };
5360}
5361
5362/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5363#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5364pub(crate) fn rect_masked_compound_hits() -> usize {
5365 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5366}
5367
5368// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5369// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5370// actually exercised the wedge blend, not just the DIFFWTD half of
5371// `MASKED_COMPOUND_HITS`.
5372thread_local! {
5373 static WEDGE_HITS: std::cell::Cell<usize> =
5374 const { std::cell::Cell::new(0) };
5375}
5376
5377/// Current value of [`WEDGE_HITS`].
5378#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5379pub(crate) fn wedge_hits() -> usize {
5380 WEDGE_HITS.with(|c| c.get())
5381}
5382
5383// How many blocks decoded a real wedge-INTERINTRA block
5384// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5385// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5386// smooth arm counted by `INTERINTRA_HITS`.
5387thread_local! {
5388 static WII_HITS: std::cell::Cell<usize> =
5389 const { std::cell::Cell::new(0) };
5390}
5391
5392/// Current value of [`WII_HITS`].
5393#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5394pub(crate) fn wii_hits() -> usize {
5395 WII_HITS.with(|c| c.get())
5396}
5397
5398// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5399// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5400// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5401// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5402// frame carrying one.
5403thread_local! {
5404 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5405}
5406
5407/// Current value of [`NOCFL_UV_MODE_HITS`].
5408#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5409pub(crate) fn nocfl_uv_mode_hits() -> usize {
5410 NOCFL_UV_MODE_HITS.with(|c| c.get())
5411}
5412
5413/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5414/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5415pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5416 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5417
5418fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5419 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5420}
5421
5422// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5423// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5424// the rect wedge masks lifted this round actually fired, not just the square
5425// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5426thread_local! {
5427 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5428 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5429}
5430
5431/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5432pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5433 RECT_WEDGE_HITS.with(|c| c.get())
5434}
5435
5436/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5437pub(crate) fn rect_wii_hits() -> [usize; 6] {
5438 RECT_WII_HITS.with(|c| c.get())
5439}
5440
5441// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5442// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5443// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5444// aomdec, neighbour list included).
5445thread_local! {
5446 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5447}
5448
5449/// Current value of [`OBMC_RECT_LEAF_HITS`].
5450pub(crate) fn obmc_rect_leaf_hits() -> usize {
5451 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5452}
5453
5454// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5455// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5456// to be read from the pair's FIRST mi, which is a different block and, when
5457// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5458// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5459thread_local! {
5460 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5461}
5462
5463/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5464pub(crate) fn obmc_pair_filter_hits() -> usize {
5465 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5466}
5467
5468// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5469// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5470// own side, so a block overhanging the bottom/right still predicts the full
5471// neighbour strip (the destination write is what clips). We used to shrink the
5472// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5473// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5474thread_local! {
5475 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5476}
5477
5478/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5479#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5480pub(crate) fn obmc_edge_span_hits() -> usize {
5481 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5482}
5483
5484/// Current value of [`OBMC_HITS_8`].
5485#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5486pub(crate) fn obmc_hits_8() -> usize {
5487 OBMC_HITS_8.with(|c| c.get())
5488}
5489
5490// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5491// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5492// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5493// `VERT_B` all still fall into the generic "a partition type this encoder
5494// never writes" refusal below) -- the gate's proof that a free-partition
5495// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5496// coincidentally never selecting one.
5497thread_local! {
5498 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5499 const { std::cell::Cell::new(0) };
5500}
5501
5502/// Current value of [`EXTENDED_PARTITION_HITS`].
5503#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5504pub(crate) fn extended_partition_hits() -> usize {
5505 EXTENDED_PARTITION_HITS.with(|c| c.get())
5506}
5507
5508// lane-partitions r1: how many 32x32 quadrants decoded a real
5509// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5510// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5511// gate's proof this round's arms actually fired.
5512thread_local! {
5513 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5514 const { std::cell::Cell::new(0) };
5515}
5516
5517/// Current value of [`RECT_PARTITION_HITS`].
5518#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5519pub(crate) fn rect_partition_hits() -> usize {
5520 RECT_PARTITION_HITS.with(|c| c.get())
5521}
5522
5523// lane-inter8 r1: how many superblocks an inter tile coded as a single
5524// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5525// static content, previously a named refusal).
5526thread_local! {
5527 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5528 /// path decoded as one whole block (its gate's own witness).
5529 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5530 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5531 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5532 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5533}
5534
5535/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5536pub(crate) fn inter_sb128_horz_hits() -> usize {
5537 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5538}
5539
5540/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5541pub(crate) fn inter_sb128_vert_hits() -> usize {
5542 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5543}
5544
5545/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5546pub fn inter_sb128_none_hits() -> usize {
5547 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5548}
5549
5550thread_local! {
5551 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5552 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5553 /// units) -- the gate's witness that the lifted refusal's case fired.
5554 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5555}
5556
5557/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5558pub fn intra_128_in_inter_hits() -> usize {
5559 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5560}
5561
5562thread_local! {
5563 /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the
5564 /// intra-in-inter 128x128 root read (`decode_inter_block`'s
5565 /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every
5566 /// unit is one `read_plane` on U and one on V, so the counter is the
5567 /// gate's proof the arm ran at all -- no committed 4:4:4 fixture
5568 /// reached it before this lane.
5569 pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell<usize> =
5570 const { std::cell::Cell::new(0) };
5571}
5572
5573/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's
5574/// before/after delta.
5575pub fn intra_128_in_inter_mu_chroma_hits() -> usize {
5576 INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get)
5577}
5578
5579thread_local! {
5580 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5581 const { std::cell::Cell::new(0) };
5582}
5583
5584/// Current value of [`INTER_SB_NONE_HITS`].
5585#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5586pub(crate) fn inter_sb_none_hits() -> usize {
5587 INTER_SB_NONE_HITS.with(|c| c.get())
5588}
5589
5590// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5591// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5592// path has always run that loop, so only this counter proves the newly-lifted
5593// alphabet value fired.
5594thread_local! {
5595 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5596 const { std::cell::Cell::new(0) };
5597}
5598
5599/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5601pub(crate) fn inter_sub16_split_hits() -> usize {
5602 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5603}
5604
5605// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5606// while at least one reference picture was SCALED (superres) -- the counter
5607// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5608thread_local! {
5609 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5610 const { std::cell::Cell::new(0) };
5611}
5612
5613/// Current value of [`SCALED_LEAF8_HITS`].
5614pub fn scaled_leaf8_hits() -> usize {
5615 SCALED_LEAF8_HITS.with(|c| c.get())
5616}
5617
5618// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5619// rect pair) were predicted from a SCALED reference -- the counter behind the
5620// lifted "sub-8x8 inter block under a scaled reference" refusal.
5621thread_local! {
5622 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5623 const { std::cell::Cell::new(0) };
5624}
5625
5626/// Current value of [`SCALED_SUB8_HITS`].
5627pub fn scaled_sub8_hits() -> usize {
5628 SCALED_SUB8_HITS.with(|c| c.get())
5629}
5630
5631// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5632// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5633// rect coefficient reader itself fired, not just the strip-level partition
5634// symbol [`RECT_PARTITION_HITS`] already counts.
5635thread_local! {
5636 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5637 const { std::cell::Cell::new(0) };
5638}
5639
5640/// Current value of [`RECT_COEFF_HITS`].
5641#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5642pub(crate) fn rect_coeff_hits() -> usize {
5643 RECT_COEFF_HITS.with(|c| c.get())
5644}
5645
5646// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5647// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5648// charter's real-aomenc gate hard-asserts.
5649thread_local! {
5650 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5651 const { std::cell::Cell::new(0) };
5652}
5653
5654/// Current value of [`RECT_LEAF_COEFF_HITS`].
5655#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5656pub(crate) fn rect_leaf_coeff_hits() -> usize {
5657 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5658}
5659
5660// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5661// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5662// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5663// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5664// needs rectangular intra prediction" before this round.
5665thread_local! {
5666 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5667 const { std::cell::Cell::new([0; 3]) };
5668}
5669
5670/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5671/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5672#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5673pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5674 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5675}
5676
5677// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5678// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5679// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5680// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5681// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5682// a single counter cannot tell an axis swap from a working arm
5683// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5684thread_local! {
5685 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5686 const { std::cell::Cell::new([0; 2]) };
5687}
5688
5689/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5690/// (0 = 64x32, 1 = 32x64).
5691pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5692 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5693}
5694
5695// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5696// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5697// is never incremented) -- the gate's proof that the lifted path ran per depth.
5698thread_local! {
5699 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5700 const { std::cell::Cell::new([0; 3]) };
5701}
5702
5703// lane-t900 r21: rect intra strips inside an inter frame that read the
5704// screen-content palette syntax (`allow_screen_content_tools` set and the
5705// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5706// refusal used to guard, so this counter is what keeps its witness gate
5707// non-vacuous.
5708thread_local! {
5709 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5710}
5711
5712/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5714pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5715 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5716}
5717
5718/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5719#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5720pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5721 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5722}
5723
5724/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5725#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5726pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5727 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5728}
5729
5730// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5731// approximation would have resolved off a DIFFERENT CDF row than the real
5732// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5733// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5734// tally is green on the old code too (class gate-blind-to-feature).
5735thread_local! {
5736 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5737 const { std::cell::Cell::new(0) };
5738}
5739
5740/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5741#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5742pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5743 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5744}
5745
5746// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5747// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5748// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5749// rect strip on the inter block path" before this round.
5750thread_local! {
5751 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5752 const { std::cell::Cell::new([0; 4]) };
5753}
5754
5755/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5756/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5757pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5758 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5759}
5760
5761// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5762// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5763// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5764// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5765// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
5766// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
5767// REACH only, never that the fix bites -- that is the gate's byte compare and
5768// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
5769thread_local! {
5770 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5771}
5772
5773/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5774#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5775pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5776 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5777}
5778
5779/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
5780#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5781pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
5782 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
5783}
5784
5785// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
5786// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
5787// stream of the same recipe leaves it at 0, which is what makes it the
5788// 4:4:4-only route.
5789//
5790// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
5791// never was. A route counter fires identically before and after a change that
5792// changes nothing downstream, so a non-zero count proves REACH and nothing
5793// more. On this lane it is also armed deliberately OUTSIDE the `own444`
5794// expression, so that the mutation (`own444 = false`) still increments it and
5795// the red comes from the pixel/entropy arm instead. The evidence that the ss
5796// gate bites is the measured fork move -- first entropy fork read 11750 ->
5797// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
5798// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
5799// a DIFFERS-style assertion to carry a claim.
5800thread_local! {
5801 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5802}
5803
5804/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
5805#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5806pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
5807 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5808}
5809
5810/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
5811#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5812pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
5813 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
5814}
5815
5816// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
5817// through one of the key-frame rect readers ([`decode_block_rect4`],
5818// [`decode_block_rect64`]). `Some((size_group, skip))` tells
5819// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
5820// already read by [`decode_inter_block`] and (b) the luma mode comes off
5821// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
5822// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
5823
5824// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
5825// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
5826// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
5827// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
5828thread_local! {
5829 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5830 const { std::cell::Cell::new(0) };
5831}
5832
5833/// Current value of [`MODE_MI_OVERRIDE_HITS`].
5834#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5835pub(crate) fn mode_mi_override_hits() -> usize {
5836 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5837}
5838
5839// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
5840// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
5841// mode from the previous tile, where libaom's `up_available`/`left_available`
5842// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
5843// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
5844// per superblock row in `start_row`, so the luma fallback cannot leak the way
5845// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
5846// the invariant that makes the coarse fallback safe.
5847thread_local! {
5848 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
5849 const { std::cell::Cell::new(0) };
5850}
5851
5852/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
5853#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5854pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
5855 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
5856}
5857
5858// lane-cfl r1: how many times a chroma intra-edge filter-type read
5859// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
5860// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
5861// r1 defect would have filtered a chroma edge with the wrong strength.
5862thread_local! {
5863 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5864 const { std::cell::Cell::new(0) };
5865}
5866
5867/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
5868#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5869pub(crate) fn uv_mode_mi_override_hits() -> usize {
5870 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5871}
5872
5873// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
5874// `uv_mode` from the mi GRID where the one-slot-per-column map would have
5875// answered differently -- the sub-8x8 pair case where the pair's own first
5876// half had already overwritten the column slot the chroma-ref half reads.
5877thread_local! {
5878 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
5879 const { std::cell::Cell::new(0) };
5880}
5881
5882/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
5883pub fn uv_mode_grid_override_hits() -> usize {
5884 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
5885}
5886
5887// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
5888// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
5889// from an earlier block in that pixel row/column while the mi-exact map --
5890// which an inter block only started writing this round -- correctly says the
5891// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
5892// an INTER mode, and its `uv_mode` "is not set for inter blocks").
5893thread_local! {
5894 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
5895 const { std::cell::Cell::new(0) };
5896}
5897
5898/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
5899#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5900pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
5901 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
5902}
5903
5904// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
5905// suppressed at a TILE edge that is not a frame edge -- the above/left
5906// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
5907// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
5908// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
5909// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
5910// above would decide this tile's chroma edge filter strength.
5911thread_local! {
5912 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
5913 const { std::cell::Cell::new(0) };
5914}
5915
5916/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
5917#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5918pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
5919 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
5920}
5921
5922// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
5923// left neighbour whose `uv_mode` at libaom's real read cell
5924// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
5925// cell this decoder used to read (its own mi row). Two buckets: the raw mode
5926// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
5927// flipped. The second is the one that can move pixels.
5928thread_local! {
5929 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
5930 const { std::cell::Cell::new(0) };
5931 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
5932 const { std::cell::Cell::new(0) };
5933}
5934thread_local! {
5935 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5936}
5937
5938/// Current value of [`UV_LEFT_SS_Y_READS`].
5939pub fn uv_left_ss_y_reads() -> usize {
5940 UV_LEFT_SS_Y_READS.with(|c| c.get())
5941}
5942
5943/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
5944pub fn uv_left_ss_y_mode_diff_hits() -> usize {
5945 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
5946}
5947
5948/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
5949pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
5950 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
5951}
5952
5953// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
5954// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
5955// decoder reads (its own mi row) and the cell libaom reads (one row down)
5956// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
5957// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
5958// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
5959thread_local! {
5960 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5961}
5962
5963/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
5964pub fn uv_left_1mi_split_hits() -> usize {
5965 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
5966}
5967
5968// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
5969// Bumped in `Neighbours::start_tile`; never read by decode logic.
5970thread_local! {
5971 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
5972}
5973
5974// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
5975// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
5976// shapes the r1 chroma defect showed up on.
5977thread_local! {
5978 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5979 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5980}
5981
5982/// Current value of [`CFL_BLOCK_HITS`].
5983#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5984pub(crate) fn cfl_block_hits() -> usize {
5985 CFL_BLOCK_HITS.with(|c| c.get())
5986}
5987
5988/// Current value of [`UV_ANGLE_DELTA_HITS`].
5989#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5990pub(crate) fn uv_angle_delta_hits() -> usize {
5991 UV_ANGLE_DELTA_HITS.with(|c| c.get())
5992}
5993
5994// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
5995// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
5996// gate's proof this round's arms actually reached a real block, not just
5997// that `partition_w64` read one of those two symbol values.
5998thread_local! {
5999 static SB_RECT_HITS: std::cell::Cell<usize> =
6000 const { std::cell::Cell::new(0) };
6001}
6002
6003// Current value of [`SB_RECT_HITS`].
6004// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
6005// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
6006// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
6007// non-SPLIT edge arm actually decoded (before this round the bit was read and
6008// thrown away, so that arm was unreachable).
6009thread_local! {
6010 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6011}
6012
6013/// Current value of [`EDGE_PART_HITS`].
6014#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6015pub(crate) fn edge_part_hits() -> [usize; 4] {
6016 EDGE_PART_HITS.with(|c| c.get())
6017}
6018
6019/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
6020#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6021pub(crate) fn reset_edge_part_hits() {
6022 EDGE_PART_HITS.with(|c| c.set([0; 4]));
6023}
6024
6025fn bump_edge_part(slot: usize) {
6026 hit_do! {
6027 EDGE_PART_HITS.with(|c| {
6028 let mut h = c.get();
6029 h[slot] += 1;
6030 c.set(h);
6031 });
6032 }
6033}
6034
6035#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6036pub(crate) fn sb_rect_hits() -> usize {
6037 SB_RECT_HITS.with(|c| c.get())
6038}
6039
6040// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
6041// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
6042// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
6043// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6044// paths (intra and inter) feed the same counter.
6045//
6046// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6047// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6048// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6049// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6050// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6051// every SB of the last row), so the 32-level slots stay 0 on that content and
6052// only these prove the arm fired.
6053thread_local! {
6054 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6055 const { std::cell::Cell::new([0; 8]) };
6056}
6057
6058/// Current value of [`EDGE32_HITS`].
6059#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6060pub(crate) fn edge32_hits() -> [usize; 8] {
6061 EDGE32_HITS.with(|c| c.get())
6062}
6063
6064/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6065/// reads are `if`-conditions, so the counter has to ride the expression.
6066fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6067 bump_edge32(base + bit.min(1));
6068 bit
6069}
6070
6071fn bump_edge32(slot: usize) {
6072 hit_do! {
6073 EDGE32_HITS.with(|c| {
6074 let mut h = c.get();
6075 h[slot] += 1;
6076 c.set(h)
6077 });
6078 }
6079}
6080
6081// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6082// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6083// strip) fired. Real aomenc picks these at 64 even with
6084// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6085// the counter the gate hard-asserts.
6086thread_local! {
6087 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6088 const { std::cell::Cell::new([0; 4]) };
6089}
6090
6091/// Current value of [`SB_AB_HITS`], summed over the four arms.
6092#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6093pub(crate) fn sb_ab_hits() -> usize {
6094 SB_AB_HITS.with(|c| c.get().iter().sum())
6095}
6096
6097/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6098/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6099/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6100/// proof of all four.
6101#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6102pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6103 SB_AB_HITS.with(std::cell::Cell::get)
6104}
6105
6106// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6107// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6108// strips). Two counters, not one, because a gate that only proved "some 1:4
6109// strip fired" would pass on a stream that never coded the other axis, and
6110// every scan/context table this round added comes in a transposed pair.
6111thread_local! {
6112 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6113 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6114}
6115
6116/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6117#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6118pub(crate) fn sb_rect4_horz_hits() -> usize {
6119 SB_RECT4_HORZ_HITS.with(|c| c.get())
6120}
6121
6122/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6123#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6124pub(crate) fn sb_rect4_vert_hits() -> usize {
6125 SB_RECT4_VERT_HITS.with(|c| c.get())
6126}
6127
6128// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6129// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6130// strips), the arms the ReelB mid-film extract stops at.
6131thread_local! {
6132 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6133 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6134 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6135 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6136 /// `PARTITION_VERT_4`.
6137 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6138 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6139 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6140 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6141 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6142 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6143 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6144 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6145}
6146
6147// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6148// a gate that only counted strips would pass on an all-skip stream, which
6149// exercises none of the new scan/context tables.
6150thread_local! {
6151 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6152}
6153
6154// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6155// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6156// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6157// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6158// counts the same for a 16x8/8x16 strip below 16x16.
6159thread_local! {
6160 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6161 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6162 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6163}
6164
6165/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6166#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6167pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6168 (
6169 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6170 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6171 )
6172}
6173
6174/// Current value of `SUB16_SPLIT_HITS`.
6175#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6176pub(crate) fn sub16_split_hits() -> usize {
6177 SUB16_SPLIT_HITS.with(|c| c.get())
6178}
6179
6180// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6181// luma transform is SPLIT and which therefore leave through that fn's early
6182// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6183thread_local! {
6184 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6185}
6186
6187/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6188#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6189pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6190 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6191}
6192
6193/// Current value of `RECT4_COEFF_HITS`.
6194pub(crate) fn rect4_coeff_hits() -> usize {
6195 RECT4_COEFF_HITS.with(|c| c.get())
6196}
6197
6198// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6199// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6200// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6201// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6202// asserts the arms it proves separately so a run whose RD only picked one
6203// cannot pass as proof of the others.
6204thread_local! {
6205 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6206}
6207
6208/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6209/// inter frame).
6210pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6211 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6212}
6213
6214// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6215// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6216// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6217// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6218// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6219// arm separately so a run whose RD only picked one cannot pass as proof of
6220// four.
6221thread_local! {
6222 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6223}
6224
6225/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6226/// inter frame).
6227pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6228 AB16_INTER_HITS.with(std::cell::Cell::get)
6229}
6230
6231// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6232// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6233// counts the odd strips that close a 4:2:0 chroma pair
6234// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6235// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6236// the PREVIOUS strip's own mv/ref/filters -- libaom
6237// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6238// through `is_sub8x8_inter` (same file, :54).
6239thread_local! {
6240 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6241 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6242 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6243 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6244}
6245
6246// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6247// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6248// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6249thread_local! {
6250 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6251 const { std::cell::Cell::new([0; 3]) };
6252}
6253
6254/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6255/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6256pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6257 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6258 (v[0], v[1], v[2])
6259}
6260
6261/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6262/// strips, chroma pairs closed, chroma pairs built from two different
6263/// strips' motion vectors)`.
6264pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6265 (
6266 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6267 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6268 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6269 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6270 )
6271}
6272
6273/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6274/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6275/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6276/// that all mean "an ordinary block, chroma of its own".
6277#[derive(Clone, Copy)]
6278pub(crate) struct InterStripChroma {
6279 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6280 /// read and reconstruct NO chroma at all.
6281 has_chroma: bool,
6282 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6283 horz: bool,
6284 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6285 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6286 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6287 pair_mi: (usize, usize),
6288 /// The previous (even) strip's single-reference MC parameters, `None`
6289 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6290 /// and the whole chroma block is predicted from THIS strip's mv.
6291 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6292}
6293
6294/// The single-reference MC parameters of the inter block that decoded
6295/// last -- read by the next 1:4 strip to build its pair's chroma.
6296
6297fn bump_ab16_inter(arm: usize) {
6298 hit_do! {
6299 AB16_INTER_HITS.with(|c| {
6300 let mut v = c.get();
6301 v[arm] += 1;
6302 c.set(v);
6303 });
6304 }
6305}
6306
6307// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6308// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6309// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6310thread_local! {
6311 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6312 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6313 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6314 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6315 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6316 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6317 /// base mi differs from what the strip's own (odd) mi would have said --
6318 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6319 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6320 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6321 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6322 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6323 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6324 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6325 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6326 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6327 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6328 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6329 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6330 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6331 /// block overhanging the frame does NOT code.
6332 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6333 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6334 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6335 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6336 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6337 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6338 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6339 /// hardcoded 4:2:0 span mis-stepped).
6340 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6341 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6342 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6343 /// that replaced the single rect unit).
6344 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6345 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6346 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6347 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6348 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6349 /// units whose libaom-faithful block-relative reach
6350 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6351 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6352 /// no stream reached a rect leaf where the two disagree -- a gate
6353 /// asserting the reach fix must see this nonzero, or the fixture never
6354 /// exercised the fixed path.
6355 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6356}
6357
6358/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6359/// that reconstructed as flat DC before lane-kf1200 r2).
6360pub fn skip_cfl_hits() -> usize {
6361 SKIP_CFL_HITS.with(|c| c.get())
6362}
6363
6364/// How many chroma transform units the frame-edge clip skipped in
6365/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6366/// stream whose lossless blocks never overhang the frame -- a gate asserting
6367/// the clip fired must see this nonzero.
6368pub fn chroma_edge_tu_clip_hits() -> usize {
6369 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6370}
6371
6372/// How many skipped lossless intrabc rect strips had their luma entropy
6373/// bands zeroed per unit (lane-av1-loss64).
6374pub fn skip_lossless_band_reset_hits() -> usize {
6375 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6376}
6377
6378/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6379/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6380/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6381/// must see this nonzero.
6382pub fn rect_split_lossless_chroma444_hits() -> usize {
6383 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6384}
6385
6386/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6387/// per-4x4 inter units (lane-av1-ibc444rect).
6388pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6389 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6390}
6391
6392/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6393/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6394pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6395 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6396}
6397
6398/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6399/// block-relative reach libaom's `has_bottom_left` gives, where the
6400/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6401/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6402pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6403 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6404}
6405
6406/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6407pub fn reset_sub8_chroma444_tu_reach_hits() {
6408 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6409}
6410
6411/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6412pub fn reset_ibc444rect_hits() {
6413 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6414 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6415}
6416
6417/// Gate-side reset for the two lane-av1-loss64 counters above.
6418pub fn reset_loss64_hits() {
6419 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6420 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6421}
6422
6423/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6424/// from the pair's base mi than the strip's own mi would have given.
6425pub fn rect4_16_uv_pair_filt_hits() -> usize {
6426 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6427}
6428
6429/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6430pub fn rect4_16_lossless_chroma_hits() -> usize {
6431 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6432}
6433
6434/// How many 16x4/4x16 strips reconstructed as intra block copy.
6435pub fn rect4_16_intrabc_hits() -> usize {
6436 RECT4_16_INTRABC_HITS.with(|c| c.get())
6437}
6438
6439/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6440pub fn reset_rect4_16_pair_hits() {
6441 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6442 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6443}
6444
6445// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6446// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6447// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6448// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6449// intra-edge filter type must come from the chroma-reference position).
6450thread_local! {
6451 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6452 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6453}
6454
6455/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6456pub fn reelc_chroma_counters() -> (usize, usize) {
6457 (
6458 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6459 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6460 )
6461}
6462
6463/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6464/// strips, chroma-reference strips, strips with a coded residual, strips
6465/// whose luma transform is split)`.
6466pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6467 (
6468 RECT4_16_HORZ_HITS.with(|c| c.get()),
6469 RECT4_16_VERT_HITS.with(|c| c.get()),
6470 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6471 RECT4_16_COEFF_HITS.with(|c| c.get()),
6472 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6473 )
6474}
6475
6476/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6477pub(crate) fn rect4_32_horz_hits() -> usize {
6478 RECT4_32_HORZ_HITS.with(|c| c.get())
6479}
6480
6481/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6482pub(crate) fn rect4_32_vert_hits() -> usize {
6483 RECT4_32_VERT_HITS.with(|c| c.get())
6484}
6485
6486/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6487pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6488 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6489}
6490
6491/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6492pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6493 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6494}
6495
6496/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6497pub(crate) fn inter_sb_horz_hits() -> usize {
6498 INTER_SB_HORZ_HITS.with(|c| c.get())
6499}
6500
6501/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6502pub(crate) fn inter_sb_vert_hits() -> usize {
6503 INTER_SB_VERT_HITS.with(|c| c.get())
6504}
6505
6506/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6507pub(crate) fn inter_sb_horz4_hits() -> usize {
6508 INTER_SB_HORZ4_HITS.with(|c| c.get())
6509}
6510
6511/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6512pub(crate) fn inter_sb_vert4_hits() -> usize {
6513 INTER_SB_VERT4_HITS.with(|c| c.get())
6514}
6515
6516// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6517// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6518// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6519// just inert-compiled. Zero forever on a passing gate means that gate's
6520// stream never carries `delta_q_present=1` through a rect64 block.
6521thread_local! {
6522 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6523 const { std::cell::Cell::new(0) };
6524}
6525
6526/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6527#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6528pub(crate) fn rect64_qidx_drift_hits() -> usize {
6529 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6530}
6531
6532// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6533// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6534// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6535// free-partition gate's proof this round's arms actually fired.
6536thread_local! {
6537 static PARTAB_HITS: std::cell::Cell<usize> =
6538 const { std::cell::Cell::new(0) };
6539}
6540
6541/// Current value of [`PARTAB_HITS`].
6542#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6543pub(crate) fn partab_hits() -> usize {
6544 PARTAB_HITS.with(|c| c.get())
6545}
6546
6547// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6548// one counter per arm rather than one shared total -- the gate hard-asserts
6549// each of these individually nonzero so a recipe that only ever fires
6550// HORZ_A can't silently stand in for the whole set.
6551thread_local! {
6552 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6553 const { std::cell::Cell::new(0) };
6554 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6555 const { std::cell::Cell::new(0) };
6556 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6557 const { std::cell::Cell::new(0) };
6558 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6559 const { std::cell::Cell::new(0) };
6560}
6561
6562/// Current value of [`INTRA_HORZ_A_HITS`].
6563#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6564pub(crate) fn intra_horz_a_hits() -> usize {
6565 INTRA_HORZ_A_HITS.with(|c| c.get())
6566}
6567/// Current value of [`INTRA_HORZ_B_HITS`].
6568#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6569pub(crate) fn intra_horz_b_hits() -> usize {
6570 INTRA_HORZ_B_HITS.with(|c| c.get())
6571}
6572/// Current value of [`INTRA_VERT_A_HITS`].
6573#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6574pub(crate) fn intra_vert_a_hits() -> usize {
6575 INTRA_VERT_A_HITS.with(|c| c.get())
6576}
6577/// Current value of [`INTRA_VERT_B_HITS`].
6578#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6579pub(crate) fn intra_vert_b_hits() -> usize {
6580 INTRA_VERT_B_HITS.with(|c| c.get())
6581}
6582
6583// How many [`read_inter_compound_mode`] reads actually happened
6584// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6585// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6586// mvstack build), not just that `comp_mode` fired. Still refused right
6587// after (no MV assignment or MC wired), so this only counts attempted
6588// reads.
6589thread_local! {
6590 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6591 const { std::cell::Cell::new(0) };
6592}
6593
6594/// Current value of [`COMPOUND_MODE_HITS`].
6595#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6596pub(crate) fn compound_mode_hits() -> usize {
6597 COMPOUND_MODE_HITS.with(|c| c.get())
6598}
6599
6600/// How many query blocks folded in at least one temporal MV candidate
6601/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6602/// temporal-MV gate's own firing counter (lane-av1tmvp).
6603///
6604/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6605/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6606/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6607/// counter compiles and the projection math it counts is unit-tested
6608/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6609/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6610/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6611/// against any real stream today. See the module doc on
6612/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6613#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6614pub(crate) fn tmv_hits() -> usize {
6615 crate::mvstack::tmv_hits()
6616}
6617
6618/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6619/// produced on this thread, the 10-bit inter gate's firing proof.
6620#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6621pub(crate) fn inter_pred_hits() -> usize {
6622 crate::mc::inter_pred_hits()
6623}
6624
6625/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6626/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6627/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6628/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6629/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6630/// needs to turn a query block's own resolved `ref_frame` into
6631/// `TplArgs::cur_offset_0` (spec 7.9.3).
6632pub(crate) struct TplFrameArgs<'a> {
6633 pub field: &'a crate::motion_field::TplField,
6634 pub order_hint_bits: u32,
6635 pub order_hint: u32,
6636 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6637 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6638 /// frame's own `ref_frame_idx` names for each single reference.
6639 pub ref_order_hints: [u32; 7],
6640}
6641
6642/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6643/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6644/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6645/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6646/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6647/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6648/// cell straddles two different blocks' values.
6649#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6650pub(crate) fn build_motion_field(
6651 grid: &MiGrid,
6652 mi_cols: usize,
6653 mi_rows: usize,
6654 order_hint: u32,
6655 order_hint_bits: u32,
6656 ref_order_hints: [u32; 7],
6657 fctx: &FrameCtx,
6658) -> crate::motion_field::MotionField {
6659 let mut field =
6660 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6661 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6662 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6663 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6664 // referencing one stores only its OTHER side's mv. With
6665 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6666 // nothing is skipped.
6667 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6668 // only on the reference frame, so it is 7 table lookups per frame instead
6669 // of two per inter unit.
6670 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6671 let i = rf.wrapping_sub(LAST_FRAME as usize);
6672 order_hint_bits != 0
6673 && i < 7
6674 && (crate::motion_field::get_relative_dist(
6675 order_hint_bits,
6676 ref_order_hints[i],
6677 order_hint,
6678 ) > 0
6679 || ref_order_hints[i] == order_hint)
6680 });
6681 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6682 // capped at 12 bits per component; a longer one is not stored at all.
6683 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6684 let (cols, rows, cells) = field.cells_mut();
6685 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6686 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6687 // `row` writes cell row `row / 2`).
6688 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6689 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6690 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6691 for col in 0..mi_cols {
6692 let Some(info) = grid.get_frame(row, col) else {
6693 continue;
6694 };
6695 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6696 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6697 // so an intra block -- or an inter block whose every slot is on the
6698 // other side / over the limit -- wipes what an earlier block wrote
6699 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6700 // share a cell).
6701 if !info.is_inter {
6702 out[col / 2] = None;
6703 continue;
6704 }
6705 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6706 // qualifying one wins -- a compound block stores its second
6707 // reference's mv, never its first (unless the second is on the
6708 // other side or over the limit). Storing slot 0 unconditionally
6709 // put the wrong (mv, ref_frame_offset) pair in every compound
6710 // block's cell, which a later frame's temporal candidate then
6711 // projected with the wrong reference distance.
6712 let mut saved: Option<crate::motion_field::SavedMv> = None;
6713 for (rf, mv) in [
6714 (info.ref_frame, Some(mv32(info.mv))),
6715 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6716 ] {
6717 let (Some(mv), true) = (mv, rf > 0) else {
6718 continue;
6719 };
6720 if other_side[rf as usize] {
6721 continue;
6722 }
6723 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6724 continue;
6725 }
6726 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6727 }
6728 out[col / 2] = saved;
6729 }
6730 }
6731 };
6732 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6733 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6734 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6735 let bands = crate::par::bands(rows, crate::par::filter_threads());
6736 if bands.len() <= 1 {
6737 fill(0, rows, cells);
6738 } else {
6739 let shared = crate::par::Shared::new(cells);
6740 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6741 // SAFETY: cell rows `r0..r1` are this band's alone.
6742 let cells = unsafe { shared.get() };
6743 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6744 });
6745 }
6746 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6747 eprintln!("EC_TPL_SAVED oh={order_hint}");
6748 for (r, row) in field.occupancy().iter().enumerate() {
6749 eprintln!("EC_TPL_SAVED r{r} {row}");
6750 }
6751 }
6752 field
6753}
6754
6755/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
6756/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
6757#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6758pub(crate) fn ref_hits(ref_frame: i8) -> usize {
6759 let c = match ref_frame {
6760 LAST2_FRAME => &LAST2_HITS,
6761 LAST3_FRAME => &LAST3_HITS,
6762 GOLDEN_FRAME => &GOLDEN_HITS,
6763 BWDREF_FRAME => &BWDREF_HITS,
6764 ALTREF2_FRAME => &ALTREF2_HITS,
6765 ALTREF_FRAME => &ALTREF_HITS,
6766 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
6767 };
6768 c.with(|v| v.get())
6769}
6770
6771/// The sequence header's `enable_intra_edge_filter`, set once per
6772/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
6773/// own read of it, kept off the call stack (see that function's own doc
6774/// comment for why) rather than threaded through every `read_plane`/
6775/// `decode_block`/`decode_leaf8` call between here and there.
6776
6777/// Set [`ENABLE_EDGE_FILTER`] for this thread.
6778///
6779/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
6780/// never did -- so an inter frame's intra blocks read whatever value the last
6781/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
6782/// harmless (its own key frame sets it first), but a caller that decodes an
6783/// inter frame directly, or a test harness running several streams on one
6784/// thread, inherits a foreign sequence's bit: decode stops being a pure
6785/// function of the bitstream. `decode_stream` now calls this once per stream
6786/// from the sequence header, which covers every frame including inter ones.
6787pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
6788 fctx.enable_edge_filter.with(|f| f.set(value));
6789}
6790
6791/// Current value of [`ANGLE_DELTA_HITS`].
6792#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6793pub(crate) fn angle_delta_hits() -> usize {
6794 ANGLE_DELTA_HITS.with(|c| c.get())
6795}
6796
6797/// Current value of [`TX_CLASS1_HITS`].
6798#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6799pub(crate) fn tx_class1_hits() -> usize {
6800 TX_CLASS1_HITS.with(|c| c.get())
6801}
6802
6803// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
6804// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
6805// bottom) this thread's decode actually reconstructed -- the same
6806// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
6807// genuinely exercised the sub-8x8 leaf path rather than every attempt
6808// coincidentally landing on `PARTITION_NONE`.
6809thread_local! {
6810 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6811 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
6812 /// sub-blocks (lane-intersub8).
6813 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6814 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
6815 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
6816 /// `[1] = VERT` (two BLOCK_4X8).
6817 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
6818 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
6819 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
6820 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
6821 /// MIXED groups whose chroma reference is INTER while its sibling is
6822 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
6823 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
6824 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
6825 /// so only this cell separates the split arm from the HORZ/VERT one).
6826 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
6827}
6828
6829/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
6830/// mixed groups, split 4x4 leaves)`.
6831pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
6832 SUB8_INTRA_RECT_HITS.with(|c| {
6833 let h = c.get();
6834 (h[0], h[1], h[2], h[3], h[4])
6835 })
6836}
6837
6838/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
6839pub fn sub8_inter_rect_hits() -> (usize, usize) {
6840 SUB8_INTER_RECT_HITS.with(|c| {
6841 let h = c.get();
6842 (h[0], h[1])
6843 })
6844}
6845
6846// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
6847// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
6848// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
6849// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
6850// (b) was 0 for every stream before this round -- the leaf path never touched
6851// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
6852// filtered where libaom skips it. A gate asserts both are non-zero.
6853thread_local! {
6854 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6855 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6856 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
6857 // crosses the cropped frame edge -- the only units for which "clamp at
6858 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
6859 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
6860 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
6861 // whose width or height is not a multiple of 8 is the only shape that
6862 // produces one; the straddling-band gate arms assert it grew.
6863 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6864 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
6865 // (see `Neighbours::skip_written`).
6866 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6867 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
6868 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
6869 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
6870 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
6871 // 8-tall strip pair where only one half is skip must still be FILTERED.
6872 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6873 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6874}
6875
6876/// Current value of `RECT_SKIP_BAND_HITS`.
6877pub fn rect_skip_band_hits() -> usize {
6878 RECT_SKIP_BAND_HITS.with(|c| c.get())
6879}
6880
6881/// Current value of `CDEF_MIXED_SKIP_UNITS`.
6882pub fn cdef_mixed_skip_units() -> usize {
6883 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
6884}
6885
6886/// Current value of `CDEF_SKIPPED_UNITS`.
6887#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6888pub(crate) fn cdef_skipped_units() -> usize {
6889 CDEF_SKIPPED_UNITS.with(|c| c.get())
6890}
6891
6892/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
6893/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
6894pub fn cdef_unwritten_skip_units() -> usize {
6895 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
6896}
6897
6898/// Current value of `INTER8_SKIP_BAND_HITS`.
6899#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6900pub(crate) fn inter8_skip_band_hits() -> usize {
6901 INTER8_SKIP_BAND_HITS.with(|c| c.get())
6902}
6903
6904/// Current value of `CDEF_STRADDLE_UNITS`.
6905#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6906pub(crate) fn cdef_straddle_units() -> usize {
6907 CDEF_STRADDLE_UNITS.with(|c| c.get())
6908}
6909
6910/// Current value of [`SUB8_SPLIT_HITS`].
6911#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6912pub(crate) fn sub8_split_hits() -> usize {
6913 SUB8_SPLIT_HITS.with(|c| c.get())
6914}
6915
6916/// Current value of [`SUB8_INTER_SPLIT_HITS`].
6917pub fn sub8_inter_split_hits() -> usize {
6918 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
6919}
6920
6921// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
6922// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
6923// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
6924// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
6925// first sub-block's type is never the one). Reading it off sub-block 0
6926// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
6927// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
6928// see this rule through this counter.
6929thread_local! {
6930 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6931}
6932
6933/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
6934pub fn sub8_chroma_tx_from_ref_hits() -> usize {
6935 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
6936}
6937
6938fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
6939 if coeffs && first_sub != chroma_ref {
6940 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
6941 }
6942}
6943
6944// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
6945// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
6946// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
6947// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
6948// asserts on these two rather than a plain leaf count.
6949thread_local! {
6950 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6951 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6952 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
6953 /// two 4x4 transform units, predicted one after the other. A separate
6954 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
6955 /// the gate can prove THIS path fired.
6956 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6957 /// 16x8/8x16 intra strips whose prediction actually read past the block's
6958 /// own width (above-right) or height (below-left) -- the samples
6959 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
6960 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
6961 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6962 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
6963 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
6964 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6965}
6966
6967/// Current value of [`RECT8_SPLIT_TX_HITS`].
6968#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6969pub(crate) fn rect8_split_tx_hits() -> usize {
6970 RECT8_SPLIT_TX_HITS.with(|c| c.get())
6971}
6972
6973/// Current value of [`RECT_STRIP_PRED_HITS`].
6974#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6975pub(crate) fn rect_strip_pred_hits() -> usize {
6976 RECT_STRIP_PRED_HITS.with(|c| c.get())
6977}
6978
6979/// Current value of [`RECT_STRIP_REACH_HITS`].
6980#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6981pub(crate) fn rect_strip_reach_hits() -> usize {
6982 RECT_STRIP_REACH_HITS.with(|c| c.get())
6983}
6984
6985/// Current value of [`TX4X8_CODED_HITS`].
6986#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6987pub(crate) fn tx4x8_coded_hits() -> usize {
6988 TX4X8_CODED_HITS.with(|c| c.get())
6989}
6990
6991/// Current value of [`TX8X4_CODED_HITS`].
6992#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6993pub(crate) fn tx8x4_coded_hits() -> usize {
6994 TX8X4_CODED_HITS.with(|c| c.get())
6995}
6996
6997// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
6998// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
6999// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
7000// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
7001// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
7002// (`eob_pt_{16,64,128,256}_chroma_class1`).
7003thread_local! {
7004 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
7005 const { std::cell::Cell::new(0) };
7006}
7007
7008/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
7009#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7010pub(crate) fn chroma_eob_class1_hits() -> usize {
7011 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
7012}
7013
7014/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
7015/// `tx_type` put this block's `eob_pt` on the class-1 row.
7016fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
7017 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
7018 hit!(CHROMA_EOB_CLASS1_HITS);
7019 }
7020}
7021
7022// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
7023// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
7024// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
7025// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
7026// looked identical to a same-plane disagreement. Set by `exec_intra` (the
7027// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
7028// by the `EC_PRED` rung, so it cannot change a decode.
7029thread_local! {
7030 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7031}
7032
7033/// The plane index the `EC_PRED` rung prints as `plane=`.
7034fn recon_plane() -> usize {
7035 RECON_PLANE.with(std::cell::Cell::get)
7036}
7037
7038/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
7039/// either of its two early returns.
7040struct PlaneGuard(usize);
7041impl Drop for PlaneGuard {
7042 fn drop(&mut self) {
7043 RECON_PLANE.with(|c| c.set(self.0));
7044 }
7045}
7046
7047const SUB_MI: u32 = 4;
7048const MI: usize = 4;
7049const SB: usize = 64;
7050/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
7051/// (tile start, superblock-row start).
7052///
7053/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
7054/// `av1_get_partition_plane_context` reads its own zero-initialised
7055/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
7056/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
7057/// (64), which reads identically at every level up to 64x64 but sets the bit
7058/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
7059/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
7060/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
7061const NO_NEIGHBOUR_SIDE: usize = 128;
7062const BLOCK: usize = 32;
7063const SUB: usize = 16;
7064const TX32: usize = 32;
7065const TX16: usize = 16;
7066const TX8: usize = 8;
7067const TX4: usize = 4;
7068const DC_PRED: usize = 0;
7069/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7070/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7071/// constant.
7072const V_PRED: usize = 1;
7073const H_PRED: usize = 2;
7074/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7075/// `Fimode_To_Intradir`, libaom `blockd.h`).
7076const D157_PRED: usize = 6;
7077/// The last directional mode, `D67_PRED`.
7078const D67_PRED: usize = 8;
7079/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7080/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7081/// codes anything else, so this decoder never reads anything else either.
7082const ANGLE_DELTA_ZERO: usize = 3;
7083const NUM_BASE_LEVELS: i32 = 2;
7084const COEFF_BASE_RANGE: i32 = 12;
7085const BR_STEP: i32 = 3;
7086const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7087
7088/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7089/// whose probability mass a superblock or block half outside the frame
7090/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7091/// duplicated here (that module is another lane's territory this round) and
7092/// kept in step with it by the byte-exact round-trip tests below rather than
7093/// by sharing code.
7094const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7095const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7096
7097fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7098 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7099 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7100 }
7101}
7102
7103fn element_prob(cdf: &[u16], element: usize) -> u16 {
7104 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7105}
7106
7107/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7108/// with: the mass of `elements` becomes the probability of the one partition
7109/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7110/// (the encoder's non-adapting counterpart to this read).
7111fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7112 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7113 [32768 - split, 32768, 0]
7114}
7115
7116fn unsupported(what: impl Into<String>) -> Error {
7117 Error::unsupported("AV1 tile", what.into())
7118}
7119
7120/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7121/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7122/// same rule.
7123pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7124 match base_q_idx {
7125 0..=20 => 0,
7126 21..=60 => 1,
7127 61..=120 => 2,
7128 _ => 3,
7129 }
7130}
7131
7132/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7133/// [`crate::tile`]'s writer generates its scan tables with.
7134fn default_scan(side: usize) -> &'static [u16] {
7135 // One table per transform side (4/8/16/32), built once: this used to be a
7136 // fresh heap allocation plus the whole anti-diagonal walk on every
7137 // transform block read.
7138 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7139 [
7140 default_scan_gen(4),
7141 default_scan_gen(8),
7142 default_scan_gen(16),
7143 default_scan_gen(32),
7144 ]
7145 });
7146 assert!(
7147 matches!(side, 4 | 8 | 16 | 32),
7148 "no default scan for a {side}-point transform"
7149 );
7150 &SCANS[side.trailing_zeros() as usize - 2]
7151}
7152
7153fn default_scan_gen(side: usize) -> Vec<u16> {
7154 let mut scan = Vec::with_capacity(side * side);
7155 for d in 0..(2 * side - 1) {
7156 let lo = d.saturating_sub(side - 1);
7157 let hi = d.min(side - 1);
7158 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7159 if d % 2 == 0 {
7160 scan.extend(diagonal.rev());
7161 } else {
7162 scan.extend(diagonal);
7163 }
7164 }
7165 scan
7166}
7167
7168/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7169/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7170/// in, instead of the default zigzag. libaom's own tables are keyed by a
7171/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7172/// physically column-major level buffer, but they decompose to the exact
7173/// same (row, col) walk as a flat row-major traversal of *our* row-major
7174/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7175/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7176/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7177/// transposed (column 0 down every row, then column 1, ...).
7178pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7179 class_scan_table_wh(side, side, class)
7180}
7181
7182/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7183/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7184/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7185/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7186/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7187/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7188fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7189 match class {
7190 TxClass::Vert => (0..(w * h) as u16).collect(),
7191 TxClass::Horiz => (0..w)
7192 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7193 .collect(),
7194 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7195 }
7196}
7197
7198fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7199 match scan_idx {
7200 0 => 0,
7201 i if i <= area / 8 => 1,
7202 i if i <= area / 4 => 2,
7203 _ => 3,
7204 }
7205}
7206
7207/// One cell of [`read_coeffs`]'s level buffer.
7208///
7209/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7210/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7211/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7212/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7213/// zero cells instead of needing the `row >= side || col >= side` edge test
7214/// this used to run five times per coefficient. Nothing writes a padding
7215/// cell, so the values are the same zeros the test returned.
7216#[inline]
7217fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7218 grid[row * stride + col] as i32
7219}
7220
7221/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7222/// `txb_common.h`): everything but the two lone-axis-identity types this
7223/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7224#[derive(Clone, Copy, PartialEq, Eq)]
7225pub(crate) enum TxClass {
7226 TwoD,
7227 Horiz,
7228 Vert,
7229}
7230
7231impl TxClass {
7232 pub(crate) fn of(tx_type: TxType) -> Self {
7233 match tx_type {
7234 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7235 // key on axis alone -- FLIPADST is still ADST for this purpose.
7236 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7237 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7238 _ => Self::TwoD,
7239 }
7240 }
7241}
7242
7243/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7244/// table (indexed by the position along the transform's *coded* axis --
7245/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7246/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7247/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7248pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7249 match i {
7250 0 => 26,
7251 1 => 31,
7252 _ => 36,
7253 }
7254}
7255
7256fn base_ctx(
7257 grid: &[u8],
7258 stride: usize,
7259 row: usize,
7260 col: usize,
7261 class: TxClass,
7262 rect_shape: Option<(usize, usize)>,
7263) -> usize {
7264 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7265 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7266 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7267 // position through the full 1D neighbour sum and offset table. Skipping
7268 // that for every class desynced the last (DC) coefficient of a
7269 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7270 // 0, which then read one extra `BR` symbol at the max and forced a
7271 // spurious third Golomb call).
7272 if class == TxClass::TwoD && row == 0 && col == 0 {
7273 return 0;
7274 }
7275 let offsets: [(usize, usize); 5] = match class {
7276 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7277 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7278 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7279 };
7280 let mag: i32 = offsets
7281 .iter()
7282 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7283 .sum();
7284 let ctx = ((mag + 1) >> 1).min(4) as usize;
7285 match class {
7286 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7287 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7288 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7289 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7290 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7291 // strip, which own a genuinely different table from the square one
7292 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7293 // square table vs the real ctx 13 the rect table gives).
7294 TxClass::TwoD => {
7295 // lane-rectsplit r4: apply libaom's GENERATING RULE
7296 // (`txb_common.h:199-209`) directly instead of indexing the
7297 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7298 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7299 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7300 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7301 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7302 // transcriptions are `[col][row]` and this read had them as
7303 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7304 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7305 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7306 // pins the rule against the tables over their whole 5x5 domain.
7307 if let Some((w, h)) = rect_shape {
7308 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7309 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7310 }
7311 if w < h && row < 2 {
7312 return ctx + 11;
7313 }
7314 if w > h && col < 2 {
7315 return ctx + 16;
7316 }
7317 }
7318 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7319 }
7320 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7321 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7322 }
7323}
7324
7325/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7326/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7327/// function of the tx class alone, which is fixed for a whole transform unit,
7328/// so resolving it once per unit takes the class match and the `(dr, dc)`
7329/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7330/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7331/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7332/// original `(dr, dc)` form.
7333fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7334 match class {
7335 TxClass::TwoD => (
7336 [stride, 1, stride + 1, 2 * stride, 2],
7337 [stride, 1, stride + 1],
7338 ),
7339 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7340 TxClass::Vert => (
7341 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7342 [stride, 1, 2 * stride],
7343 ),
7344 }
7345}
7346
7347/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7348/// neighbours) + 1) >> 1`, clamped to 4.
7349#[inline(always)]
7350fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7351 let mut mag = 0u32;
7352 for &t in taps {
7353 mag += u32::from(grid[idx + t]).min(3);
7354 }
7355 (((mag + 1) >> 1) as usize).min(4)
7356}
7357
7358/// [`br_ctx`]'s neighbour sum, off flat taps.
7359#[inline(always)]
7360fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7361 let mut mag = 0u32;
7362 for &t in taps {
7363 mag += u32::from(grid[idx + t]);
7364 }
7365 (((mag + 1) >> 1) as usize).min(6)
7366}
7367
7368/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7369/// origin-offset tail the two coefficient readers state inline; kept as the
7370/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7371/// flat one against.
7372#[cfg(test)]
7373fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7374 let extra = match class {
7375 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7376 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7377 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7378 };
7379 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7380 let mag = (((mag + 1) >> 1).min(6)) as usize;
7381 if row == 0 && col == 0 {
7382 return mag;
7383 }
7384 let near_origin = match class {
7385 TxClass::TwoD => row < 2 && col < 2,
7386 TxClass::Horiz => col == 0,
7387 TxClass::Vert => row == 0,
7388 };
7389 if near_origin { mag + 7 } else { mag + 14 }
7390}
7391
7392/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7393/// transposed from libaom's column-major buffer into this decoder's row-major
7394/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7395/// against the real table). Not the square zigzag formula generalized to
7396/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7397const SCAN_32X16: [u16; 512] = [
7398 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7399 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7400 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7401 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7402 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7403 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7404 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7405 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7406 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7407 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7408 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7409 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7410 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7411 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7412 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7413 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7414 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7415 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7416 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7417 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7418 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7419 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7420 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7421 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7422 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7423 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7424 510, 479, 511,
7425];
7426
7427/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7428/// [`SCAN_32X16`]'s doc comment).
7429const SCAN_16X32: [u16; 512] = [
7430 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,
7431 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7432 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7433 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7434 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7435 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7436 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7437 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7438 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7439 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7440 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7441 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7442 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7443 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7444 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7445 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7446 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7447 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7448 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7449 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7450 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7451 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7452 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7453 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7454 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7455 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7456];
7457
7458/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7459/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7460/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7461/// the same source).
7462const SCAN_4X8: [u16; 32] = [
7463 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,
7464 23, 26, 29, 27, 30, 31,
7465];
7466
7467/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7468const SCAN_8X4: [u16; 32] = [
7469 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,
7470 29, 22, 15, 30, 23, 31,
7471];
7472
7473/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7474/// [`SCAN_32X16`]'s doc comment).
7475const SCAN_16X8: [u16; 128] = [
7476 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,
7477 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7478 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7479 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7480 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7481 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7482];
7483
7484/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7485/// [`SCAN_32X16`]'s doc comment).
7486const SCAN_8X16: [u16; 128] = [
7487 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,
7488 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7489 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7490 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7491 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7492 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7493];
7494
7495/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7496/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7497/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7498/// scans column-major (`p = col * height + row`), so a naive copy of
7499/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7500/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7501/// are byte-identical to this decoder's [`SCAN_8X16`].
7502const SCAN_32X8: [u16; 256] = [
7503 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7504 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7505 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7506 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7507 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7508 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7509 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7510 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7511 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7512 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7513 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7514 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7515 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7516];
7517/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7518/// 16x64 `PARTITION_VERT_4` strip).
7519const SCAN_8X32: [u16; 256] = [
7520 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,
7521 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7522 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7523 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7524 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7525 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7526 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7527 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7528 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7529 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7530 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7531 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7532 239, 246, 253, 247, 254, 255,
7533];
7534/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7535/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7536/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7537/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7538/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7539/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7540/// were emitted -- a naive copy installs the transpose (class
7541/// reference-layout-not-spec).
7542const SCAN_16X4: [u16; 64] = [
7543 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,
7544 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7545 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7546];
7547/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7548/// 8x32 `PARTITION_VERT_4` strip).
7549const SCAN_4X16: [u16; 64] = [
7550 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,
7551 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7552 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7553];
7554
7555/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7556/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7557/// padding already holds.
7558#[inline]
7559fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7560 grid[row * stride + col] as i32
7561}
7562
7563/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7564/// the rect generalization is libaom's own comment in
7565/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7566/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7567/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7568/// [`decode_block_rect`] codes (see that function's own doc comment).
7569fn base_ctx_rect(
7570 grid: &[u8],
7571 stride: usize,
7572 w: usize,
7573 h: usize,
7574 row: usize,
7575 col: usize,
7576 class: TxClass,
7577) -> usize {
7578 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7579 // the 2D class short-circuits the DC position.
7580 if class == TxClass::TwoD && row == 0 && col == 0 {
7581 return 0;
7582 }
7583 let offsets: [(usize, usize); 5] = match class {
7584 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7585 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7586 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7587 };
7588 let mag: i32 = offsets
7589 .iter()
7590 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7591 .sum();
7592 let ctx = ((mag + 1) >> 1).min(4) as usize;
7593 match class {
7594 TxClass::TwoD => {
7595 if w < h && row < 2 {
7596 return ctx + 11;
7597 }
7598 if w > h && col < 2 {
7599 return ctx + 16;
7600 }
7601 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7602 }
7603 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7604 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7605 // position along one axis only).
7606 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7607 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7608 }
7609}
7610
7611/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7612/// neighbour-offset math itself is shape-independent, only the boundary
7613/// clamp needs the real bound in each axis.
7614/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7615/// its body was character-for-character [`br_ctx`]'s, which
7616/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7617#[cfg(test)]
7618fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7619 let extra = match class {
7620 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7621 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7622 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7623 };
7624 let mag = neighbour_rect(grid, stride, row + 1, col)
7625 + neighbour_rect(grid, stride, row, col + 1)
7626 + extra;
7627 let mag = (((mag + 1) >> 1).min(6)) as usize;
7628 if row == 0 && col == 0 {
7629 return mag;
7630 }
7631 let near_origin = match class {
7632 TxClass::TwoD => row < 2 && col < 2,
7633 TxClass::Horiz => col == 0,
7634 TxClass::Vert => row == 0,
7635 };
7636 if near_origin { mag + 7 } else { mag + 14 }
7637}
7638
7639fn dc_vote(dc: Option<bool>) -> i32 {
7640 match dc {
7641 None => 0,
7642 Some(true) => -1,
7643 Some(false) => 1,
7644 }
7645}
7646
7647fn dc_sign_ctx(vote: i32) -> usize {
7648 match vote.signum() {
7649 0 => 0,
7650 -1 => 1,
7651 _ => 2,
7652 }
7653}
7654
7655/// The `tx_type` a CDF symbol names, given the width of the row it was read
7656/// from.
7657///
7658/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7659/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7660/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7661/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7662/// members are a prefix of the five.
7663///
7664/// One function rather than a `match` at each reader, so
7665/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7666/// tests the mapping the readers actually use.
7667pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7668 match cdf_len {
7669 17 => TxType::from_symbol_all16(t),
7670 13 => TxType::from_symbol_set2_12(t),
7671 8 => TxType::from_symbol_set1(t),
7672 _ => TxType::from_symbol(t),
7673 }
7674}
7675
7676/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7677/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7678/// (class `table-and-reader-move-together` -- the writer picks its symbol
7679/// through the reader's own map, so the two cannot drift).
7680pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7681 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7682}
7683
7684/// The remainder of a level the base and base-range syntax could not reach
7685/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7686/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7687pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7688 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7689 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7690 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7691 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7692 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7693 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7694 // stream_can_carry` enumerates that whole value domain.
7695 //
7696 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7697 // earlier desync (class `refusal-hides-a-defect`), and every historical
7698 // instance was closed by fixing that desync -- lane-dgolomb's
7699 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7700 // Raising the cap only trades a clean refusal for silent corruption:
7701 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7702 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7703 // from a refusal into a frame-0 LUMA MISMATCH.
7704 let mut length = 1u32;
7705 while dec.literal(1) == 0 {
7706 length += 1;
7707 if length > 20 {
7708 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7709 }
7710 }
7711 let mut x = 1u32;
7712 for _ in 1..length {
7713 x = (x << 1) | dec.literal(1);
7714 }
7715 Ok(x - 1)
7716}
7717
7718/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7719/// [`crate::tile`]'s `write_eob`.
7720fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7721 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7722 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7723
7724 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7725 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7726 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7727 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7728 // `eob_multi_ctx`). Missing that split desynced the very first
7729 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7730 // against a real aomdec trace).
7731 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7732 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7733 (_, Some(class1)) => class1,
7734 };
7735 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7736 let (range, value) = dec.debug_state();
7737 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7738 }
7739 let group = dec.symbol(eob_pt) + 1;
7740 if trace {
7741 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7742 }
7743 let bits = OFFSET_BITS[group];
7744 let mut offset = 0u32;
7745 if bits > 0 {
7746 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7747 if trace {
7748 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
7749 }
7750 offset = top << (bits - 1);
7751 if bits > 1 {
7752 offset |= dec.literal(bits - 1);
7753 }
7754 }
7755 GROUP_START[group] + offset as usize
7756}
7757
7758/// One transform block's levels, the inverse of [`crate::tile`]'s
7759/// `write_coeffs`, returned as a `side * side` grid in raster order, along
7760/// with the transform type that grid was coded under (`DCT_DCT` when the
7761/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
7762/// 64-point transforms, which never code anything else).
7763///
7764/// # Errors
7765/// Returns an error if the `tx_type` symbol decodes to a value outside its
7766/// CDF's own set (a corrupt or unsupported bitstream) — every value the
7767/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
7768/// produce dispatches to a real inverse transform.
7769/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
7770/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
7771/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
7772/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
7773/// the plane's own predicted mode instead. Every entry this table can
7774/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
7775/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
7776/// table ever names), so unlike the CDF-coded luma path there is no
7777/// ext-tx-set membership check to fall back from here.
7778pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
7779 use crate::intra::{
7780 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
7781 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
7782 };
7783 match mode {
7784 DC_PRED | D45_PRED => TxType::DctDct,
7785 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
7786 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
7787 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
7788 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
7789 }
7790}
7791
7792/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
7793/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
7794/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
7795fn is_smooth_mode(mode: usize) -> bool {
7796 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
7797}
7798
7799/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
7800/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7801/// nine of them inside the base/sign loops pinned nine sets of values in the
7802/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
7803/// traffic). Out of line, the loop keeps its values in registers and the
7804/// trace output is character-for-character what it was.
7805#[cold]
7806#[inline(never)]
7807fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7808 eprintln!(
7809 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
7810 );
7811}
7812
7813#[cold]
7814#[inline(never)]
7815fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7816 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
7817}
7818
7819#[cold]
7820#[inline(never)]
7821fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
7822 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
7823}
7824
7825#[cold]
7826#[inline(never)]
7827fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
7828 let (rng, _) = dec.debug_state();
7829 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
7830}
7831
7832#[cold]
7833#[inline(never)]
7834fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
7835 let (rng, _) = dec.debug_state();
7836 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
7837}
7838
7839#[cold]
7840#[inline(never)]
7841fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
7842 let (rng, _) = dec.debug_state();
7843 eprintln!(
7844 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
7845 negative as i32
7846 );
7847}
7848
7849#[cold]
7850#[inline(never)]
7851fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
7852 let (rng, _) = dec.debug_state();
7853 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
7854}
7855
7856#[cold]
7857#[inline(never)]
7858fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
7859 let (rng, _) = dec.debug_state();
7860 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
7861}
7862
7863// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
7864#[track_caller]
7865fn read_coeffs(
7866 dec: &mut SymbolDecoder,
7867 coding: &mut TxbTables,
7868 scan: &[u16],
7869 skip_ctx: usize,
7870 sign_ctx: usize,
7871 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
7872 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
7873 // nothing at all; `DctDct` for every luma call and every chroma call at
7874 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
7875 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
7876 default_tx_type: TxType,
7877 // `Some((w, h))` with `w != h` when this read is a superblock-level
7878 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
7879 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
7880 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
7881 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
7882 // caller's block genuinely is `side` x `side`.
7883 rect_shape: Option<(usize, usize)>,
7884) -> Result<(Grid, TxType)> {
7885 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7886 let side = coding.side;
7887 // lane-av1readcensus: this unit's own entry state, so the census line
7888 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
7889 // (which prints `r->ec.rng` before the same `txb_skip` read).
7890 let census_entry_rng = dec.debug_state().0;
7891 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
7892 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7893 let (range, value) = dec.debug_state();
7894 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
7895 }
7896 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
7897 let (range, value) = dec.debug_state();
7898 let bit = dec.debug_bitpos();
7899 eprintln!(
7900 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
7901 );
7902 }
7903 let dbg_txbskip = if coeff_trace_on() {
7904 coding.txb_skip[skip_ctx]
7905 } else {
7906 [0; 3]
7907 };
7908 let sq_bit = if coeff_trace_on() {
7909 dec.debug_bitpos()
7910 } else {
7911 0
7912 };
7913 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7914 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
7915 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
7916 // filter on it before pairing anything against the oracle.
7917 if crate::envflags::env_flag!("EC_IBCTX") {
7918 eprintln!(
7919 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
7920 coding.side,
7921 std::panic::Location::caller(),
7922 );
7923 }
7924 if coeff_trace_on() {
7925 let (rng, _) = dec.debug_state();
7926 eprintln!(
7927 "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={}",
7928 coding.side,
7929 all_zero as i32,
7930 dec.debug_bitpos()
7931 );
7932 }
7933 if crate::envflags::env_flag!("EC_AV1_TELL") {
7934 eprintln!(
7935 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
7936 all_zero as u8,
7937 dec.debug_bitpos(),
7938 dec.debug_state().0
7939 );
7940 }
7941 if trace {
7942 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
7943 }
7944 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7945 let (range, value) = dec.debug_state();
7946 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
7947 }
7948 if all_zero {
7949 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
7950 // shared zero grid instead of allocating and zeroing its own.
7951 census_unit(
7952 census_w,
7953 census_h,
7954 TxType::DctDct,
7955 0,
7956 true,
7957 census_entry_rng,
7958 dec,
7959 );
7960 return Ok((Grid::Zero(side * side), TxType::DctDct));
7961 }
7962 let mut grid = vec![0i32; side * side];
7963 let mut tx_type = default_tx_type;
7964 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
7965 // The CDF row's own width names its set (lane-cdffwd2: extended
7966 // past the original two-way intra split once wider `reduced_tx_set
7967 // == 0` inter sets joined the table): 17 slots (16 symbols) is
7968 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
7969 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
7970 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
7971 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
7972 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
7973 let len = tx_type_cdf.len();
7974 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
7975 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
7976 }
7977 let t = dec.symbol(tx_type_cdf);
7978 crate::census::tx_type(len, t);
7979 if coeff_trace_on() {
7980 let (rng, _) = dec.debug_state();
7981 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
7982 }
7983 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7984 let (range, value) = dec.debug_state();
7985 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
7986 }
7987 if trace {
7988 eprintln!("TRACE tx_type value={t} len={len}");
7989 }
7990 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
7991 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
7992 })?;
7993 }
7994
7995 let class = TxClass::of(tx_type);
7996 if class != TxClass::TwoD {
7997 hit!(TX_CLASS1_HITS);
7998 hit!(RECT_CLASS1_HITS);
7999 }
8000 let eob = read_eob(dec, coding, class);
8001 if trace {
8002 eprintln!("TRACE eob value={eob}");
8003 }
8004 let ec_trace_coeff = coeff_trace_on();
8005 if ec_trace_coeff {
8006 let (rng, _) = dec.debug_state();
8007 let cls = match class {
8008 TxClass::TwoD => "2d",
8009 TxClass::Horiz => "horiz",
8010 TxClass::Vert => "vert",
8011 };
8012 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
8013 }
8014 let class_scan;
8015 let scan: &[u16] = if class == TxClass::TwoD {
8016 scan
8017 } else {
8018 class_scan = class_scan_table(side, class);
8019 &class_scan
8020 };
8021 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
8022 // coefficient `pos / side`, `pos % side` was a hardware divide where a
8023 // shift and a mask say the same thing, and the level buffer fits a fixed
8024 // 32x32 frame of stack instead of a heap allocation per transform block.
8025 debug_assert!(side.is_power_of_two() && side <= 32);
8026 let sh = side.trailing_zeros();
8027 let col_mask = side - 1;
8028 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
8029 // `stride = side + 4` columns and four spare rows, so the widest read
8030 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
8031 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
8032 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
8033 let stride = side + 4;
8034 let mut levels_buf = [0u8; 36 * 36];
8035 let levels = &mut levels_buf[..stride * stride];
8036 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
8037 // `pos >> sh` / `& mask` decomposition and load the level back out of the
8038 // padded frame just to skip the zeros. The base pass already knows both,
8039 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
8040 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
8041 // pass walks that list in reverse (the base pass runs in reverse scan
8042 // order, so reversing it is forward scan order: the same coefficients, in
8043 // the same order, with the same `c` the trace prints).
8044 let mut nz_buf = [0u16; 1024];
8045 let mut nz_n = 0usize;
8046 let (base_taps, br_taps) = flat_taps(stride, class);
8047 for scan_idx in (0..eob).rev() {
8048 let pos = scan[scan_idx] as usize;
8049 let (row, col) = (pos >> sh, pos & col_mask);
8050 let idx = row * stride + col;
8051 let level = if scan_idx == eob - 1 {
8052 let ctx = eob_coeff_ctx(scan_idx, side * side);
8053 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8054 if trace {
8055 trace_base_eob(scan_idx, pos, row, col, ctx, v);
8056 }
8057 v
8058 } else {
8059 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
8060 if row == 0 && col == 0 {
8061 0
8062 } else {
8063 base_mag(levels, idx, &base_taps)
8064 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8065 }
8066 } else {
8067 base_ctx(levels, stride, row, col, class, rect_shape)
8068 };
8069 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8070 if ec_trace_coeff {
8071 // `pos` in libaom's column-major `coeff_idx` convention, so
8072 // the ladder lines up with instrumented `aomdec`.
8073 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
8074 }
8075 if trace {
8076 trace_base(scan_idx, pos, row, col, ctx, v);
8077 }
8078 v
8079 };
8080 let level = if level > NUM_BASE_LEVELS {
8081 let ctx = {
8082 let mag = br_mag(levels, idx, &br_taps);
8083 if row == 0 && col == 0 {
8084 mag
8085 } else {
8086 let near_origin = match class {
8087 TxClass::TwoD => row < 2 && col < 2,
8088 TxClass::Horiz => col == 0,
8089 TxClass::Vert => row == 0,
8090 };
8091 if near_origin { mag + 7 } else { mag + 14 }
8092 }
8093 };
8094 let mut level = level;
8095 let mut sent = 0;
8096 loop {
8097 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8098 if ec_trace_coeff {
8099 // lane-leaf8tx r3: the `br` rung was missing from THIS
8100 // path's trace, so the cross-decoder range ladder was
8101 // blind to every base-range symbol and mis-reported the
8102 // first divergence (class [[gate-blind-to-feature]]).
8103 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8104 }
8105 if trace {
8106 trace_br(scan_idx, pos, row, col, ctx, k);
8107 }
8108 level += k;
8109 sent += BR_STEP;
8110 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8111 break;
8112 }
8113 }
8114 level
8115 } else {
8116 level
8117 };
8118 if ec_trace_coeff && scan_idx == eob - 1 {
8119 coeff_step_base_eob_level(dec, level);
8120 }
8121 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8122 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8123 // added in the sign pass below, straight into `grid`), so the context
8124 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8125 // byte gather (lane-coefbuf).
8126 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8127 levels[idx] = level as u8;
8128 if level != 0 {
8129 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8130 nz_n += 1;
8131 }
8132 }
8133 if ec_trace_coeff {
8134 let (rng, _) = dec.debug_state();
8135 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8136 }
8137
8138 for &packed in nz_buf[..nz_n].iter().rev() {
8139 let c = (packed >> 4) as usize;
8140 let pos = scan[c] as usize;
8141 let level = (packed & 15) as i32;
8142 let negative = if pos == 0 {
8143 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8144 if trace {
8145 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8146 }
8147 v
8148 } else {
8149 dec.literal(1) == 1
8150 };
8151 if ec_trace_coeff {
8152 coeff_step_sign(dec, c, negative);
8153 }
8154 let level = if level > MAX_BR_LEVEL {
8155 let g = read_golomb(dec)?;
8156 if trace {
8157 eprintln!("TRACE golomb pos={pos} value={g}");
8158 }
8159 level + g as i32
8160 } else {
8161 level
8162 };
8163 if ec_trace_coeff {
8164 coeff_step_post_golomb(dec, c, level);
8165 }
8166 grid[pos] = if negative { -level } else { level };
8167 }
8168 census_unit(
8169 census_w,
8170 census_h,
8171 tx_type,
8172 eob,
8173 false,
8174 census_entry_rng,
8175 dec,
8176 );
8177 Ok((Grid::Own(grid), tx_type))
8178}
8179
8180/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8181/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8182/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8183/// can ever produce, since every `tx_type` this decoder's rect sets can read
8184/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8185/// rather than guess-decode if a non-2D class ever shows up here, since
8186/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8187/// form for those.
8188
8189// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
8190// of this reader -- the only thing that identifies a unit's route. No plane is
8191// printed here: the plane is the ORACLE's side of the pairing, and a label
8192// here is one more thing that can disagree with it.
8193#[track_caller]
8194fn read_coeffs_rect(
8195 dec: &mut SymbolDecoder,
8196 coding: &mut TxbTables,
8197 scan: &[u16],
8198 w: usize,
8199 h: usize,
8200 skip_ctx: usize,
8201 sign_ctx: usize,
8202 default_tx_type: TxType,
8203 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8204 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8205 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8206 // independent lane reports.
8207 plane: usize,
8208) -> Result<(Grid, TxType)> {
8209 let rect_trace = coeff_trace_on();
8210 let entry_rng = dec.debug_state().0;
8211 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8212 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8213 // plane itself rather than inheriting whichever reader did last. The
8214 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8215 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8216 // value -- and the other plane-owning readers stamp on entry.
8217 set_census_plane(plane);
8218 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
8219 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
8220 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8221 if rect_trace {
8222 eprintln!(
8223 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
8224 all_zero as i32,
8225 dec.debug_state().0,
8226 dec.debug_bitpos()
8227 );
8228 }
8229 if ibctx_on {
8230 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
8231 // range: the only collision-free key for pairing this unit against the
8232 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
8233 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
8234 // either way, which is exactly the artifact that made an earlier
8235 // round of this lane claim a false exactness.
8236 eprintln!(
8237 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
8238 dec.debug_bitpos(),
8239 std::panic::Location::caller(),
8240 );
8241 }
8242 if all_zero {
8243 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8244 return Ok((Grid::Zero(w * h), TxType::DctDct));
8245 }
8246 let mut grid = vec![0i32; w * h];
8247 hit!(RECT_COEFF_TU_HITS);
8248 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8249 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8250 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8251 // context offsets -- both of which now have rect forms
8252 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8253 // The rect sets that carry no symbol at all still pass `None` here.
8254 let mut tx_type = default_tx_type;
8255 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8256 let len = tx_type_cdf.len();
8257 let t = dec.symbol(tx_type_cdf);
8258 crate::census::tx_type(len, t);
8259 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8260 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8261 })?;
8262 if rect_trace {
8263 eprintln!(
8264 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8265 dec.debug_state().0
8266 );
8267 }
8268 }
8269 let class = TxClass::of(tx_type);
8270 if class != TxClass::TwoD {
8271 hit!(TX_CLASS1_HITS);
8272 }
8273 let eob = read_eob(dec, coding, class);
8274 if rect_trace {
8275 eprintln!(
8276 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8277 dec.debug_state().0
8278 );
8279 }
8280 let class_scan;
8281 let scan: &[u16] = if class == TxClass::TwoD {
8282 scan
8283 } else {
8284 class_scan = class_scan_table_wh(w, h, class);
8285 &class_scan
8286 };
8287 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8288 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8289 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8290 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8291 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8292 // mask rather than a hardware divide.
8293 let stride = w + 4;
8294 let n = stride * (h + 4);
8295 if !(w.is_power_of_two() && n <= 36 * 36) {
8296 panic!("rect coeff scratch w={w} h={h} n={n}");
8297 }
8298 let (mut b96, mut b256, mut b768);
8299 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8300 let levels: &mut [u8] = if n <= 96 {
8301 b96 = [0u8; 96];
8302 &mut b96[..n]
8303 } else if n <= 256 {
8304 b256 = [0u8; 256];
8305 &mut b256[..n]
8306 } else {
8307 b768 = [0u8; 768];
8308 &mut b768[..n]
8309 };
8310 let wsh = w.trailing_zeros();
8311 let wmask = w - 1;
8312 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8313 let mut nz_buf = [0u16; 1024];
8314 let mut nz_n = 0usize;
8315 let (base_taps, br_taps) = flat_taps(stride, class);
8316 let (wlt, wgt) = (w < h, w > h);
8317 for scan_idx in (0..eob).rev() {
8318 let pos = scan[scan_idx] as usize;
8319 let (row, col) = (pos >> wsh, pos & wmask);
8320 let idx = row * stride + col;
8321 // libaom's column-major `coeff_idx`, for ladder comparison.
8322 let _apos = col * h + row;
8323 let level = if scan_idx == eob - 1 {
8324 let ctx = eob_coeff_ctx(scan_idx, w * h);
8325 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8326 if rect_trace {
8327 eprintln!(
8328 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8329 dec.debug_state().0
8330 );
8331 }
8332 v
8333 } else {
8334 let ctx = if class == TxClass::TwoD {
8335 if row == 0 && col == 0 {
8336 0
8337 } else {
8338 let m = base_mag(levels, idx, &base_taps);
8339 if wlt && row < 2 {
8340 m + 11
8341 } else if wgt && col < 2 {
8342 m + 16
8343 } else {
8344 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8345 }
8346 }
8347 } else {
8348 base_ctx_rect(levels, stride, w, h, row, col, class)
8349 };
8350 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8351 if rect_trace {
8352 eprintln!(
8353 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8354 dec.debug_state().0
8355 );
8356 }
8357 v
8358 };
8359 let level = if level > NUM_BASE_LEVELS {
8360 let ctx = {
8361 let mag = br_mag(levels, idx, &br_taps);
8362 if row == 0 && col == 0 {
8363 mag
8364 } else {
8365 let near_origin = match class {
8366 TxClass::TwoD => row < 2 && col < 2,
8367 TxClass::Horiz => col == 0,
8368 TxClass::Vert => row == 0,
8369 };
8370 if near_origin { mag + 7 } else { mag + 14 }
8371 }
8372 };
8373 let mut level = level;
8374 let mut sent = 0;
8375 loop {
8376 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8377 if rect_trace {
8378 eprintln!(
8379 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8380 dec.debug_state().0
8381 );
8382 }
8383 level += k;
8384 sent += BR_STEP;
8385 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8386 break;
8387 }
8388 }
8389 level
8390 } else {
8391 level
8392 };
8393 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8394 levels[idx] = level as u8;
8395 if level != 0 {
8396 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8397 nz_n += 1;
8398 }
8399 if rect_trace {
8400 let (rng, _) = dec.debug_state();
8401 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
8402 }
8403 }
8404 if rect_trace {
8405 let (rng, _) = dec.debug_state();
8406 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8407 }
8408 for &packed in nz_buf[..nz_n].iter().rev() {
8409 let pos = scan[(packed >> 4) as usize] as usize;
8410 let level = (packed & 15) as i32;
8411 let negative = if pos == 0 {
8412 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8413 } else {
8414 dec.literal(1) == 1
8415 };
8416 if rect_trace {
8417 let (rng, _) = dec.debug_state();
8418 eprintln!(
8419 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8420 u8::from(negative)
8421 );
8422 }
8423 let level = if level > MAX_BR_LEVEL {
8424 let g = read_golomb(dec)?;
8425 level + g as i32
8426 } else {
8427 level
8428 };
8429 grid[pos] = if negative { -level } else { level };
8430 }
8431 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8432 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8433 // grids differ is a reader defect, one whose grids agree is a transform
8434 // defect.
8435 if crate::envflags::env_flag!("EC_DQCOEFF") {
8436 let nz: Vec<String> = grid
8437 .iter()
8438 .enumerate()
8439 .filter(|&(_, &v)| v != 0)
8440 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8441 .collect();
8442 eprintln!(
8443 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8444 nz.join(",")
8445 );
8446 }
8447 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8448 Ok((Grid::Own(grid), tx_type))
8449}
8450
8451/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8452/// [`read_plane`] family already has.
8453///
8454/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8455/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8456/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8457/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8458/// enforces that for every strip that reads its chroma through it, but the rect
8459/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8460/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8461/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8462/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8463/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8464/// symbol -- and therefore every later pixel -- is decoded from the wrong
8465/// place, without ever tripping a refusal (the desynced values stay inside
8466/// every coded alphabet).
8467fn read_chroma_coeffs_rect(
8468 dec: &mut SymbolDecoder,
8469 coding: &mut TxbTables,
8470 scan: &[u16],
8471 w: usize,
8472 h: usize,
8473 skip_ctx: usize,
8474 sign_ctx: usize,
8475 default_tx_type: TxType,
8476 fctx: &crate::decode::FrameCtx,
8477 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8478 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8479 // V-plane read was indistinguishable from a luma one in the log).
8480 plane: usize,
8481) -> Result<(Grid, TxType)> {
8482 if mono(fctx) {
8483 return Ok((Grid::Zero(w * h), TxType::DctDct));
8484 }
8485 read_coeffs_rect(
8486 dec,
8487 coding,
8488 scan,
8489 w,
8490 h,
8491 skip_ctx,
8492 sign_ctx,
8493 default_tx_type,
8494 plane,
8495 )
8496}
8497
8498/// What one coded block leaves behind for the blocks that read it as a
8499/// neighbour: whether it coded anything at all, and the sign of its DC —
8500/// [`crate::tile`]'s own private `Neighbour`.
8501#[derive(Clone, Copy, Default)]
8502struct Neighbour {
8503 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8504 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8505 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8506 /// boolean (`level != 0`) is enough for every context this decoder read
8507 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8508 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8509 /// needs the actual magnitude tier of its above/left neighbours, not
8510 /// just whether they coded anything.
8511 level: u8,
8512 dc: Option<bool>,
8513}
8514
8515/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8516/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8517/// grid is dropped, never a panic. One `memset` per grid row instead of a
8518/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8519/// is contiguous, so this writes exactly the cells the cell loop did,
8520/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8521/// next row.
8522#[inline]
8523fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8524 let end = (start + n).min(dst.len());
8525 if start < end {
8526 dst[start..end].fill(v);
8527 }
8528}
8529
8530fn neighbour_state(grid: &[i32]) -> Neighbour {
8531 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8532 // sum has no early exit, so the 60% of units that code nothing used to
8533 // walk their whole grid here.
8534 if is_zero_grid(grid) {
8535 return Neighbour::default();
8536 }
8537 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8538 Neighbour {
8539 level: cul.min(7) as u8,
8540 dc: (grid[0] != 0).then_some(grid[0] < 0),
8541 }
8542}
8543
8544/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8545/// transform unit smaller than the block it sits in): `top`/`left` are the
8546/// above/left neighbours' magnitude tiers, each already clamped to 4.
8547pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8548 [1, 2, 2, 2, 3],
8549 [2, 4, 4, 4, 5],
8550 [2, 4, 4, 4, 5],
8551 [2, 4, 4, 4, 5],
8552 [3, 5, 5, 5, 6],
8553];
8554
8555/// The `skip` flag, its written-instrument bit, and the covering coded
8556/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8557/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8558/// nothing else, so a block's row is one fill instead of four, and the
8559/// deblocker's `pu_edge` reads origin and dims off one cache line.
8560#[derive(Clone, Copy)]
8561struct BlkCell {
8562 skip: bool,
8563 written: bool,
8564 org: [u16; 2],
8565 dim: [u8; 2],
8566}
8567
8568/// The neighbour state a block's contexts are read from — a duplicate of
8569/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8570/// territory this round), kept at the same two granularities the real writer
8571/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8572/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8573/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8574/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8575/// chroma transform straddling the true, odd-sized frame edge see its
8576/// neighbour's state clamped at its own subsampled edge rather than luma's.
8577#[derive(Clone)]
8578struct Neighbours {
8579 above: Vec<[Neighbour; 3]>,
8580 left: Vec<[Neighbour; 3]>,
8581 above_mode: Vec<usize>,
8582 left_mode: Vec<usize>,
8583 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8584 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8585 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8586 /// luma one -- the same block can (and often does) code a different
8587 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8588 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8589 /// within-block neighbour finer than this grid) is luma-only -- a known,
8590 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8591 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8592 above_uv_mode: Vec<usize>,
8593 left_uv_mode: Vec<usize>,
8594 above_side: Vec<usize>,
8595 left_side: Vec<usize>,
8596 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8597 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8598 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8599 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8600 /// array cannot tell the second leaf's partition symbol that the first
8601 /// one was coded at 8x8.
8602 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8603 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8604 above_side_mi: Vec<u8>,
8605 left_side_mi: Vec<u8>,
8606 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8607 /// / row, with the mi position it was written at
8608 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8609 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8610 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8611 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8612 /// leaf whose neighbour is another split group needs that group's leaf 3
8613 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8614 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8615 /// fall back to the coarse slot whenever the real neighbour was a block
8616 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8617 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8618 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8619 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8620 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8621 /// frame is 65536 px = 16384 mi).
8622 sub8_mode_col: Vec<(u16, u8)>,
8623 sub8_mode_row: Vec<(u16, u8)>,
8624 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8625 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8626 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8627 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8628 /// the leaf above writes the same row slot the block to the left owns.
8629 uv_mode_col: Vec<(u16, u8)>,
8630 uv_mode_row: Vec<(u16, u8)>,
8631 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8632 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8633 /// blockd.h). lane-t900 r12: the one-slot-per-column
8634 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8635 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8636 /// overwrote the row the pair's chroma-ref half then wanted to read --
8637 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8638 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8639 uv_mode_grid: Vec<u8>,
8640 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8641 /// every other band here).
8642 uv_grid_cols: usize,
8643 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
8644 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
8645 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
8646 /// the `+ss_y` read compares written by the same block?", which is the
8647 /// whole question the `+ss_y` term turns on: the term is only observable
8648 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
8649 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
8650 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
8651 /// in this tile can never be mistaken for a written one.
8652 uv_owner: Vec<u32>,
8653 /// Whether the block above/left of this column/row was coded `skip` --
8654 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8655 /// key-frame writer never tracks (its skip context is always zero); a
8656 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8657 /// `left_skip`.
8658 above_skip: Vec<bool>,
8659 left_skip: Vec<bool>,
8660 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8661 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8662 /// pixels last written over each unit by `set_txfm_ctxs`/
8663 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8664 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8665 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8666 /// array is exactly libaom's per-superblock-row reset, since each mi row
8667 /// is only ever visited inside one superblock row.
8668 above_txfm: Vec<u8>,
8669 left_txfm: Vec<u8>,
8670 /// Whether the block above/left of this column/row coded `skip_mode`
8671 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8672 /// lane-av1comp round 14.
8673 above_skip_mode: Vec<bool>,
8674 left_skip_mode: Vec<bool>,
8675 /// Whether the block above/left was coded inter -- the `is_inter`
8676 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8677 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8678 above_inter: Vec<bool>,
8679 left_inter: Vec<bool>,
8680 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8681 /// alphabet) the block above/left of this column/row coded, or `-1` for
8682 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8683 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8684 /// just "was it inter" (lane-av1refs: every inter block used to be
8685 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8686 /// enough).
8687 above_ref: Vec<i8>,
8688 left_ref: Vec<i8>,
8689 /// The block above/left's *second* reference frame when it was coded
8690 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8691 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8692 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8693 /// `i8`, once a compound `read_ref_frames` lands.
8694 /// lane-publish2 audit: the "always `None` today" note this doc used to
8695 /// carry is long stale -- compound blocks do occur, and
8696 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8697 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8698 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8699 /// [`crate::mvstack::NeighbourRef`] construction (class
8700 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8701 above_ref1: Vec<Option<i8>>,
8702 left_ref1: Vec<Option<i8>>,
8703 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8704 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8705 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8706 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8707 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8708 above_comp_group_idx: Vec<u8>,
8709 left_comp_group_idx: Vec<u8>,
8710 above_compound_idx: Vec<u8>,
8711 left_compound_idx: Vec<u8>,
8712 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8713 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8714 /// block above/left of this column/row -- spec
8715 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8716 above_filter: Vec<[u8; 2]>,
8717 left_filter: Vec<[u8; 2]>,
8718 mi_cols: usize,
8719 mi_rows: usize,
8720 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8721 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8722 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8723 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8724 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8725 /// granularity by [`apply_cdef`] since `skip` is constant across every
8726 /// mi cell one coded block covers.
8727 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8728 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8729 /// the `skip` bit at this mi cell during this frame. A fresh
8730 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8731 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8732 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
8733 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
8734 /// unobservable from the pixels alone. Counted by
8735 /// [`cdef_unwritten_skip_units`].
8736 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
8737 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
8738 /// which re-enables the loop filter at a prediction boundary between two
8739 /// skipped inter blocks (lane-mergefix r4). Written by
8740 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
8741 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
8742 /// that cell -- the other half of `pu_edge`: libaom tests the edge
8743 /// coordinate against the block's size in the FILTERED plane's own
8744 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
8745 blk_grid: Vec<BlkCell>,
8746 skip_grid_cols_mi: usize,
8747 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
8748 /// never splits a coded block's transform below its own size (round 2:
8749 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
8750 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
8751 /// edge-length lookup (`apply_deblock`).
8752 tx_grid: Vec<u8>,
8753 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
8754 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
8755 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
8756 tx_h_grid: Vec<u8>,
8757 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
8758 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
8759 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
8760 /// does NOT follow luma's `tx_depth` split, so deriving it as
8761 /// `tx_grid / 2` invented chroma transform edges the deblocker then
8762 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
8763 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
8764 /// every caller routes through.
8765 uv_tx_grid: Vec<u8>,
8766 uv_tx_h_grid: Vec<u8>,
8767 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
8768 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
8769 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
8770 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
8771 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
8772 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
8773 /// reference onto `LAST_FRAME`'s own delta).
8774 ref_grid: Vec<i8>,
8775 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
8776 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
8777 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
8778 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
8779 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
8780 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
8781 /// to know which mode produced the value.
8782 delta_lf_grid: Vec<[i8; 4]>,
8783 /// The block above/left's own palette-Y size (0 = not a palette block)
8784 /// and its base colours -- `av1_get_palette_mode_ctx`/
8785 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
8786 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
8787 above_palette_size: Vec<u8>,
8788 left_palette_size: Vec<u8>,
8789 above_palette_colors: Vec<[u16; 8]>,
8790 left_palette_colors: Vec<[u16; 8]>,
8791 /// As the four fields above, for the neighbour's own chroma (U-channel
8792 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
8793 /// palette size/colours (lane-palette2 r1).
8794 above_palette_uv_size: Vec<u8>,
8795 left_palette_uv_size: Vec<u8>,
8796 above_palette_uv_colors: Vec<[u16; 8]>,
8797 left_palette_uv_colors: Vec<[u16; 8]>,
8798 /// This tile's own top-left corner, in 4x4 mode-info units (spec
8799 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
8800 /// neighbour" check compares against this instead of literal `0`, since a
8801 /// block at the tile's own top/left edge has no usable neighbour even
8802 /// though a decoded block sits there in the picture (spec `decode_tile`'s
8803 /// per-tile `clear_above_context`/`left_available`/`up_available`).
8804 /// `0` for a single-tile frame, matching every existing caller exactly.
8805 tile_row0_mi: usize,
8806 tile_col0_mi: usize,
8807}
8808
8809#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8810impl Neighbours {
8811 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
8812 /// true (unpadded) size in 4x4 mode-info units.
8813 fn new(
8814 cols: usize,
8815 rows: usize,
8816 mi_cols: usize,
8817 mi_rows: usize,
8818 fctx: &crate::decode::FrameCtx,
8819 ) -> Self {
8820 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
8821 // neighbour state over the whole 64-row extent, past the frame's last
8822 // mi row (mi_rows 198, block rows 192..208). libaom's own context
8823 // buffers are superblock-aligned for exactly that reason
8824 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
8825 // side arrays to a superblock multiple and leave those cells unread --
8826 // every availability check uses the true `mi_rows`/`mi_cols` below.
8827 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
8828 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
8829 Self {
8830 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
8831 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
8832 above_mode: vec![DC_PRED; cols],
8833 left_mode: vec![DC_PRED; rows],
8834 above_uv_mode: vec![DC_PRED; cols],
8835 left_uv_mode: vec![DC_PRED; rows],
8836 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
8837 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
8838 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
8839 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
8840 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8841 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8842 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8843 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8844 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
8845 uv_grid_cols: cols * (SUB / MI),
8846 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
8847 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
8848 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
8849 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
8850 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
8851 // 16x16 block beside it, which a SUB-grid slot cannot name
8852 // (class context-read-from-one-cell).
8853 above_skip: vec![false; cols * (SUB / MI)],
8854 left_skip: vec![false; rows * (SUB / MI)],
8855 above_skip_mode: vec![false; cols * (SUB / MI)],
8856 left_skip_mode: vec![false; rows * (SUB / MI)],
8857 above_inter: vec![false; cols * (SUB / MI)],
8858 left_inter: vec![false; rows * (SUB / MI)],
8859 above_ref: vec![-1; cols * (SUB / MI)],
8860 left_ref: vec![-1; rows * (SUB / MI)],
8861 above_ref1: vec![None; cols * (SUB / MI)],
8862 left_ref1: vec![None; rows * (SUB / MI)],
8863 above_comp_group_idx: vec![0; cols * (SUB / MI)],
8864 left_comp_group_idx: vec![0; rows * (SUB / MI)],
8865 above_compound_idx: vec![0; cols * (SUB / MI)],
8866 left_compound_idx: vec![0; rows * (SUB / MI)],
8867 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
8868 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
8869 mi_cols,
8870 mi_rows,
8871 blk_grid: vec![
8872 BlkCell {
8873 skip: false,
8874 written: false,
8875 org: [0; 2],
8876 dim: [1; 2]
8877 };
8878 cols * (SUB / MI) * rows * (SUB / MI)
8879 ],
8880 skip_grid_cols_mi: cols * (SUB / MI),
8881 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8882 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8883 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8884 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8885 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
8886 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
8887 above_palette_size: vec![0; cols * (SUB / MI)],
8888 left_palette_size: vec![0; rows * (SUB / MI)],
8889 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8890 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8891 above_palette_uv_size: vec![0; cols * (SUB / MI)],
8892 left_palette_uv_size: vec![0; rows * (SUB / MI)],
8893 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8894 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8895 tile_row0_mi: 0,
8896 tile_col0_mi: 0,
8897 }
8898 }
8899
8900 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
8901 /// tile's own column span (`col1_mi` exclusive), plus recording
8902 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
8903 /// availability check below. Left context resets every superblock row
8904 /// regardless of tile ([`Self::start_row`], already called once per SB
8905 /// row by every caller) so it needs no tile-specific reset here.
8906 fn start_tile(
8907 &mut self,
8908 row0_mi: usize,
8909 col0_mi: usize,
8910 col1_mi: usize,
8911 fctx: &crate::decode::FrameCtx,
8912 ) {
8913 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
8914 // are tile-relative, same as every other neighbour lookup here.
8915 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
8916 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
8917 // tile writes, so the `+ss_y` read's "different block?" probe never
8918 // compares against a cell a previous tile left behind.
8919 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
8920 self.tile_row0_mi = row0_mi;
8921 self.tile_col0_mi = col0_mi;
8922 let end = col1_mi.min(self.above.len());
8923 for i in col0_mi.min(end)..end {
8924 self.above[i] = Default::default();
8925 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
8926 }
8927 let (sc0, sc1) = (
8928 col0_mi / (SUB / MI),
8929 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
8930 );
8931 for i in sc0.min(sc1)..sc1 {
8932 self.above_mode[i] = DC_PRED;
8933 self.above_side[i] = NO_NEIGHBOUR_SIDE;
8934 }
8935 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
8936 // the tile's own mi column span directly.
8937 let mend = col1_mi.min(self.above_skip.len());
8938 for i in col0_mi.min(mend)..mend {
8939 self.above_skip[i] = false;
8940 self.above_skip_mode[i] = false;
8941 self.above_inter[i] = false;
8942 self.above_ref[i] = -1;
8943 self.above_ref1[i] = None;
8944 self.above_comp_group_idx[i] = 0;
8945 self.above_compound_idx[i] = 0;
8946 self.above_filter[i] = [3u8; 2];
8947 }
8948 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
8949 // stale `(row, mode)` from the tile to the LEFT names an mi row this
8950 // tile's first block would read as its own above neighbour.
8951 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
8952 for i in col0_mi.min(mcol_end)..mcol_end {
8953 self.sub8_mode_col[i] = (u16::MAX, 0);
8954 self.uv_mode_col[i] = (u16::MAX, 0);
8955 }
8956 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
8957 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
8958 // not zero) -- without it a second tile column reads the first one's
8959 // resolved transform sizes as its own above context.
8960 let tend = col1_mi.min(self.above_txfm.len());
8961 for i in col0_mi.min(tend)..tend {
8962 self.above_txfm[i] = TXFM_CTX_INIT;
8963 }
8964 }
8965
8966 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
8967 /// for a non-palette block, clearing any stale neighbour state) into every
8968 /// [`SUB`]-grid cell it covers on both the above and left edges --
8969 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
8970 /// call sites are all square blocks).
8971 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
8972 self.record_palette_y_rect(
8973 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
8974 side,
8975 side,
8976 size,
8977 colors,
8978 );
8979 }
8980
8981 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
8982 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
8983 /// [`Self::record`]): a true rect strip's above/left neighbour spans
8984 /// differ.
8985 fn record_palette_y_rect(
8986 &mut self,
8987 mi: (usize, usize),
8988 w: usize,
8989 h: usize,
8990 size: usize,
8991 colors: [u16; 8],
8992 ) {
8993 let (r, c) = mi;
8994 if crate::envflags::env_flag!("EC_PALPUB") {
8995 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
8996 }
8997 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
8998 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
8999 // cell immediately left of the block, not its 16px [`SUB`] cell. The
9000 // old SUB grid let a 16x8 strip pair share one slot, so the second
9001 // strip of mi(0,8) read the FIRST strip's palette size and the colour
9002 // cache came out one entry short (class [[context-read-from-one-cell]]).
9003 for cell in 0..(w / MI).max(1) {
9004 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
9005 *e = size as u8;
9006 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
9007 // neighbour's colours only where its palette size > 0, so a
9008 // non-palette block need not stamp 16 bytes of zeroes here.
9009 if size > 0 {
9010 self.above_palette_colors[c + cell] = colors;
9011 }
9012 }
9013 }
9014 for cell in 0..(h / MI).max(1) {
9015 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
9016 *e = size as u8;
9017 if size > 0 {
9018 self.left_palette_colors[r + cell] = colors;
9019 }
9020 }
9021 }
9022 }
9023
9024 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
9025 /// neighbours that are themselves a palette-Y block, plus
9026 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
9027 /// cache (pred_common.c:73).
9028 ///
9029 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
9030 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
9031 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
9032 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
9033 /// the ctx too made every superblock in the frame's second SB row read
9034 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
9035 /// palette block decoded as "no palette" and the tile desynced from
9036 /// there (class [[cdf-row-held-constant]]).
9037 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
9038 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9039 }
9040
9041 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
9042 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
9043 /// drops the above neighbour on a 64-px superblock boundary
9044 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
9045 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
9046 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
9047 /// every strip in an SB's top cell row, which libaom does not do.
9048 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
9049 let (r, c) = mi;
9050 let above_ok = r % 16 != 0;
9051 // `xd->above_mbmi` exists for every row but the tile's own first.
9052 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
9053 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
9054 (
9055 usize::from(self.above_palette_size[c]),
9056 self.above_palette_colors[c],
9057 )
9058 } else {
9059 (0, [0u16; 8])
9060 };
9061 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
9062 // is NULL whenever the block sits at its TILE's own left column
9063 // (`left_available`), not the frame's -- without this guard a second
9064 // tile column reads the previous tile's palette colours into its cache
9065 // and its `palette_y_mode` ctx.
9066 let left_ok = c > self.tile_col0_mi;
9067 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
9068 (
9069 usize::from(self.left_palette_size[r]),
9070 self.left_palette_colors[r],
9071 )
9072 } else {
9073 (0, [0u16; 8])
9074 };
9075 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
9076 let mut cache = Vec::with_capacity(16);
9077 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9078 if cache.last() != Some(&v) {
9079 cache.push(v);
9080 }
9081 };
9082 let (mut ai, mut li) = (0usize, 0usize);
9083 while ai < above_n && li < left_n {
9084 let (va, vl) = (above_colors[ai], left_colors[li]);
9085 if vl < va {
9086 push_dedup(&mut cache, vl);
9087 li += 1;
9088 } else {
9089 push_dedup(&mut cache, va);
9090 ai += 1;
9091 if vl == va {
9092 li += 1;
9093 }
9094 }
9095 }
9096 while ai < above_n {
9097 push_dedup(&mut cache, above_colors[ai]);
9098 ai += 1;
9099 }
9100 while li < left_n {
9101 push_dedup(&mut cache, left_colors[li]);
9102 li += 1;
9103 }
9104 (ctx, cache)
9105 }
9106
9107 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
9108 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9109 /// same way (lane-palette2 r1).
9110 fn record_palette_uv(
9111 &mut self,
9112 at: (usize, usize),
9113 side: usize,
9114 size: usize,
9115 colors: [u16; 8],
9116 ) {
9117 self.record_palette_uv_rect(
9118 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9119 side,
9120 side,
9121 size,
9122 colors,
9123 );
9124 }
9125
9126 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9127 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9128 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9129 /// luma resolution regardless of which plane the recorded state is for).
9130 fn record_palette_uv_rect(
9131 &mut self,
9132 mi: (usize, usize),
9133 w: usize,
9134 h: usize,
9135 size: usize,
9136 colors: [u16; 8],
9137 ) {
9138 let (r, c) = mi;
9139 // mi granularity, see [`Self::record_palette_y_rect`].
9140 for cell in 0..(w / MI).max(1) {
9141 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9142 *e = size as u8;
9143 if size > 0 {
9144 self.above_palette_uv_colors[c + cell] = colors;
9145 }
9146 }
9147 }
9148 for cell in 0..(h / MI).max(1) {
9149 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9150 *e = size as u8;
9151 if size > 0 {
9152 self.left_palette_uv_colors[r + cell] = colors;
9153 }
9154 }
9155 }
9156 }
9157
9158 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9159 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9160 /// no neighbour lookup at all (it is this block's own just-decided Y
9161 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9162 /// so only the cache is wanted here.
9163 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9164 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9165 }
9166
9167 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9168 /// [`Self::palette_ctx_and_cache_mi`].
9169 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9170 let (r, c) = mi;
9171 let above_ok = r % 16 != 0;
9172 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9173 (
9174 usize::from(self.above_palette_uv_size[c]),
9175 self.above_palette_uv_colors[c],
9176 )
9177 } else {
9178 (0, [0u16; 8])
9179 };
9180 // Same tile-relative left availability as the luma cache above.
9181 let left_ok = c > self.tile_col0_mi;
9182 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9183 (
9184 usize::from(self.left_palette_uv_size[r]),
9185 self.left_palette_uv_colors[r],
9186 )
9187 } else {
9188 (0, [0u16; 8])
9189 };
9190 let mut cache = Vec::with_capacity(16);
9191 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9192 if cache.last() != Some(&v) {
9193 cache.push(v);
9194 }
9195 };
9196 let (mut ai, mut li) = (0usize, 0usize);
9197 while ai < above_n && li < left_n {
9198 let (va, vl) = (above_colors[ai], left_colors[li]);
9199 if vl < va {
9200 push_dedup(&mut cache, vl);
9201 li += 1;
9202 } else {
9203 push_dedup(&mut cache, va);
9204 ai += 1;
9205 if vl == va {
9206 li += 1;
9207 }
9208 }
9209 }
9210 while ai < above_n {
9211 push_dedup(&mut cache, above_colors[ai]);
9212 ai += 1;
9213 }
9214 while li < left_n {
9215 push_dedup(&mut cache, left_colors[li]);
9216 li += 1;
9217 }
9218 cache
9219 }
9220
9221 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9222 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9223 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9224 /// units as [`Self::fill_skip_grid`].
9225 fn fill_lf_grid(
9226 &mut self,
9227 at_mi: (usize, usize),
9228 side_mi: usize,
9229 tx_px: u8,
9230 ref_frame: i8,
9231 fctx: &crate::decode::FrameCtx,
9232 ) {
9233 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9234 }
9235
9236 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9237 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9238 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9239 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9240 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9241 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9242 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9243 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9244 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9245 /// block's published transform extent to its own size is exactly that
9246 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9247 /// that needs it is the 128 root, whose chroma extent is the one
9248 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9249 /// never suppressed (libaom's `is_inter_block` term), so this is called
9250 /// only from the skipped-inter branch.
9251 ///
9252 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
9253 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
9254 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
9255 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
9256 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
9257 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
9258 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
9259 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
9260 /// no format guard was possible inside this method until now.
9261 ///
9262 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
9263 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
9264 /// every edge it lets through then meets the SAME libaom rule applied at
9265 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
9266 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
9267 /// skip_at && skip_at`. Inside one skipped block both cells are that same
9268 /// block, so all four terms hold and the edge dies there too. The masking
9269 /// is TOTAL, not incidental: this method is only ever called for a block
9270 /// that is itself skipped, so no input exists on which one side of an
9271 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
9272 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
9273 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
9274 /// differ from each other in not one sample. The gate for this value is
9275 /// therefore a source scan, not a pixel gate --
9276 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
9277 fn suppress_internal_lf_edges(
9278 &mut self,
9279 at_mi: (usize, usize),
9280 w_mi: usize,
9281 h_mi: usize,
9282 fctx: &FrameCtx,
9283 ) {
9284 let (mi_r, mi_c) = at_mi;
9285 let (uv_w, uv_h) = (
9286 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
9287 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
9288 );
9289 for rr in 0..h_mi {
9290 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9291 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9292 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9293 }
9294 }
9295
9296 fn fill_lf_grid_rect(
9297 &mut self,
9298 at_mi: (usize, usize),
9299 w_mi: usize,
9300 h_mi: usize,
9301 tx_px: u8,
9302 tx_h_px: u8,
9303 ref_frame: i8,
9304 fctx: &crate::decode::FrameCtx,
9305 ) {
9306 let (mi_r, mi_c) = at_mi;
9307 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9308 // half its luma one (min 4 px, the smallest transform), capped at
9309 // TX_32X32 -- independent of this block's luma `tx_depth`.
9310 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9311 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9312 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9313 eprintln!(
9314 "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}"
9315 );
9316 }
9317 crate::census::tx(tx_px, tx_h_px);
9318 let cur = fctx.current_delta_lf.with(|c| c.get());
9319 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9320 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9321 } else {
9322 [cur[0].clamp(-63, 63) as i8; 4]
9323 };
9324 for rr in 0..h_mi {
9325 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9326 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9327 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9328 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9329 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9330 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9331 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9332 }
9333 if fctx.intra_only.with(std::cell::Cell::get) {
9334 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9335 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9336 // xd)` for EVERY block, an intra-only frame's included, and
9337 // `get_tx_size_context` / `txfm_partition_context` read those two
9338 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9339 // over the same footprint, so the publish is this write: the
9340 // `skip && is_inter` term is 0 for every intra-only block that is
9341 // not an intrabc one, and the bodies that can code an intrabc
9342 // block publish their own (the term is then the BLOCK size, a value
9343 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9344 // Inter frames publish at their own sites and are excluded here
9345 // because their skipped-block term needs the block size too.
9346 txfm_partition_update_rect(
9347 self,
9348 at_mi,
9349 (tx_px as usize, tx_h_px as usize),
9350 (w_mi * MI, h_mi * MI),
9351 );
9352 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9353 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9354 // instead of its transform band. Every block stamps its own cells
9355 // here; the intrabc bodies re-stamp theirs `true` afterwards
9356 // (`record_intrabc_inter_bands`).
9357 for i in 0..w_mi {
9358 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9359 *cell = false;
9360 }
9361 }
9362 for i in 0..h_mi {
9363 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9364 *cell = false;
9365 }
9366 }
9367 }
9368 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9369 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9370 // not just the intrabc ones. A later intrabc block's DV predictor is
9371 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9372 // `MB_MODE_INFO` for EVERY block and steps by
9373 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9374 // non-intrabc neighbour reads as uncovered and the scan advances it
9375 // by one cell instead of by its real width.
9376 fctx.intrabc_mi_grid.with(|g| {
9377 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9378 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9379 }
9380 });
9381 }
9382
9383 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9384 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9385 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9386 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9387 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9388 /// dims from the LEAF span and so invented chroma transform edges the
9389 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9390 /// are already correct from the block's own fill over the same span.
9391 fn fill_lf_grid_leaf_luma(
9392 &mut self,
9393 at_mi: (usize, usize),
9394 w_mi: usize,
9395 h_mi: usize,
9396 tx_px: u8,
9397 tx_h_px: u8,
9398 ) {
9399 let (mi_r, mi_c) = at_mi;
9400 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9401 eprintln!(
9402 "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}"
9403 );
9404 }
9405 for rr in 0..h_mi {
9406 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9407 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9408 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9409 }
9410 }
9411
9412 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9413 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9414 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9415 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9416 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9417 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9418 }
9419
9420 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9421 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9422 let (mi_r, mi_c) = at_mi;
9423 if skip && w_mi != h_mi {
9424 hit!(RECT_SKIP_BAND_HITS);
9425 }
9426 // lane-census: an INTRA frame's blocks never reach the inter
9427 // publisher, and this one is what every coded block writes.
9428 crate::census::block_intra_frame(w_mi, h_mi, skip);
9429 for rr in 0..h_mi {
9430 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9431 fill_span(
9432 &mut self.blk_grid,
9433 start,
9434 w_mi,
9435 BlkCell {
9436 skip,
9437 written: true,
9438 org: [mi_r as u16, mi_c as u16],
9439 dim: [w_mi as u8, h_mi as u8],
9440 },
9441 );
9442 }
9443 }
9444
9445 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
9446 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
9447 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
9448 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
9449 /// straddle the region with a mix of skip/non-skip blocks).
9450 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
9451 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
9452 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
9453 /// filtered edge's two sides are each exactly one coded block wide.
9454 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
9455 self.blk_grid
9456 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9457 .is_some_and(|c| c.skip)
9458 }
9459
9460 /// The `skip_txfm` context of a block whose top-left mi cell is
9461 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
9462 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
9463 /// with an absent neighbour contributing 0. The mi grid is per tile, so
9464 /// row/column 0 is a tile edge and has no neighbour on that axis.
9465 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
9466 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
9467 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
9468 }
9469
9470 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
9471 (0..2).all(|rr| {
9472 (0..2).all(|cc| {
9473 self.blk_grid
9474 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
9475 .is_some_and(|c| c.skip)
9476 })
9477 })
9478 }
9479
9480 fn start_row(&mut self) {
9481 self.left.iter_mut().for_each(|l| *l = Default::default());
9482 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
9483 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
9484 self.left_side
9485 .iter_mut()
9486 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
9487 self.left_side_mi
9488 .iter_mut()
9489 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
9490 self.left_skip.iter_mut().for_each(|s| *s = false);
9491 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
9492 self.left_inter.iter_mut().for_each(|i| *i = false);
9493 self.left_ref.iter_mut().for_each(|r| *r = -1);
9494 self.left_ref1.iter_mut().for_each(|r| *r = None);
9495 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
9496 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9497 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
9498 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
9499 // context (a tile/SB-row boundary has no left neighbour).
9500 self.sub8_mode_row
9501 .iter_mut()
9502 .for_each(|s| *s = (u16::MAX, 0));
9503 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
9504 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
9505 // are per-mi maps like every other one here, so they reset with the
9506 // row too -- the left guard above is what actually stops a cross-tile
9507 // read, this keeps a stale colour out of the arrays at all.
9508 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
9509 self.left_palette_colors
9510 .iter_mut()
9511 .for_each(|c| *c = [0u16; 8]);
9512 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
9513 self.left_palette_uv_colors
9514 .iter_mut()
9515 .for_each(|c| *c = [0u16; 8]);
9516 // lane-mergefix r2: `av1_zero_left_context` memsets
9517 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
9518 // every superblock row of every tile -- the var-tx left context does
9519 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
9520 // previous tile column's last block otherwise).
9521 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9522 }
9523
9524 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
9525 /// block that reads it as a neighbour -- [`crate::tile`]'s
9526 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9527 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9528 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9529 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9530 /// the real value, not just `is_inter`).
9531 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9532 fn record_inter(
9533 &mut self,
9534 at: (usize, usize),
9535 side: usize,
9536 skip: bool,
9537 is_inter: bool,
9538 ref_frame: i8,
9539 filter: [u8; 2],
9540 skip_mode: bool,
9541 ) {
9542 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9543 }
9544
9545 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9546 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9547 /// r1: a true rectangular strip's above-context span (its own width) and
9548 /// left-context span (its own height) differ, unlike every caller before
9549 /// this round (class neighbour-votes-all-its-fields).
9550 #[allow(clippy::too_many_arguments)]
9551 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9552 fn record_inter_rect(
9553 &mut self,
9554 at: (usize, usize),
9555 w_sub: usize,
9556 h_sub: usize,
9557 skip: bool,
9558 is_inter: bool,
9559 ref_frame: i8,
9560 filter: [u8; 2],
9561 skip_mode: bool,
9562 ) {
9563 let (r, c) = at;
9564 self.record_inter_rect_mi(
9565 (r * (SUB / MI), c * (SUB / MI)),
9566 w_sub / MI,
9567 h_sub / MI,
9568 skip,
9569 is_inter,
9570 ref_frame,
9571 filter,
9572 skip_mode,
9573 );
9574 }
9575
9576 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9577 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9578 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9579 /// routes through the wrapper above.
9580 #[allow(clippy::too_many_arguments)]
9581 fn record_inter_rect_mi(
9582 &mut self,
9583 at_mi: (usize, usize),
9584 w_mi: usize,
9585 h_mi: usize,
9586 skip: bool,
9587 is_inter: bool,
9588 ref_frame: i8,
9589 filter: [u8; 2],
9590 skip_mode: bool,
9591 ) {
9592 let (r, c) = at_mi;
9593 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9594 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9595 // writes for a whole block class): an INTER block left the luma mode
9596 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9597 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9598 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9599 // block in that pixel row -- the directional edge filter then ran at
9600 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9601 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9602 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9603 // already stamped it).
9604 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9605 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9606 // uv map must read DC_PRED over an inter block's cells too.
9607 if is_inter {
9608 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9609 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9610 }
9611 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9612 self.above_skip[c..c + w_mi].fill(skip);
9613 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9614 self.above_inter[c..c + w_mi].fill(is_inter);
9615 self.above_ref[c..c + w_mi].fill(ref_frame);
9616 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9617 // this with the block's real second reference for a compound block,
9618 // called right after this one (lane-publish2 audit).
9619 self.above_ref1[c..c + w_mi].fill(None);
9620 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9621 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9622 // as `3`/`1` even though this block has no second reference.
9623 // `record_compound_ctx` overwrites this with the real bit for an
9624 // actual compound block's cells, called right after this one.
9625 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9626 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9627 self.above_filter[c..c + w_mi].fill(filter);
9628 self.left_skip[r..r + h_mi].fill(skip);
9629 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9630 self.left_inter[r..r + h_mi].fill(is_inter);
9631 self.left_ref[r..r + h_mi].fill(ref_frame);
9632 self.left_ref1[r..r + h_mi].fill(None);
9633 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9634 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9635 self.left_filter[r..r + h_mi].fill(filter);
9636 }
9637
9638 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9639 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9640 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9641 /// `get_comp_index_context`) -- called right after `record_inter` for
9642 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9643 /// stamps `above_ref1`/`left_ref1` with the block's real second
9644 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9645 /// this is the one caller that actually knows it) -- so the next block's
9646 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9647 /// neighbour instead of `record_inter`'s single-ref default.
9648 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9649 fn record_compound_ctx(
9650 &mut self,
9651 at: (usize, usize),
9652 side: usize,
9653 ref1: i8,
9654 comp_group_idx: u8,
9655 compound_idx: u8,
9656 ) {
9657 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
9658 }
9659
9660 /// [`Self::record_compound_ctx`] with independent above/left extents,
9661 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
9662 #[allow(clippy::too_many_arguments)]
9663 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9664 fn record_compound_ctx_rect(
9665 &mut self,
9666 at: (usize, usize),
9667 w_sub: usize,
9668 h_sub: usize,
9669 ref1: i8,
9670 comp_group_idx: u8,
9671 compound_idx: u8,
9672 ) {
9673 let (r, c) = at;
9674 self.record_compound_ctx_rect_mi(
9675 (r * (SUB / MI), c * (SUB / MI)),
9676 w_sub / MI,
9677 h_sub / MI,
9678 ref1,
9679 comp_group_idx,
9680 compound_idx,
9681 );
9682 }
9683
9684 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
9685 /// [`Self::record_inter_rect_mi`]).
9686 fn record_compound_ctx_rect_mi(
9687 &mut self,
9688 at_mi: (usize, usize),
9689 w_mi: usize,
9690 h_mi: usize,
9691 ref1: i8,
9692 comp_group_idx: u8,
9693 compound_idx: u8,
9694 ) {
9695 let (r, c) = at_mi;
9696 crate::census::compound();
9697 for cell in 0..w_mi {
9698 self.above_ref1[c + cell] = Some(ref1);
9699 self.above_comp_group_idx[c + cell] = comp_group_idx;
9700 self.above_compound_idx[c + cell] = compound_idx;
9701 }
9702 for cell in 0..h_mi {
9703 self.left_ref1[r + cell] = Some(ref1);
9704 self.left_comp_group_idx[r + cell] = comp_group_idx;
9705 self.left_compound_idx[r + cell] = compound_idx;
9706 }
9707 }
9708
9709 /// The context of a block's partition symbol: delegates to the mi-precise
9710 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9711 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
9712 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
9713 /// only touches the finer mi arrays -- leaves them stale for the *next*
9714 /// sibling's own partition symbol.
9715 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
9716 let (r, c) = at;
9717 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
9718 }
9719
9720 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
9721 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
9722 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
9723 /// than the enclosing 16x16 slot's stale, shared state.
9724 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9725 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
9726 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
9727 }
9728
9729 /// The gathered coded/DC-sign state of the blocks above and to the left
9730 /// of a block `side` samples across, per plane.
9731 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9732 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
9733 }
9734
9735 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
9736 /// units, for the same reason [`Self::record_mi`] does.
9737 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9738 let side_mi = side / MI;
9739 // One pass over the cells accumulating all three planes, not one pass
9740 // per plane: the three planes of a cell live in the same
9741 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
9742 // cache lines three times (lane-publish). Clamp each edge to the true
9743 // frame extent: a block at the right/bottom edge may be padded beyond
9744 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
9745 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
9746 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
9747 let mut out = [(false, false, 0i32); 3];
9748 for cell in 0..above_mi {
9749 let above = &self.above[mi_c + cell];
9750 for (plane, o) in out.iter_mut().enumerate() {
9751 o.0 |= above[plane].level != 0;
9752 o.2 += dc_vote(above[plane].dc);
9753 }
9754 }
9755 for cell in 0..left_mi {
9756 let left = &self.left[mi_r + cell];
9757 for (plane, o) in out.iter_mut().enumerate() {
9758 o.1 |= left[plane].level != 0;
9759 o.2 += dc_vote(left[plane].dc);
9760 }
9761 }
9762 out
9763 }
9764
9765 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
9766 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
9767 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
9768 /// spans TWO luma mi columns. Both cells of a column carry the covering
9769 /// unit's whole-unit dc sign (the same value libaom stores), so the
9770 /// per-luma-mi sum counts each chroma column twice -- and
9771 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
9772 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
9773 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
9774 /// Sampling every second above cell counts each chroma column once,
9775 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
9776 /// its per-mi cells already line up one-to-one. The level booleans are
9777 /// ORs over duplicated cells, so the sampling cannot change them.
9778 fn around_mi_422_chroma(
9779 &self,
9780 (mi_r, mi_c): (usize, usize),
9781 w: usize,
9782 h: usize,
9783 ) -> [(bool, bool, i32); 3] {
9784 let (w_mi, h_mi) = (w / MI, h / MI);
9785 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9786 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9787 let mut out = [(false, false, 0i32); 3];
9788 for cell in (0..above_mi).step_by(2) {
9789 let above = &self.above[mi_c + cell];
9790 for (plane, o) in out.iter_mut().enumerate() {
9791 o.0 |= above[plane].level != 0;
9792 o.2 += dc_vote(above[plane].dc);
9793 }
9794 }
9795 for cell in 0..left_mi {
9796 let left = &self.left[mi_r + cell];
9797 for (plane, o) in out.iter_mut().enumerate() {
9798 o.1 |= left[plane].level != 0;
9799 o.2 += dc_vote(left[plane].dc);
9800 }
9801 }
9802 if crate::envflags::env_flag!("EC_DCDUMP") {
9803 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
9804 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
9805 // The above rows are the SAMPLED (every-second) cells.
9806 for (plane, o) in out.iter().enumerate() {
9807 let vote = o.2;
9808 let ab: Vec<String> = (0..above_mi)
9809 .step_by(2)
9810 .map(|k| {
9811 format!(
9812 "{:?}/{}",
9813 self.above[mi_c + k][plane].dc,
9814 self.above[mi_c + k][plane].level
9815 )
9816 })
9817 .collect();
9818 let lf: Vec<String> = (0..left_mi)
9819 .map(|k| {
9820 format!(
9821 "{:?}/{}",
9822 self.left[mi_r + k][plane].dc,
9823 self.left[mi_r + k][plane].level
9824 )
9825 })
9826 .collect();
9827 eprintln!(
9828 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9829 ab.join(","),
9830 lf.join(",")
9831 );
9832 }
9833 }
9834 out
9835 }
9836
9837 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
9838 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
9839 /// extent pattern for a true rectangular strip's own coefficient context.
9840 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
9841 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
9842 }
9843
9844 /// [`Self::around_rect`] taking the block's position directly in 4x4
9845 /// mode-info units, mirroring [`Self::around_mi`].
9846 fn around_mi_rect(
9847 &self,
9848 (mi_r, mi_c): (usize, usize),
9849 w: usize,
9850 h: usize,
9851 ) -> [(bool, bool, i32); 3] {
9852 let (w_mi, h_mi) = (w / MI, h / MI);
9853 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9854 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9855 // [`Self::around_mi`]'s single pass, with the two extents split.
9856 let mut out = [(false, false, 0i32); 3];
9857 for cell in 0..above_mi {
9858 let above = &self.above[mi_c + cell];
9859 for (plane, o) in out.iter_mut().enumerate() {
9860 o.0 |= above[plane].level != 0;
9861 o.2 += dc_vote(above[plane].dc);
9862 }
9863 }
9864 for cell in 0..left_mi {
9865 let left = &self.left[mi_r + cell];
9866 for (plane, o) in out.iter_mut().enumerate() {
9867 o.1 |= left[plane].level != 0;
9868 o.2 += dc_vote(left[plane].dc);
9869 }
9870 }
9871 if crate::envflags::env_flag!("EC_DCDUMP") {
9872 for (plane, o) in out.iter().enumerate() {
9873 let vote = o.2;
9874 let ab: Vec<String> = (0..above_mi)
9875 .map(|k| {
9876 format!(
9877 "{:?}/{}",
9878 self.above[mi_c + k][plane].dc,
9879 self.above[mi_c + k][plane].level
9880 )
9881 })
9882 .collect();
9883 let lf: Vec<String> = (0..left_mi)
9884 .map(|k| {
9885 format!(
9886 "{:?}/{}",
9887 self.left[mi_r + k][plane].dc,
9888 self.left[mi_r + k][plane].level
9889 )
9890 })
9891 .collect();
9892 eprintln!(
9893 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9894 ab.join(","),
9895 lf.join(",")
9896 );
9897 }
9898 }
9899 out
9900 }
9901
9902 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
9903 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
9904 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
9905 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
9906 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
9907 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
9908 /// is always 0, spec's `plane_bsize == tx_size` branch).
9909 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
9910 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
9911 }
9912
9913 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
9914 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
9915 /// context over `tx_size_wide` and the left one over `tx_size_high`.
9916 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
9917 let side_mi = w_mi;
9918 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9919 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9920 let mut top = 0u8;
9921 let mut left = 0u8;
9922 for cell in 0..above_mi {
9923 top |= self.above[mi_c + cell][0].level;
9924 }
9925 for cell in 0..left_mi {
9926 left |= self.left[mi_r + cell][0].level;
9927 }
9928 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
9929 if crate::envflags::env_flag!("EC_ECDUMP") {
9930 let ab: Vec<String> = (0..above_mi)
9931 .map(|k| self.above[mi_c + k][0].level.to_string())
9932 .collect();
9933 let lf: Vec<String> = (0..left_mi)
9934 .map(|k| self.left[mi_r + k][0].level.to_string())
9935 .collect();
9936 // lane-av1mix: the last few msac register states, so the
9937 // byte-position of the `all_zero` read can be matched against
9938 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
9939 // second run.
9940 let recent = crate::msac::symtrace::ecdump_recent(4)
9941 .iter()
9942 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
9943 .collect::<Vec<_>>()
9944 .join(" ");
9945 eprintln!(
9946 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
9947 ab.join(","),
9948 lf.join(","),
9949 recent
9950 );
9951 }
9952 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9953 eprintln!(
9954 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
9955 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
9956 );
9957 }
9958 ctx
9959 }
9960
9961 /// Writes one coded block into every cell it covers, on both grids: the
9962 /// mode/side arrays up to `side`'s own width, and the coefficient-context
9963 /// arrays up to the true frame edge — the units past it are left at their
9964 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
9965 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
9966 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
9967 /// not from this block's own side).
9968 fn record(
9969 &mut self,
9970 at: (usize, usize),
9971 side: usize,
9972 mode: usize,
9973 uv_mode: usize,
9974 grids: &[&[i32]; 3],
9975 ) {
9976 self.record_rect(at, side, side, mode, uv_mode, grids);
9977 }
9978
9979 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
9980 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
9981 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
9982 /// spec's per-edge partition-context rule, so a true rectangular block
9983 /// naturally wants two different values here rather than one.
9984 /// Writes this block's luma `mode` into the mi-granular
9985 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
9986 /// position a *later* neighbour would read it from: the block's LAST mi
9987 /// row for every column it spans (what the block below reads via
9988 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
9989 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
9990 /// read these back, and only when the recorded position is exactly their
9991 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
9992 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
9993 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
9994 let mode = mode as u8;
9995 for cell in 0..mi_w {
9996 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
9997 *slot = (last_r, mode);
9998 }
9999 }
10000 for cell in 0..mi_h {
10001 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
10002 *slot = (last_c, mode);
10003 }
10004 }
10005 }
10006
10007 /// The mi-exact above/left neighbour luma mode for a block whose top-left
10008 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
10009 /// mi position (then the coarse [`SUB`]-grid slot is right by
10010 /// construction). See [`Self::record_mode_mi`].
10011 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10012 match self.sub8_mode_col.get(mi_c) {
10013 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
10014 Some(usize::from(m))
10015 }
10016 _ => None,
10017 }
10018 }
10019
10020 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10021 match self.sub8_mode_row.get(mi_r) {
10022 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
10023 Some(usize::from(m))
10024 }
10025 _ => None,
10026 }
10027 }
10028
10029 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
10030 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
10031 fn record_uv_mode_mi(
10032 &mut self,
10033 mi_r: usize,
10034 mi_c: usize,
10035 mi_w: usize,
10036 mi_h: usize,
10037 uv_mode: usize,
10038 ) {
10039 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
10040 fill_span(
10041 &mut self.uv_mode_col,
10042 mi_c,
10043 mi_w,
10044 (last_r as u16, uv_mode as u8),
10045 );
10046 fill_span(
10047 &mut self.uv_mode_row,
10048 mi_r,
10049 mi_h,
10050 (last_c as u16, uv_mode as u8),
10051 );
10052 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
10053 // covers, so the chroma neighbour read below is a plain grid read.
10054 let stride = self.uv_grid_cols;
10055 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
10056 for row in mi_r..=last_r {
10057 fill_span(
10058 &mut self.uv_mode_grid,
10059 row * stride + mi_c,
10060 n,
10061 uv_mode as u8,
10062 );
10063 }
10064 // lane-av1leftwit: stamp the writing block's own mi over its extent,
10065 // the same cells and the same clipping as `uv_mode_grid` above.
10066 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
10067 for row in mi_r..=last_r {
10068 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
10069 }
10070 if crate::envflags::env_flag!("EC_LEFTSSY") {
10071 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
10072 }
10073 }
10074
10075 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
10076 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
10077 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
10078 /// block has recorded the exact neighbouring mi.
10079 fn smooth_uv_neighbour(
10080 &self,
10081 mi_r: usize,
10082 mi_c: usize,
10083 r: usize,
10084 c: usize,
10085 fctx: &crate::decode::FrameCtx,
10086 ) -> bool {
10087 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
10088 // REFERENCE block, not off the mi that carries the chroma syntax.
10089 // `set_mi_row_col` (`blockd.h`) takes
10090 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
10091 // only then `chroma_above_mbmi = base_mi[-stride]` /
10092 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
10093 // the ODD mi, so without the snap we looked one mi row/column too far
10094 // down/right -- the mi-exact slot never matched and the coarse
10095 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
10096 // 8x4 at (688, 100) = mi (51, 344): libaom's
10097 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
10098 // `UV_SMOOTH_PRED`), ours was 0, which flips
10099 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
10100 // false for type 1, TRUE for type 0) and upsampled an edge libaom
10101 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
10102 // predicting from it (class `context-read-from-one-cell`).
10103 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
10104 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
10105 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
10106 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
10107 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
10108 let snap_y = (1usize << ss_y(fctx)) - 1;
10109 let snap_x = (1usize << ss_x(fctx)) - 1;
10110 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
10111 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
10112 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
10113 // the two chroma-reference offsets on top of it -- see its own comment
10114 // for which axis each one moves.
10115 self.smooth_uv_neighbour_unsnapped(
10116 mi_r & !snap_y,
10117 mi_c & !snap_x,
10118 r,
10119 c,
10120 ss_x(fctx),
10121 ss_y(fctx),
10122 true,
10123 )
10124 }
10125
10126 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
10127 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
10128 /// counter wants this: it measures how often the snap CHANGES the answer,
10129 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
10130 /// decode path uses the snapping form.
10131 /// `decode_path` is `true` only for the snapping form every decode call
10132 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
10133 /// `+ss_y` counters measure a read that actually filters a chroma edge and
10134 /// not the counter-only one.
10135 ///
10136 /// lane-av1leftwit: the mirror's justification used to be "no committed
10137 /// fixture reaches the shape on the decode path", and that was false --
10138 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
10139 /// counter-only mirror at an ODD mi row is still not a decode-path read,
10140 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
10141 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
10142 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
10143 fn smooth_uv_neighbour_unsnapped(
10144 &self,
10145 mi_r: usize,
10146 mi_c: usize,
10147 r: usize,
10148 c: usize,
10149 ss_x: usize,
10150 ss_y: usize,
10151 decode_path: bool,
10152 ) -> bool {
10153 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10154 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10155 // array that `start_tile` does not clear, so a block on a tile's first
10156 // mi row used to read the uv_mode of the block above it in the tile
10157 // ABOVE and filter its chroma edge at that neighbour's strength
10158 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10159 // at chroma (120, 32), the top-right tile's first block).
10160 let have_above = mi_r > self.tile_row0_mi;
10161 let have_left = mi_c > self.tile_col0_mi;
10162 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10163 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10164 {
10165 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10166 }
10167 // The mi grid is libaom's own read; the two maps below stay as the
10168 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10169 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10170 (col < self.uv_grid_cols)
10171 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10172 .flatten()
10173 .filter(|&m| m != u8::MAX)
10174 .map(usize::from)
10175 };
10176 // libaom's two chroma-reference mi, from `set_mi_row_col`
10177 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10178 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10179 // snap -- i.e. already libaom's `base_mi`:
10180 //
10181 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10182 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10183 //
10184 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10185 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10186 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10187 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10188 // boolean it feeds is simply not exercised differently by that stream
10189 // at its blocks. One chroma column spans two luma mi columns, so the
10190 // chroma edge reaches into the right-hand luma block, and that is where
10191 // its reference lives.
10192 //
10193 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10194 // last open item lane-av1422warp carried. libaom puts the left
10195 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10196 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10197 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10198 // read (the above) and regressed the byte-exact 4:2:0 control, which
10199 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10200 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10201 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10202 // measured. Measured over all 48 committed fixtures that decode
10203 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10204 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10205 // put a 1-mi-tall left neighbour in front of a decode-path read at
10206 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10207 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10208 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10209 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10210 // changing is what is still unwitnessed.
10211 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10212 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10213 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10214 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10215 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10216 // row at every subsampling. The term is only observable when the two
10217 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10218 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10219 // and only libaom's is the chroma reference. Three counters measure
10220 // that, and the third is the one the other two need: a read can only
10221 // differ if the two cells are written by DIFFERENT blocks, which
10222 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10223 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10224 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10225 // reads > 0 is the term being unobservable on real material, not
10226 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10227 // whether the mode value, and the boolean this feeds
10228 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10229 // edge filter), actually moved.
10230 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10231 let read_left = |row: usize| -> usize {
10232 match self.uv_mode_row.get(row) {
10233 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10234 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10235 _ if have_left => self.left_uv_mode[r],
10236 _ => DC_PRED,
10237 }
10238 };
10239 let above = match self.uv_mode_col.get(above_mi.1) {
10240 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10241 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10242 _ if have_above => self.above_uv_mode[c],
10243 _ => DC_PRED,
10244 };
10245 let left = read_left(left_mi.0);
10246 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10247 // how many chroma edge-filter-type reads took this path at all, so a
10248 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10249 // term did not change the answer". The two DIFF buckets compare
10250 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10251 // every committed fixture and every one of the ~1000 encodes swept in
10252 // `lanes/av1leftref.report.md`, which is what makes the read change a
10253 // proven no-op on today's material rather than an unmeasured guess.
10254 if decode_path && have_left && ss_y > 0 {
10255 hit!(UV_LEFT_SS_Y_READS);
10256 // The pre-lane read, kept as the counter's own-row arm: it is what
10257 // this decoder answered before the `+ss_y` term landed, and
10258 // comparing against it is what proves the term is load-bearing.
10259 let own_row = read_left(mi_r);
10260 if own_row != left {
10261 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10262 }
10263 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10264 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10265 }
10266 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10267 // cells are one left mi column apart, so they are two different
10268 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10269 let col = left_mi.1;
10270 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10271 let own = (col < self.uv_grid_cols)
10272 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10273 .flatten()
10274 .filter(|o| o & 0xff00_0000 == epoch)
10275 .unwrap_or(0);
10276 let down = self
10277 .uv_owner
10278 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10279 .copied()
10280 .filter(|o| o & 0xff00_0000 == epoch)
10281 .unwrap_or(0);
10282 if own != 0 && down != 0 && own != down {
10283 hit!(UV_LEFT_1MI_SPLIT_HITS);
10284 if crate::envflags::env_flag!("EC_LEFTSSY") {
10285 eprintln!(
10286 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10287 owners=({},{})->({},{}) modes={own_row}/{left}",
10288 epoch >> 24,
10289 own >> 12 & 0xfff,
10290 own & 0xfff,
10291 down >> 12 & 0xfff,
10292 down & 0xfff,
10293 );
10294 }
10295 }
10296 }
10297 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10298 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10299 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10300 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10301 }) {
10302 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10303 }
10304 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10305 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10306 // have been filtered at the wrong strength by the coarse map alone.
10307 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10308 hit!(UV_MODE_MI_OVERRIDE_HITS);
10309 }
10310 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10311 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10312 {
10313 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10314 }
10315 is_smooth_mode(above) || is_smooth_mode(left)
10316 }
10317
10318 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10319 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10320 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10321 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10322 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10323 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10324 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10325 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10326 /// a different CDF for the same mode value).
10327 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10328 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10329 /// only when `up_available` and `left_mbmi` only when `left_available`;
10330 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10331 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10332 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10333 /// strip's mode as its "left neighbour" (measured on the band fixture at
10334 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10335 fn modes_above_left_mi(
10336 &self,
10337 mi_r: usize,
10338 mi_c: usize,
10339 fallback: (usize, usize),
10340 ) -> (usize, usize) {
10341 let above = if mi_r > self.tile_row0_mi {
10342 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10343 } else {
10344 DC_PRED
10345 };
10346 let left = if mi_c > self.tile_col0_mi {
10347 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10348 } else {
10349 DC_PRED
10350 };
10351 (above, left)
10352 }
10353
10354 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10355 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10356 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10357 /// per superblock row and never per tile, so the first block column of
10358 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10359 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10360 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10361 /// `up_available`/`left_available` and uses DC_PRED otherwise
10362 /// ([`Self::modes_above_left_mi`]).
10363 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10364 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10365 let (above, left) =
10366 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10367 if above != self.above_mode[c] || left != self.left_mode[r] {
10368 hit!(MODE_MI_OVERRIDE_HITS);
10369 }
10370 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10371 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10372 {
10373 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10374 }
10375 // A neighbour the coarse band offered where the tile edge makes it
10376 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10377 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10378 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10379 {
10380 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10381 }
10382 (above, left)
10383 }
10384
10385 fn record_rect(
10386 &mut self,
10387 at: (usize, usize),
10388 w: usize,
10389 h: usize,
10390 mode: usize,
10391 uv_mode: usize,
10392 grids: &[&[i32]; 3],
10393 ) {
10394 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10395 }
10396
10397 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10398 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10399 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10400 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10401 /// the [`SUB`]-unit path does).
10402 fn record_rect_mi(
10403 &mut self,
10404 at_mi: (usize, usize),
10405 w: usize,
10406 h: usize,
10407 mode: usize,
10408 uv_mode: usize,
10409 grids: &[&[i32]; 3],
10410 ) {
10411 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
10412 // lane-inter4 r2: a strip whose own footprint runs past the frame's
10413 // last 16-px column/row stamps only the cells that exist (libaom's
10414 // arrays are padded past the frame and those cells are never read).
10415 for cell in 0..w / SUB {
10416 if c + cell >= self.above_mode.len() {
10417 break;
10418 }
10419 self.above_mode[c + cell] = mode;
10420 self.above_uv_mode[c + cell] = uv_mode;
10421 self.above_side[c + cell] = w;
10422 }
10423 for cell in 0..h / SUB {
10424 if r + cell >= self.left_mode.len() {
10425 break;
10426 }
10427 self.left_mode[r + cell] = mode;
10428 self.left_uv_mode[r + cell] = uv_mode;
10429 self.left_side[r + cell] = h;
10430 }
10431 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
10432 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
10433 self.record_mi_rect(at_mi, w, h, grids);
10434 }
10435
10436 /// The coefficient-context half of [`Self::record`], taking the block's
10437 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
10438 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
10439 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
10440 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
10441 self.record_mi_rect(at_mi, side, side, grids);
10442 }
10443
10444 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
10445 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
10446 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
10447 let (mi_r, mi_c) = at_mi;
10448 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
10449 let (w_mi, h_mi) = (w / MI, h / MI);
10450 if crate::envflags::env_flag!("EC_ECPUB") {
10451 eprintln!(
10452 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
10453 states[0].level
10454 );
10455 }
10456 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10457 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10458 // A chroma 4x4 unit straddling the true luma edge is still whole in
10459 // chroma's own halved grid, so libaom rounds the luma bound up to the
10460 // plane's own 4x4 unit before clamping a subsampled plane
10461 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
10462 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10463 let bound_h = [
10464 self.mi_rows,
10465 round_up_even(self.mi_rows),
10466 round_up_even(self.mi_rows),
10467 ];
10468 let bound_w = [
10469 self.mi_cols,
10470 round_up_even(self.mi_cols),
10471 round_up_even(self.mi_cols),
10472 ];
10473 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
10474 // past the padded side arrays (mi_rows 198, block rows 192..208);
10475 // libaom's own arrays are superblock-sized, so those cells simply
10476 // have no reader -- [`fill_span`] drops them, as the `break` did.
10477 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
10478 // predicate is three contiguous runs: all planes, chroma only, none
10479 // (lane-mi).
10480 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
10481 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
10482 let uv_only = [Neighbour::default(), states[1], states[2]];
10483 fill_span(&mut self.left, mi_r, luma_h, states);
10484 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
10485 fill_span(
10486 &mut self.left,
10487 mi_r + chroma_h,
10488 h_mi - chroma_h,
10489 [Neighbour::default(); 3],
10490 );
10491 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
10492 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
10493 let uv_only_w = [Neighbour::default(), states[1], states[2]];
10494 fill_span(&mut self.above, mi_c, luma_w, states);
10495 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
10496 fill_span(
10497 &mut self.above,
10498 mi_c + chroma_w,
10499 w_mi - chroma_w,
10500 [Neighbour::default(); 3],
10501 );
10502 }
10503
10504 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
10505 /// inside a coded block whose luma transform is smaller than its own
10506 /// side (`TxMode::Select`): the real per-transform-unit coefficient
10507 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
10508 /// coarse per-block `tx_grid`/`fill_lf_grid` state
10509 /// [`Self::record_split_luma`] still writes once for the whole block.
10510 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
10511 /// the caller's own [`Self::record_split_luma`] call sets those once,
10512 /// at the block's own true side, not this TU's.
10513 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
10514 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
10515 }
10516
10517 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
10518 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
10519 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
10520 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
10521 /// coefficient-context arrays are indexed by luma mi, the convention
10522 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
10523 /// clamp included.
10524 fn record_mi_chroma(
10525 &mut self,
10526 (mi_r, mi_c): (usize, usize),
10527 w_px: usize,
10528 h_px: usize,
10529 plane: usize,
10530 grid: &[i32],
10531 ) {
10532 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10533 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10534 let state = neighbour_state(grid);
10535 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
10536 eprintln!(
10537 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
10538 state.level,
10539 state.dc.map_or(-1, |s| i32::from(s))
10540 );
10541 }
10542 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
10543 self.left[mi_r + cell][plane] = state;
10544 }
10545 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
10546 self.above[mi_c + cell][plane] = state;
10547 }
10548 }
10549
10550 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
10551 /// r1): the above context spans the unit's width, the left context its
10552 /// height, which for a square unit is the same loop it always was.
10553 fn record_mi_luma_rect(
10554 &mut self,
10555 (mi_r, mi_c): (usize, usize),
10556 w_px: usize,
10557 h_px: usize,
10558 grid: &[i32],
10559 ) {
10560 let state = neighbour_state(grid);
10561 if crate::envflags::env_flag!("EC_ECPUB") {
10562 eprintln!(
10563 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
10564 state.level
10565 );
10566 }
10567 for cell in 0..h_px / MI {
10568 if mi_r + cell < self.mi_rows {
10569 self.left[mi_r + cell][0] = state;
10570 }
10571 }
10572 for cell in 0..w_px / MI {
10573 if mi_c + cell < self.mi_cols {
10574 self.above[mi_c + cell][0] = state;
10575 }
10576 }
10577 }
10578
10579 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
10580 /// block whose luma was decoded as several transform units through
10581 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
10582 /// whole-block luma write -- everything [`Self::record`] does except
10583 /// plane 0, which is already correct per-TU by the time this runs.
10584 fn record_split_luma(
10585 &mut self,
10586 at: (usize, usize),
10587 side: usize,
10588 mode: usize,
10589 uv_mode: usize,
10590 chroma_grids: [&[i32]; 2],
10591 ) {
10592 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
10593 }
10594
10595 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
10596 /// extents in pixels (lane-rectsplit r1), the same relationship
10597 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
10598 /// luma transform split into several square units needs exactly this
10599 /// bookkeeping, at its own true rectangular extents.
10600 fn record_split_luma_rect(
10601 &mut self,
10602 at: (usize, usize),
10603 w: usize,
10604 h: usize,
10605 mode: usize,
10606 uv_mode: usize,
10607 chroma_grids: [&[i32]; 2],
10608 ) {
10609 let (r, c) = at;
10610 self.record_split_luma_rect_mi(
10611 (r * (SUB / MI), c * (SUB / MI)),
10612 w,
10613 h,
10614 mode,
10615 uv_mode,
10616 chroma_grids,
10617 );
10618 }
10619
10620 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
10621 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
10622 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
10623 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
10624 /// convention [`decode_block_rect4`] already established for 1:4 strips.
10625 fn record_split_luma_rect_mi(
10626 &mut self,
10627 at_mi: (usize, usize),
10628 w: usize,
10629 h: usize,
10630 mode: usize,
10631 uv_mode: usize,
10632 chroma_grids: [&[i32]; 2],
10633 ) {
10634 let (mi_r, mi_c) = at_mi;
10635 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10636 for cell in 0..w.div_ceil(SUB) {
10637 if c + cell >= self.above_mode.len() {
10638 break;
10639 }
10640 self.above_mode[c + cell] = mode;
10641 self.above_uv_mode[c + cell] = uv_mode;
10642 self.above_side[c + cell] = w;
10643 }
10644 for cell in 0..h.div_ceil(SUB) {
10645 if r + cell >= self.left_mode.len() {
10646 break;
10647 }
10648 self.left_mode[r + cell] = mode;
10649 self.left_uv_mode[r + cell] = uv_mode;
10650 self.left_side[r + cell] = h;
10651 }
10652
10653 let (w_mi, h_mi) = (w / MI, h / MI);
10654 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
10655 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
10656 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10657 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10658 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10659 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10660 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
10661 let plane = plane_idx + 1;
10662 let state = neighbour_state(grid);
10663 for cell in 0..h_mi {
10664 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
10665 self.left[mi_r + cell][plane] = state;
10666 }
10667 }
10668 for cell in 0..w_mi {
10669 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
10670 self.above[mi_c + cell][plane] = state;
10671 }
10672 }
10673 }
10674 }
10675}
10676
10677/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
10678/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
10679/// exactly — including its skip context, which the real key-frame writer
10680/// always writes at a fixed context of zero (it never tracks a neighbour-based
10681/// one for intra blocks; that is the inter-frame writer's rule instead).
10682/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
10683/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
10684/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
10685/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
10686/// plain DC chroma.
10687/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
10688/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
10689/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
10690/// instead (the defect commit 1a89ed9 fixed at the square sites).
10691pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
10692 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
10693 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
10694}
10695
10696/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
10697/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
10698/// bound (spec `filter_intra_mode_info` never reads a symbol there).
10699pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
10700 match side {
10701 4 => Some(0),
10702 8 => Some(1),
10703 16 => Some(2),
10704 32 => Some(3),
10705 _ => None,
10706 }
10707}
10708
10709/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
10710/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
10711/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
10712/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
10713fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
10714 match (bw, bh) {
10715 (32, 16) => Some(4),
10716 (16, 32) => Some(5),
10717 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
10718 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
10719 // here dropped that symbol on every DC_PRED strip of that size and
10720 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
10721 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
10722 (16, 8) => Some(6),
10723 (8, 16) => Some(7),
10724 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
10725 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
10726 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
10727 (4, 8) => Some(8),
10728 (8, 4) => Some(9),
10729 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
10730 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
10731 // `use_filter_intra` symbol on those strips although aomenc writes
10732 // one for every DC_PRED block of that shape with
10733 // `--enable-filter-intra=1` (its default), silently desyncing the
10734 // tile (class symbol-consumption-gap).
10735 (32, 8) => Some(10),
10736 (8, 32) => Some(11),
10737 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
10738 // strips), rows 17/16 of `default_filter_intra_cdfs`.
10739 (16, 4) => Some(12),
10740 (4, 16) => Some(13),
10741 _ if bw == bh => filter_intra_size_class(bw),
10742 _ => None,
10743 }
10744}
10745
10746/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
10747/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
10748/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
10749/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
10750/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
10751pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
10752 palette_bsize_ctx_wh(side, side)
10753}
10754
10755/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
10756/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
10757/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
10758/// for ANY bsize, not just the square ones a hand-picked table happened to
10759/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
10760/// row breaks the moment its indexing field moves off the diagonal, and a
10761/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
10762/// block dimension is a power of two, so `bw*bh` always is too and
10763/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
10764/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
10765fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
10766 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
10767 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
10768 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
10769 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
10770 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
10771 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
10772 if bw > 64 || bh > 64 || bw * bh < 64 {
10773 return None;
10774 }
10775 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
10776}
10777
10778/// A just-decoded palette-Y block's own size, base colours (only the first
10779/// `size` entries are real), and per-pixel colour-index map (`side*side`,
10780/// row-major, each entry `< size`).
10781struct PaletteY {
10782 size: usize,
10783 colors: [u16; 8],
10784 map: Vec<u8>,
10785}
10786
10787/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
10788/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
10789/// shared between U and V, both co-located after 4:2:0 subsampling) plus
10790/// each plane's own base colours.
10791struct PaletteUv {
10792 size: usize,
10793 u_colors: [u16; 8],
10794 v_colors: [u16; 8],
10795 map: Vec<u8>,
10796}
10797
10798/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
10799/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
10800/// `get_unsigned_bits`, which is the same formula): smallest `n` with
10801/// `2^n >= x`, `0` for `x <= 1`.
10802pub(crate) fn ceil_log2(x: u32) -> u32 {
10803 if x < 2 {
10804 0
10805 } else {
10806 32 - (x - 1).leading_zeros()
10807 }
10808}
10809
10810/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
10811/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
10812fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
10813 let l = ceil_log2(n as u32);
10814 let m = (1usize << l) - n;
10815 let v = dec.literal(l - 1) as usize;
10816 if v < m {
10817 v
10818 } else {
10819 (v << 1) - m + dec.literal(1) as usize
10820 }
10821}
10822
10823/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
10824/// colours (already-known, from the above/left neighbours) with the
10825/// ascending `transmitted` ones (delta-coded off the wire) back into one
10826/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
10827/// value picks the cached copy first, matching the C `<=`.
10828fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
10829 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
10830 let (mut ci, mut ti) = (0, 0);
10831 while ci < cached.len() && ti < transmitted.len() {
10832 if cached[ci] <= transmitted[ti] {
10833 out.push(cached[ci]);
10834 ci += 1;
10835 } else {
10836 out.push(transmitted[ti]);
10837 ti += 1;
10838 }
10839 }
10840 out.extend_from_slice(&cached[ci..]);
10841 out.extend_from_slice(&transmitted[ti..]);
10842 out
10843}
10844
10845/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
10846/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
10847/// each delta's width, the `range` bound and the clamp) is sized by
10848/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
10849/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
10850/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
10851/// the msac range, so a cross-decoder range ladder stays bit-identical
10852/// through the whole miscount -- only the decoded VALUE differs (class
10853/// `compare-range-not-tell`'s blind spot). (this
10854/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
10855/// (one flag bit each, in cache order), then delta-codes the remainder
10856/// (first value raw, each following delta `>= 1` off a shrinking bit width),
10857/// and merges the two ascending lists back together.
10858fn read_palette_colors_y(
10859 dec: &mut SymbolDecoder,
10860 n: usize,
10861 cache: &[u16],
10862 fctx: &crate::decode::FrameCtx,
10863) -> [u16; 8] {
10864 let mut cached = Vec::with_capacity(n);
10865 for &c in cache {
10866 if cached.len() >= n {
10867 break;
10868 }
10869 if dec.literal(1) == 1 {
10870 cached.push(c);
10871 }
10872 }
10873 let bd = u32::from(bit_depth(fctx));
10874 let max_val = (1i32 << bd) - 1;
10875 let mut colors = [0u16; 8];
10876 let n_cached = cached.len();
10877 if n_cached < n {
10878 let mut transmitted = Vec::with_capacity(n - n_cached);
10879 let first = dec.literal(bd) as u16;
10880 transmitted.push(first);
10881 if n_cached + 1 < n {
10882 let min_bits = bd - 3;
10883 let mut bits = min_bits + dec.literal(2);
10884 let mut range = (1i32 << bd) - i32::from(first) - 1;
10885 for _ in (n_cached + 1)..n {
10886 let delta = dec.literal(bits) as i32 + 1;
10887 let prev = *transmitted.last().unwrap();
10888 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
10889 range -= i32::from(val) - i32::from(prev);
10890 bits = bits.min(ceil_log2(range.max(0) as u32));
10891 transmitted.push(val);
10892 }
10893 }
10894 let merged = merge_colors(&transmitted, &cached);
10895 colors[..n].copy_from_slice(&merged);
10896 } else {
10897 colors[..n].copy_from_slice(&cached[..n]);
10898 }
10899 colors
10900}
10901
10902/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
10903/// `bit_depth` (see [`read_palette_colors_y`]): U reads
10904/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
10905/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
10906/// unbiased by `+1` -- both differences from Y's own reader, matching the C
10907/// side by side). V never uses a cache: a leading bit picks either `n` raw
10908/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
10909/// rather than clamp.
10910fn read_palette_colors_uv(
10911 dec: &mut SymbolDecoder,
10912 n: usize,
10913 cache: &[u16],
10914 fctx: &crate::decode::FrameCtx,
10915) -> ([u16; 8], [u16; 8]) {
10916 let mut cached = Vec::with_capacity(n);
10917 for &c in cache {
10918 if cached.len() >= n {
10919 break;
10920 }
10921 if dec.literal(1) == 1 {
10922 cached.push(c);
10923 }
10924 }
10925 let bd = u32::from(bit_depth(fctx));
10926 let max_val = 1i32 << bd;
10927 let mut u_colors = [0u16; 8];
10928 let n_cached = cached.len();
10929 if n_cached < n {
10930 let mut transmitted = Vec::with_capacity(n - n_cached);
10931 let first = dec.literal(bd) as u16;
10932 transmitted.push(first);
10933 if n_cached + 1 < n {
10934 let min_bits = bd - 3;
10935 let mut bits = min_bits + dec.literal(2);
10936 let mut range = max_val - i32::from(first);
10937 for _ in (n_cached + 1)..n {
10938 let delta = dec.literal(bits) as i32;
10939 let prev = *transmitted.last().unwrap();
10940 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
10941 range -= i32::from(val) - i32::from(prev);
10942 bits = bits.min(ceil_log2(range.max(0) as u32));
10943 transmitted.push(val);
10944 }
10945 }
10946 let merged = merge_colors(&transmitted, &cached);
10947 u_colors[..n].copy_from_slice(&merged);
10948 } else {
10949 u_colors[..n].copy_from_slice(&cached[..n]);
10950 }
10951 let mut v_colors = [0u16; 8];
10952 if dec.literal(1) == 1 {
10953 let min_bits_v = bd - 4;
10954 let bits = min_bits_v + dec.literal(2);
10955 v_colors[0] = dec.literal(bd) as u16;
10956 for i in 1..n {
10957 let mut delta = dec.literal(bits) as i32;
10958 if delta != 0 && dec.literal(1) == 1 {
10959 delta = -delta;
10960 }
10961 let mut val = i32::from(v_colors[i - 1]) + delta;
10962 if val < 0 {
10963 val += max_val;
10964 }
10965 if val >= max_val {
10966 val -= max_val;
10967 }
10968 v_colors[i] = val as u16;
10969 }
10970 } else {
10971 for i in 0..n {
10972 v_colors[i] = dec.literal(bd) as u16;
10973 }
10974 }
10975 (u_colors, v_colors)
10976}
10977
10978/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
10979/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
10980/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
10981const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
10982
10983/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
10984/// map's own per-pixel context and colour-order permutation, from the
10985/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
10986/// selection sort). `map`'s stride is `side` (this decoder never crops a
10987/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
10988/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
10989/// actual colour index to store.
10990pub(crate) fn palette_color_index_context(
10991 map: &[u8],
10992 side: usize,
10993 row: usize,
10994 col: usize,
10995 n: usize,
10996) -> (usize, [u8; 8]) {
10997 let left = if col >= 1 {
10998 Some(map[row * side + col - 1])
10999 } else {
11000 None
11001 };
11002 let up_left = if col >= 1 && row >= 1 {
11003 Some(map[(row - 1) * side + col - 1])
11004 } else {
11005 None
11006 };
11007 let up = if row >= 1 {
11008 Some(map[(row - 1) * side + col])
11009 } else {
11010 None
11011 };
11012 let mut scores = [0i32; 8];
11013 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
11014 if let Some(v) = neighbour {
11015 scores[v as usize] += weight;
11016 }
11017 }
11018 let mut color_order = [0u8; 8];
11019 for i in 0..8 {
11020 color_order[i] = i as u8;
11021 }
11022 for i in 0..3 {
11023 let mut max = scores[i];
11024 let mut max_idx = i;
11025 for j in (i + 1)..n {
11026 if scores[j] > max {
11027 max = scores[j];
11028 max_idx = j;
11029 }
11030 }
11031 if max_idx != i {
11032 let max_score = scores[max_idx];
11033 let max_color = color_order[max_idx];
11034 for k in (i + 1..=max_idx).rev() {
11035 scores[k] = scores[k - 1];
11036 color_order[k] = color_order[k - 1];
11037 }
11038 scores[i] = max_score;
11039 color_order[i] = max_color;
11040 }
11041 }
11042 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
11043 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
11044 (ctx as usize, color_order)
11045}
11046
11047/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
11048/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
11049/// cut by the frame's bottom or right mi edge codes its colour-index map only
11050/// over this part and replicates it outward -- reading the full `bw x bh` grid
11051/// consumed symbols libaom never wrote and desynced the rest of the tile
11052/// (lane-svtinter; class map-read-past-frame-edge).
11053fn palette_onscreen(
11054 mi_r: usize,
11055 mi_c: usize,
11056 bw: usize,
11057 bh: usize,
11058 fctx: &crate::decode::FrameCtx,
11059) -> (usize, usize) {
11060 // lane-palw: the ENCODER's own in-process reconstruct runs on a
11061 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
11062 // frame encoders publish the header's mi dims onto it themselves
11063 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
11064 // clamp and `tile::write_color_index_map`'s now agree there too.
11065 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
11066 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
11067}
11068
11069/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
11070/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
11071/// compute the same on-screen extent or the decoder reads a different number
11072/// of symbols than the encoder wrote.
11073pub(crate) fn palette_onscreen_dims(
11074 mi_r: usize,
11075 mi_c: usize,
11076 bw: usize,
11077 bh: usize,
11078 (mi_rows, mi_cols): (usize, usize),
11079) -> (usize, usize) {
11080 (
11081 bw.min(mi_cols.saturating_sub(mi_c) * MI),
11082 bh.min(mi_rows.saturating_sub(mi_r) * MI),
11083 )
11084}
11085
11086/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
11087/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
11088/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
11089/// together or a cut 8-wide block reads its chroma map at the wrong width.
11090/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
11091/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
11092/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
11093pub(crate) fn palette_onscreen_uv(
11094 luma: (usize, usize),
11095 on: (usize, usize),
11096 chroma: (usize, usize),
11097 ss: (usize, usize),
11098) -> (usize, usize) {
11099 (
11100 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
11101 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
11102 )
11103}
11104
11105/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
11106/// map's wavefront decode over a `side x side` grid, read over the on-screen
11107/// `on_side x on_side` corner (see [`palette_onscreen`]).
11108fn decode_color_index_map(
11109 dec: &mut SymbolDecoder,
11110 cdfs: &mut Cdfs,
11111 n: usize,
11112 side: usize,
11113 on: (usize, usize),
11114 uv: bool,
11115) -> Vec<u8> {
11116 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
11117}
11118
11119/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
11120/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
11121/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
11122/// independently rather than one shared `side` -- the square call above is
11123/// just `bw == bh`.
11124fn decode_color_index_map_wh(
11125 dec: &mut SymbolDecoder,
11126 cdfs: &mut Cdfs,
11127 n: usize,
11128 bw: usize,
11129 bh: usize,
11130 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
11131 on: (usize, usize),
11132 uv: bool,
11133) -> Vec<u8> {
11134 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
11135 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11136 if on_bw < bw || on_bh < bh {
11137 hit!(PALETTE_ONSCREEN_CUT_HITS);
11138 }
11139 let mut map = vec![0u8; bw * bh];
11140 if trace {
11141 let (rng, _) = dec.debug_state();
11142 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
11143 }
11144 map[0] = read_uniform(dec, n) as u8;
11145 if trace {
11146 let (rng, _) = dec.debug_state();
11147 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11148 }
11149 for i in 1..(on_bw + on_bh - 1) {
11150 let j_hi = i.min(on_bw - 1);
11151 let j_lo = i.saturating_sub(on_bh - 1);
11152 for j in (j_lo..=j_hi).rev() {
11153 let row = i - j;
11154 let col = j;
11155 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11156 if trace {
11157 let (rng, _) = dec.debug_state();
11158 let row_cdf = if uv {
11159 &cdfs.palette_uv_color_index[n - 2][ctx]
11160 } else {
11161 &cdfs.palette_y_color_index[n - 2][ctx]
11162 };
11163 eprintln!(
11164 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11165 row_cdf[0], row_cdf[n]
11166 );
11167 }
11168 let symbol = if uv {
11169 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11170 } else {
11171 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11172 };
11173 map[row * bw + col] = color_order[symbol];
11174 if trace {
11175 let (rng, _) = dec.debug_state();
11176 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11177 }
11178 }
11179 }
11180 palette_replicate(&mut map, bw, bh, on);
11181 map
11182}
11183
11184/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11185/// last on-screen column then the last on-screen row are replicated over the
11186/// off-screen remainder, so the prediction still covers the whole block. The
11187/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11188/// so the pixels it prices and reconstructs are the ones the on-screen
11189/// symbols it writes really decode to.
11190pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11191 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11192 for row in 0..on_bh {
11193 let last = map[row * bw + on_bw - 1];
11194 map[row * bw + on_bw..row * bw + bw].fill(last);
11195 }
11196 for row in on_bh..bh {
11197 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11198 }
11199}
11200
11201/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11202/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11203/// size class comes from [`filter_intra_size_class_rect`] instead of the
11204/// square-only [`filter_intra_size_class`], and the palette read (when
11205/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11206/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11207/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11208/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11209#[allow(clippy::too_many_arguments)]
11210fn read_intra_mode_rect(
11211 dec: &mut SymbolDecoder,
11212 cdfs: &mut Cdfs,
11213 above_mode: usize,
11214 left_mode: usize,
11215 cfl: bool,
11216 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11217 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11218 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11219 // chroma is coded once, on the closing strip). Every other caller is a
11220 // block big enough to own its chroma and passes `true`.
11221 has_chroma: bool,
11222 bw: usize,
11223 bh: usize,
11224 enable_filter_intra: bool,
11225 skip_ctx: usize,
11226 allow_screen_content_tools: bool,
11227 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11228 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11229 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11230 palette: Option<(usize, &[u16])>,
11231 palette_uv_cache: &[u16],
11232 mi_r: usize,
11233 mi_c: usize,
11234 fctx: &crate::decode::FrameCtx,
11235) -> Result<(
11236 bool,
11237 usize,
11238 i32,
11239 usize,
11240 i32,
11241 Option<(i32, i32)>,
11242 Option<usize>,
11243 Option<PaletteY>,
11244 Option<PaletteUv>,
11245 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11246 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11247 // straight out of `read_intra_frame_mode_info` then, so every later field
11248 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11249 // no filter intra). A caller that can reconstruct intrabc at its shape
11250 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11251 // name with the same string it always did.
11252 Option<(i32, i32)>,
11253)> {
11254 // lane-av1mono: libaom guards every chroma symbol read with
11255 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11256 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11257 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11258 // into the same `has_chroma` this reader already gates on.
11259 let has_chroma = has_chroma && !mono(fctx);
11260 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11261 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11262 if ec_istep {
11263 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11264 // (decodemv.c:818), printed at the same point: before the first
11265 // mode-info symbol of the block, so a cross-decoder range ladder can
11266 // be keyed on the BLOCK, not just on the symbol sequence.
11267 eprintln!(
11268 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11269 enable_filter_intra as i32,
11270 filter_intra_size_class_rect(bw, bh),
11271 dec.debug_state().0
11272 );
11273 }
11274 macro_rules! istep {
11275 ($name:literal, $val:expr) => {
11276 if ec_istep {
11277 let (rng, _) = dec.debug_state();
11278 eprintln!(
11279 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11280 $name, $val
11281 );
11282 }
11283 };
11284 }
11285 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11286 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11287 // the one point every rect caller routes through, so no call site can
11288 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11289 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11290 let cfl = if cfl && bw.max(bh) > 32 {
11291 hit!(NOCFL_UV_MODE_HITS);
11292 false
11293 } else {
11294 cfl
11295 };
11296 // lane-intra14 r1: on the INTER block path everything up to and including
11297 // `is_inter` was already read by [`decode_inter_block`], so this reader
11298 // starts at the mode syntax with the `skip` that caller read.
11299 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11300 let skip = if let Some((_, skip)) = inter {
11301 skip
11302 } else {
11303 // Same `intra_segment_id` placement as the square reader above.
11304 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11305 if seg_id_pre_skip(fctx) {
11306 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11307 }
11308 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11309 istep!("skip", skip as i32);
11310 if !seg_id_pre_skip(fctx) {
11311 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11312 }
11313 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11314 istep!("cdef", 0);
11315 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11316 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11317 // `false`.
11318 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11319 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11320 istep!("dq", 0);
11321 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11322 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11323 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11324 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11325 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11326 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11327 // decoder at the FIRST symbol of the first rect block of every
11328 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11329 // block at this shape is out of scope, so the flag is consumed and
11330 // refused by name when it fires.
11331 if allow_intrabc_frame(fctx) {
11332 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11333 hit!(RECT_INTRABC_READS);
11334 istep!("intrabc", use_intrabc as i32);
11335 if use_intrabc {
11336 hit!(INTRABC_HITS);
11337 // libaom `read_intrabc_info`: the DV read, then an immediate
11338 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
11339 // no angle deltas, no palette, no filter intra. The caller owns
11340 // the reconstruction at its own shape.
11341 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
11342 return Ok((
11343 skip,
11344 DC_PRED,
11345 0,
11346 DC_PRED,
11347 0,
11348 None,
11349 None,
11350 None,
11351 None,
11352 Some(dv),
11353 ));
11354 }
11355 }
11356 skip
11357 };
11358 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
11359 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
11360 // off `kf_y_mode_cdf[above][left]`).
11361 let mode = if let Some((size_group, _)) = inter {
11362 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
11363 dec.symbol(&mut cdfs.y_mode[size_group])
11364 } else {
11365 let above_ctx = INTRA_MODE_CTX[above_mode];
11366 let left_ctx = INTRA_MODE_CTX[left_mode];
11367 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
11368 };
11369 istep!("mode", mode as i32);
11370 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11371 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11372 } else {
11373 0
11374 };
11375 istep!("angle_y", angle_delta_y);
11376 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
11377 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
11378 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
11379 // here, from the block's own size, is the single point every caller routes
11380 // through -- a caller passing `true` for a >32 strip used to pick the
11381 // 14-symbol CFL CDF, same value but a different range (class
11382 // wrong-alphabet-same-value).
11383 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
11384 let uv_mode = if !has_chroma {
11385 DC_PRED
11386 } else if cfl {
11387 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11388 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11389 } else {
11390 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11391 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11392 };
11393 istep!("uv_mode", uv_mode as i32);
11394 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
11395 Some(read_cfl_alphas(dec, cdfs))
11396 } else {
11397 None
11398 };
11399 if has_chroma && (9..=12).contains(&uv_mode) {
11400 hit!(SMOOTH_UV_HITS);
11401 }
11402 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
11403 hit!(DIRECTIONAL_UV_HITS);
11404 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11405 } else {
11406 0
11407 };
11408 istep!("angle_uv", angle_delta_uv);
11409 if angle_delta_uv != 0 {
11410 hit!(UV_ANGLE_DELTA_HITS);
11411 }
11412 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
11413 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
11414 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
11415 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
11416 // colours only here, the colour-index maps deferred past `filter_intra`
11417 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
11418 // runs from the caller, after the whole mode-info read).
11419 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11420 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11421 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
11422 // r6: this is the exact site the removed blanket refusal used to
11423 // guard -- reached for EVERY rect strip in a screen-content frame,
11424 // independent of whether the block ends up using a palette.
11425 hit!(RECT_SCREEN_CONTENT_HITS);
11426 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11427 let use_palette_y =
11428 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11429 if use_palette_y {
11430 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11431 let colors = read_palette_colors_y(dec, n, cache, fctx);
11432 palette_y_pending = Some((n, colors));
11433 }
11434 let palette_uv_mode_ctx = usize::from(use_palette_y);
11435 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
11436 if has_chroma
11437 && uv_mode == DC_PRED
11438 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
11439 {
11440 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11441 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
11442 palette_uv_pending = Some((n, u_colors, v_colors));
11443 }
11444 }
11445 let mut filter_intra = None;
11446 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11447 let (rng, _) = dec.debug_state();
11448 eprintln!(
11449 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
11450 class={:?} rng={rng}",
11451 enable_filter_intra as i32,
11452 filter_intra_size_class_rect(bw, bh)
11453 );
11454 }
11455 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
11456 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
11457 if mode == DC_PRED
11458 && enable_filter_intra
11459 && palette_y_pending.is_none()
11460 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11461 {
11462 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11463 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11464 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
11465 }
11466 istep!("use_filter_intra", use_filter_intra as i32);
11467 if use_filter_intra {
11468 hit!(FILTER_INTRA_HITS);
11469 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11470 istep!("filter_intra_mode", fi_mode as i32);
11471 filter_intra = Some(fi_mode);
11472 }
11473 }
11474 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
11475 // same order as [`read_intra_mode`]'s own square path.
11476 let palette_y = palette_y_pending.map(|(n, colors)| {
11477 let map = decode_color_index_map_wh(
11478 dec,
11479 cdfs,
11480 n,
11481 bw,
11482 bh,
11483 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11484 false,
11485 );
11486 hit!(PALETTE_HITS);
11487 hit!(PALETTE_RECT_HITS);
11488 PaletteY {
11489 size: n,
11490 colors,
11491 map,
11492 }
11493 });
11494 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11495 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
11496 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
11497 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
11498 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
11499 // chroma palette and desynced the tile from there.
11500 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11501 let on = palette_onscreen_uv(
11502 (bw, bh),
11503 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11504 (cw, ch),
11505 (ss_x(fctx), ss_y(fctx)),
11506 );
11507 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11508 hit!(PALETTE_UV_HITS);
11509 PaletteUv {
11510 size: n,
11511 u_colors,
11512 v_colors,
11513 map,
11514 }
11515 });
11516 Ok((
11517 skip,
11518 mode,
11519 angle_delta_y,
11520 uv_mode,
11521 angle_delta_uv,
11522 alpha,
11523 filter_intra,
11524 palette_y,
11525 palette_uv,
11526 None,
11527 ))
11528}
11529
11530/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
11531/// at the strip's REAL mi position. `av1_get_palette_cache` reads
11532/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
11533/// block, so each strip owns its own rows and columns and no aliasing rule
11534/// is needed (lane-kf900 r6).
11535#[allow(clippy::too_many_arguments)]
11536fn record_strip_palette(
11537 n: &mut Neighbours,
11538 mi: (usize, usize),
11539 bw: usize,
11540 bh: usize,
11541 y_size: usize,
11542 y_colors: [u16; 8],
11543 uv_size: usize,
11544 uv_colors: [u16; 8],
11545) {
11546 let (r, c) = mi;
11547 // lane-t900 r23 rung: every publication of a block's palette state into
11548 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
11549 // path left a stale `left_palette_size` behind when
11550 // `av1_get_palette_mode_ctx` disagrees with libaom's.
11551 if crate::envflags::env_flag!("EC_PALPUB") {
11552 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
11553 }
11554 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
11555 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
11556 // existed because the 16px [`SUB`] cell held one slot for all the strips
11557 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
11558 // real neighbour leaf 1 reads.
11559 {
11560 for cell in 0..(bw / MI).max(1) {
11561 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
11562 *e = y_size as u8;
11563 n.above_palette_uv_size[c + cell] = uv_size as u8;
11564 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
11565 // colours of a size-0 neighbour are never read.
11566 if y_size > 0 {
11567 n.above_palette_colors[c + cell] = y_colors;
11568 }
11569 if uv_size > 0 {
11570 n.above_palette_uv_colors[c + cell] = uv_colors;
11571 }
11572 }
11573 }
11574 }
11575 {
11576 for cell in 0..(bh / MI).max(1) {
11577 if n.left_palette_size.get(r + cell).is_none() {
11578 break;
11579 }
11580 n.left_palette_size[r + cell] = y_size as u8;
11581 n.left_palette_uv_size[r + cell] = uv_size as u8;
11582 if y_size > 0 {
11583 n.left_palette_colors[r + cell] = y_colors;
11584 }
11585 if uv_size > 0 {
11586 n.left_palette_uv_colors[r + cell] = uv_colors;
11587 }
11588 }
11589 }
11590}
11591
11592/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
11593fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
11594 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
11595 i32::from(y.data[ly * y.width + lx])
11596 })
11597}
11598
11599/// Everything a rect strip already read out of the stream before its luma
11600/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
11601/// (nine values that would otherwise be nine more parameters).
11602struct RectStripModes {
11603 skip: bool,
11604 mode: usize,
11605 angle_delta_y: i32,
11606 uv_predict_mode: usize,
11607 angle_delta_uv: i32,
11608 alpha: Option<(i32, i32)>,
11609 filter_intra: Option<usize>,
11610 smooth_neighbor: bool,
11611 smooth_neighbor_uv: bool,
11612 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
11613 /// mapped through the colour table), sliced per transform unit below --
11614 /// palette prediction reads no edge pixels, so a unit's slice of the
11615 /// whole-block map IS its prediction. Without this a palette strip whose
11616 /// transform splits predicted DC and came out flat grey while the entropy
11617 /// stream stayed in sync (the coefficients are read either way).
11618 palette_y: Option<Vec<u16>>,
11619 /// As `palette_y`, for the un-split chroma transform (U, V).
11620 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
11621}
11622
11623/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
11624/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
11625/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
11626/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
11627/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
11628/// TX_32X16`) and only the second reaches a square -- the reason
11629/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
11630/// already square) mis-tiled 1:4 strips.
11631fn depth_to_tx_wh(
11632 bw: usize,
11633 bh: usize,
11634 depth: usize,
11635 fctx: &crate::decode::FrameCtx,
11636) -> (usize, usize) {
11637 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
11638 // `read_tx_size`: the lossless early return comes before
11639 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
11640 if lossless(fctx) {
11641 return (4, 4);
11642 }
11643 let (mut w, mut h) = (bw.min(64), bh.min(64));
11644 for _ in 0..depth {
11645 match w.cmp(&h) {
11646 std::cmp::Ordering::Greater => w /= 2,
11647 std::cmp::Ordering::Less => h /= 2,
11648 std::cmp::Ordering::Equal => {
11649 w /= 2;
11650 h /= 2;
11651 }
11652 }
11653 }
11654 (w, h)
11655}
11656
11657/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
11658/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
11659/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
11660/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
11661/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
11662/// 2-px-wide area is not a transform shape. The strip pairs with its
11663/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
11664/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
11665/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
11666/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
11667/// the entropy context on the floored cell. Returns
11668/// `(pair block width, pair block height, write anchor x, entropy mi column)`
11669/// for that pair, or `None` when the strip keeps its own plane block at its
11670/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
11671/// 2 px wide) and every 4:2:2 strip of 8 px or more.
11672fn chroma422_pair_plane(
11673 ss_x: bool,
11674 ss_y: bool,
11675 mi_col: usize,
11676 bw: usize,
11677 bh: usize,
11678) -> Option<(usize, usize, usize, usize)> {
11679 if ss_x && !ss_y && (bw >> 1) == 2 {
11680 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
11681 } else {
11682 None
11683 }
11684}
11685
11686/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
11687/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
11688/// rect path here refused by name until now ("per-unit rect prediction is not
11689/// ported").
11690///
11691/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
11692/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
11693/// strip the very first step already lands on a SQUARE transform
11694/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
11695/// every further step halves a square) -- so each unit is square and reads
11696/// through the ordinary square [`read_plane`]. What is genuinely rectangular
11697/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
11698/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
11699/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
11700/// split by luma's depth.
11701///
11702/// Each unit predicts off whatever the earlier units of this same block
11703/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
11704/// inside `av1_foreach_transformed_block`, raster order), which is exactly
11705/// what predicting the whole strip in one shot got wrong.
11706#[allow(clippy::too_many_arguments)]
11707fn decode_rect_split(
11708 dec: &mut SymbolDecoder,
11709 cdfs: &mut Cdfs,
11710 neighbours: &mut Neighbours,
11711 at_mi: (usize, usize),
11712 bw: usize,
11713 bh: usize,
11714 // The transform unit's own width and height in pixels. Square for every
11715 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
11716 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
11717 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
11718 tx_w: usize,
11719 tx_h: usize,
11720 m: &RectStripModes,
11721 y: &mut PlaneBuf<'static>,
11722 u: &mut PlaneBuf<'static>,
11723 v: &mut PlaneBuf<'static>,
11724 base_q_idx: u8,
11725 reduced_tx_set: bool,
11726 fctx: &crate::decode::FrameCtx,
11727) -> Result<()> {
11728 let (mi_r, mi_c) = at_mi;
11729 let (px, py) = (mi_c * MI, mi_r * MI);
11730 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
11731 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
11732 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
11733 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
11734 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
11735 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
11736 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
11737 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
11738 // measurement). The plane is still coded -- `decode_token_recon_block`
11739 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
11740 // 4x8 rect units, plane-major.
11741 let chroma_422_oob = ss_x(fctx) == 1
11742 && ss_y(fctx) == 0
11743 && matches!(
11744 (bw, bh),
11745 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
11746 );
11747 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
11748 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
11749 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
11750 // plane is then `(4, chroma_h)` written at the FLOORED cell
11751 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
11752 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
11753 // the same walk the (8, 32) class takes). The lossless raster arm keeps
11754 // the strip's own geometry: no caller of this function can present a
11755 // 4-wide strip yet (the enumeration test pins the five callers at
11756 // `8 <= min`), and the skip/tiled arms are the routes a future caller
11757 // needs.
11758 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
11759 let chroma_422_pair_wide = chroma422_pair.is_some();
11760 let (chroma_block_w, chroma_block_h, chroma_x) =
11761 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
11762 // The chroma transform is picked before any symbol is read, so an
11763 // unsupported chroma shape refuses before this strip desyncs the tile.
11764 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
11765 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
11766 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
11767 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
11768 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
11769 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
11770 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
11771 // squares a rect transform down to a CDF set by
11772 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
11773 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
11774 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
11775 // paths already prove for these same shapes.
11776 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
11777 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
11778 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
11779 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
11780 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
11781 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
11782 _ => None,
11783 };
11784 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
11785 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
11786 // below; everything else still needs a single-unit table.
11787 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
11788 // halves only the width, so a rect luma strip codes a SQUARE chroma block
11789 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
11790 // rect strip's chroma is itself rect, so the square rows are unreachable
11791 // there and cannot change their results.
11792 // lane-av1-422blockhalf: the tiled arms below handle every shape this
11793 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
11794 // diagnostic names only the shapes that would actually refuse -- it used
11795 // to fire for every tiled square too (the parent lane's `chroma=8x8`
11796 // rows) and sent the next lane chasing handled shapes.
11797 let chroma_tiled = chroma_422_pair_wide
11798 || chroma_422_oob
11799 || matches!(
11800 (chroma_w, chroma_h),
11801 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
11802 );
11803 if !m.skip {
11804 if let Some(i) = match (chroma_w, chroma_h) {
11805 (32, 8) => Some(0),
11806 (8, 32) => Some(1),
11807 (8, 4) => Some(2),
11808 (4, 8) => Some(3),
11809 _ => None,
11810 } {
11811 hit_do! {
11812 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
11813 let mut hits = c.get();
11814 hits[i] += 1;
11815 c.set(hits);
11816 });
11817 }
11818 }
11819 if !m.skip && chroma.is_none() && !chroma_tiled {
11820 // Diagnostic for the next caller that lands here (class
11821 // refusal-names-a-correlate: the message names the tool, not the
11822 // shape); the refusal below keeps its inventory-pinned wording.
11823 eprintln!(
11824 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
11825 chroma={chroma_w}x{chroma_h}"
11826 );
11827 }
11828 }
11829 // lane-rectsplit r2 (verifier finding): with both callers wired
11830 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
11831 // 64x32/32x64) every shape that reaches here has a table above, so this
11832 // arm is UNREACHABLE today. It stays as the shape guard for the next
11833 // caller -- a new strip size would otherwise hit the `expect` below and
11834 // panic instead of refusing by name -- and so stays in
11835 // `refusal_inventory::REFUSALS`.
11836 if !m.skip && chroma.is_none() && !chroma_tiled {
11837 return Err(unsupported(
11838 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
11839 ));
11840 }
11841 hit!(RECT_SPLIT_TX_HITS);
11842 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
11843 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
11844 }
11845 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
11846 // A square unit reads through the ordinary square [`read_plane`]; a rect
11847 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
11848 // the very tables the unsplit 16x8/32x16 paths use.
11849 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
11850 (w, h) if w == h => None,
11851 (16, 8) | (8, 16) => Some((
11852 if reduced_tx_set {
11853 TxbSet::LumaRect16x8
11854 } else {
11855 TxbSet::LumaRect16x8Set1
11856 },
11857 if tx_w == 16 {
11858 &SCAN_16X8[..]
11859 } else {
11860 &SCAN_8X16[..]
11861 },
11862 )),
11863 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
11864 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
11865 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
11866 // strip, read through the `luma_64corner` arm below instead of a rect
11867 // table -- a 64-length axis codes only its low 32 coefficients
11868 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
11869 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
11870 // depth-0 arm already reads on the key-frame path.
11871 //
11872 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
11873 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
11874 // sub-8x8 intra leaves still refused: with those lifted (r2) the
11875 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
11876 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
11877 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
11878 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
11879 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
11880 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
11881 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
11882 (64, 32) | (32, 64) => None,
11883 _ => {
11884 return Err(unsupported(format!(
11885 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
11886 coefficient tables for that shape here)"
11887 )));
11888 }
11889 };
11890 // The `None` above that is NOT the square arm.
11891 let luma_64corner = tx_w != tx_h;
11892 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
11893 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
11894 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
11895 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
11896 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
11897 // per-unit rect walk stay wired above/below; the round that finds that
11898 // defect deletes this refusal and nothing else.
11899 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
11900 let luma_scan = default_scan(tx_w.min(tx_h));
11901 let zero_tu = vec![0i32; tx_w * tx_h];
11902 // The strip's OWN edge availability, the fallback for a transform unit
11903 // whose top-right/bottom-left pixels fall outside the strip.
11904 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11905 for tu_row in 0..bh / tx_h {
11906 for tu_col in 0..bw / tx_w {
11907 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
11908 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11909 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
11910 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
11911 // libaom clips `av1_foreach_transformed_block_in_plane` to
11912 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
11913 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
11914 // TOP-LEFT sample falls outside the frame is never coded. We read
11915 // coefficients for those phantom units and desynced the stream at
11916 // the very next symbol.
11917 if tu_px >= y.true_width || tu_py >= y.true_height {
11918 continue;
11919 }
11920 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
11921 // transform unit INSIDE a block, which is a different rule from
11922 // the standalone-block table [`Reach::of`] applies -- and the
11923 // reason a depth-2 superblock strip came out one sample off
11924 // before this: `Reach::of(tx, ..)` answered as if the unit were
11925 // its own block at that superblock position.
11926 // * top-right: if the unit's right neighbour is still inside the
11927 // strip the pixels are already reconstructed (`col_off +
11928 // tx_wide < plane_bw`); otherwise only the strip's own top row
11929 // of units can reach past it, through the block-level answer.
11930 // * bottom-left: a unit that is not in the strip's left column
11931 // has none (`col_off > 0` returns 0); inside the strip
11932 // (`row_off + tx_high < plane_bh`) they are the left
11933 // neighbour's, already reconstructed; the last row falls back
11934 // to the block-level answer.
11935 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
11936 // The unit's own window on the block's palette prediction.
11937 if let Some(buf) = &m.palette_y {
11938 let tu_buf: Vec<u16> = (0..tx_h)
11939 .flat_map(|i| {
11940 let base = (row_off + i) * bw + col_off;
11941 buf[base..base + tx_w].iter().copied()
11942 })
11943 .collect();
11944 set_palette_pred(tu_buf, fctx);
11945 }
11946 if m.skip {
11947 push_intra_rect(
11948 0,
11949 tu_px,
11950 tu_py,
11951 tx_w,
11952 tx_h,
11953 m.mode,
11954 m.angle_delta_y,
11955 tu_reach,
11956 &zero_tu,
11957 None,
11958 m.filter_intra,
11959 m.smooth_neighbor,
11960 fctx,
11961 );
11962 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11963 } else if luma_64corner && luma_rect.is_none() {
11964 // The un-split 64-level luma transform: `read_coeffs` on the
11965 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
11966 // and the real rect shape passed through for
11967 // `av1_nz_map_ctx_offset` -- byte for byte
11968 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
11969 // 64-level strip gate already proves. `tx_type` is not coded
11970 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
11971 // the square-up size is TX_64X64), and this unit covers its
11972 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
11973 if crate::envflags::env_flag!("EC_RECT64TU") {
11974 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
11975 }
11976 hit_do! {
11977 RECT64_CORNER_TU_HITS.with(|c| {
11978 let mut v = c.get();
11979 v[usize::from(tx_h > tx_w)] += 1;
11980 c.set(v);
11981 });
11982 }
11983 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11984 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
11985 let (corner, tu_tx_type) = read_coeffs(
11986 dec,
11987 &mut coding,
11988 default_scan(TX32),
11989 0,
11990 dc_sign_ctx(tu_around.2),
11991 TxType::DctDct,
11992 Some((tx_w, tx_h)),
11993 )?;
11994 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
11995 let mut tu_grid = vec![0i32; tx_w * tx_h];
11996 for row in 0..ch {
11997 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
11998 }
11999 let residual = dequant_and_inverse_typed_wh(
12000 &tu_grid,
12001 tx_w,
12002 tx_h,
12003 crate::decode::bit_depth(fctx),
12004 block_q_idx(fctx),
12005 plane_q_delta(0, fctx).0,
12006 plane_q_delta(0, fctx).1,
12007 tu_tx_type,
12008 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12009 );
12010 push_intra_rect(
12011 0,
12012 tu_px,
12013 tu_py,
12014 tx_w,
12015 tx_h,
12016 m.mode,
12017 m.angle_delta_y,
12018 tu_reach,
12019 &residual,
12020 None,
12021 m.filter_intra,
12022 m.smooth_neighbor,
12023 fctx,
12024 );
12025 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12026 } else if let Some((rect_set, rect_scan)) = luma_rect {
12027 // The rect-unit twin of the square arm below: same contexts,
12028 // same order, through the rect coefficient reader. The
12029 // `tx_type` CDF row of a filter-intra block is
12030 // `fimode_to_intradir[filter_intra_mode]`, never the block's
12031 // own (always DC_PRED) mode -- [`read_plane`] applies that
12032 // for the square arm, so this one must too.
12033 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12034 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
12035 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
12036 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
12037 // neighbour-magnitude table is for a unit SMALLER than its
12038 // block. [`decode_block_rect`]'s own unsplit read passes a
12039 // literal 0 for the same reason; this arm applied the table
12040 // unconditionally and desynced every depth-0 rect strip that
12041 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
12042 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
12043 0
12044 } else {
12045 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
12046 };
12047 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
12048 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12049 dec,
12050 &mut coding,
12051 rect_scan,
12052 tx_w,
12053 tx_h,
12054 tu_skip_ctx,
12055 dc_sign_ctx(tu_around.2),
12056 TxType::DctDct,
12057 0,
12058 )?;
12059 let residual = dequant_and_inverse_typed_wh(
12060 &tu_grid,
12061 tx_w,
12062 tx_h,
12063 crate::decode::bit_depth(fctx),
12064 block_q_idx(fctx),
12065 plane_q_delta(0, fctx).0,
12066 plane_q_delta(0, fctx).1,
12067 tu_tx_type,
12068 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12069 );
12070 push_intra_rect(
12071 0,
12072 tu_px,
12073 tu_py,
12074 tx_w,
12075 tx_h,
12076 m.mode,
12077 m.angle_delta_y,
12078 tu_reach,
12079 &residual,
12080 None,
12081 m.filter_intra,
12082 m.smooth_neighbor,
12083 fctx,
12084 );
12085 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12086 } else {
12087 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12088 // This unit is smaller than the block it sits in, so
12089 // `txb_skip_ctx` is the neighbour-magnitude table, not the
12090 // lone-TU 0 (spec `get_txb_ctx_general`).
12091 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12092 let tu_grid = read_plane(
12093 dec,
12094 cdfs,
12095 luma_set,
12096 &luma_scan,
12097 0,
12098 tu_around,
12099 m.mode,
12100 m.mode,
12101 m.angle_delta_y,
12102 tu_reach,
12103 y,
12104 tu_px,
12105 tu_py,
12106 tx_w,
12107 tx_w,
12108 base_q_idx,
12109 None,
12110 m.filter_intra,
12111 Some(tu_skip_ctx),
12112 m.smooth_neighbor,
12113 fctx,
12114 )?;
12115 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12116 }
12117 }
12118 }
12119 // CHROMA: one un-split rect transform for the whole strip.
12120 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
12121 // units -- each stamps its own neighbour context as it is read, and the
12122 // whole-block `record_split_luma_rect_mi` below would overwrite all of
12123 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
12124 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
12125 // collected here and replayed after that record.
12126 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12127 // The chroma_tiled arm below stamps each unit's coefficient context
12128 // immediately (so the NEXT unit reads it), then the whole-strip
12129 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
12130 // whole-strip state and the per-unit DC signs and levels are lost
12131 // (class `override-slot-on-one-arm`). The units are collected here and
12132 // replayed after that record, the way the lossless arm's
12133 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
12134 // already do.
12135 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12136 let ac = m.alpha.map(|_| {
12137 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
12138 // luma -- the 8-px-wide region the floored 4-px chroma block covers
12139 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
12140 if chroma_422_pair_wide {
12141 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
12142 } else {
12143 cfl_src_rect(px, py, bw, bh)
12144 }
12145 });
12146 let reach = if chroma_422_pair_wide {
12147 // The chroma units predict off the PAIR block's edges: an odd-column
12148 // strip's pair starts 4 luma px to the strip's left, so the strip's
12149 // own answer names the wrong above/right samples (the pair16 arm's
12150 // `pair_reach`, one partition level up).
12151 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12152 } else {
12153 block_reach
12154 };
12155 let (u_grid, v_grid) = if mono(fctx) {
12156 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12157 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12158 // section -- the skipped-strip pushes, the lossless raster and the
12159 // un-split `read_coeffs_rect` below -- is bypassed.
12160 let zero = Grid::Zero(chroma_w * chroma_h);
12161 (zero.clone(), zero)
12162 } else if m.skip {
12163 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12164 if chroma_422_pair_wide || chroma_422_oob {
12165 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12166 // per transform unit even when the strip is skipped
12167 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12168 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12169 // units -- one whole-plane push here would ask the intra
12170 // predictor for a 1:8 rect it never needs.
12171 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12172 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12173 // grid at the floored anchor `chroma_x`.
12174 let (uw, uh) = (4usize, 8usize);
12175 for plane_idx in 1..=2 {
12176 if let Some((ub, vb)) = &m.palette_uv {
12177 let buf = if plane_idx == 1 { ub } else { vb };
12178 set_palette_pred(buf.clone(), fctx);
12179 }
12180 for cu_row in 0..chroma_block_h / uh {
12181 for cu_col in 0..chroma_block_w / uw {
12182 push_intra_rect(
12183 plane_idx,
12184 chroma_x + cu_col * uw,
12185 cpy + cu_row * uh,
12186 uw,
12187 uh,
12188 m.uv_predict_mode,
12189 m.angle_delta_uv,
12190 reach,
12191 &ZERO_RESIDUAL[..uw * uh],
12192 m.alpha
12193 .zip(ac.clone())
12194 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12195 None,
12196 m.smooth_neighbor_uv,
12197 fctx,
12198 );
12199 }
12200 }
12201 }
12202 } else {
12203 if let Some((ub, _)) = &m.palette_uv {
12204 set_palette_pred(ub.clone(), fctx);
12205 }
12206 push_intra_rect(
12207 1,
12208 cpx,
12209 cpy,
12210 chroma_w,
12211 chroma_h,
12212 m.uv_predict_mode,
12213 m.angle_delta_uv,
12214 reach,
12215 &zero,
12216 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12217 None,
12218 m.smooth_neighbor_uv,
12219 fctx,
12220 );
12221 if let Some((_, vb)) = &m.palette_uv {
12222 set_palette_pred(vb.clone(), fctx);
12223 }
12224 push_intra_rect(
12225 2,
12226 cpx,
12227 cpy,
12228 chroma_w,
12229 chroma_h,
12230 m.uv_predict_mode,
12231 m.angle_delta_uv,
12232 reach,
12233 &zero,
12234 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12235 None,
12236 m.smooth_neighbor_uv,
12237 fctx,
12238 );
12239 }
12240 (zero.clone(), zero)
12241 } else if lossless(fctx) {
12242 // lane-lossless: the strip's chroma plane block is coded as 4x4
12243 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12244 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12245 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12246 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12247 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12248 // offset (our `+3` row base) whenever the plane block is bigger than
12249 // the transform.
12250 let scan4 = default_scan(4);
12251 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12252 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12253 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12254 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12255 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12256 // cell), and the 8-px step made every unit past the first column/row
12257 // read its `txb_skip` context at the WRONG mi (two cells over) and
12258 // stamp a 2-cell span with one unit's state -- the polluted above-band
12259 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12260 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12261 // ours read `above[28..29]` where the oracle read `above[26]`).
12262 let span_x = 4 << ss_x(fctx);
12263 let span_y = 4 << ss_y(fctx);
12264 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12265 for plane_idx in 1..=2 {
12266 for cu_row in 0..ch_n {
12267 for cu_col in 0..cw_n {
12268 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12269 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
12270 let cu_reach = tu_reach(
12271 bw,
12272 bh,
12273 cu_col * span_x,
12274 cu_row * span_y,
12275 span_x,
12276 block_reach,
12277 px,
12278 py,
12279 y.width,
12280 y.height,
12281 fctx,
12282 );
12283 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12284 if let Some((ub, vb)) = &m.palette_uv {
12285 let pbuf = if plane_idx == 1 { ub } else { vb };
12286 set_palette_pred(
12287 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12288 fctx,
12289 );
12290 }
12291 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12292 let grid = read_plane(
12293 dec,
12294 cdfs,
12295 TxbSet::Chroma4,
12296 &scan4,
12297 plane_idx,
12298 cu_around[plane_idx],
12299 m.mode,
12300 m.uv_predict_mode,
12301 m.angle_delta_uv,
12302 cu_reach,
12303 plane,
12304 cu_x,
12305 cu_y,
12306 4,
12307 4,
12308 base_q_idx,
12309 m.alpha
12310 .zip(ac)
12311 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12312 None,
12313 offset,
12314 m.smooth_neighbor_uv,
12315 fctx,
12316 )?;
12317 if span_x == 4 && span_y == 4 {
12318 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
12319 }
12320 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
12321 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
12322 last[plane_idx - 1] = grid;
12323 }
12324 }
12325 }
12326 let [ug, vg] = last;
12327 (ug, vg)
12328 } else if chroma_tiled {
12329 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
12330 if chroma_422_pair_wide || chroma_422_oob {
12331 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
12332 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
12333 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
12334 // see above). For the 4-wide strip the units tile the PAIR's
12335 // plane, stepping from the floored anchor.
12336 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
12337 } else {
12338 match (chroma_w, chroma_h) {
12339 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
12340 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
12341 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
12342 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
12343 // through the square reader like every other square chroma unit.
12344 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
12345 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
12346 _ => unreachable!("chroma_tiled"),
12347 }
12348 };
12349 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
12350 // frame's square chroma units count it.
12351 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12352 hit!(CHROMA422_SQUARE_HITS);
12353 }
12354 if chroma_422_pair_wide {
12355 hit!(CHROMA422_PAIR_WIDE_HITS);
12356 }
12357 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
12358 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
12359 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
12360 // the pinned Release oracle), so its txb_skip rows always carry the
12361 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
12362 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
12363 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12364 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
12365 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
12366 // mode-indexed default, the same rule the unsplit arm below applies.
12367 let default_tx = if uw.max(uh) >= 32 {
12368 TxType::DctDct
12369 } else {
12370 default_intra_tx_type(m.uv_predict_mode as u8)
12371 };
12372 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
12373 for plane_idx in 1..=2 {
12374 for cu_row in 0..nh {
12375 for cu_col in 0..nw {
12376 let luma_span_x = uw << ss_x(fctx);
12377 let luma_span_y = uh << ss_y(fctx);
12378 let cu_mi = (
12379 mi_r + cu_row * (luma_span_y / MI),
12380 if chroma_422_pair_wide {
12381 mi_c & !1
12382 } else {
12383 mi_c
12384 } + cu_col * (luma_span_x / MI),
12385 );
12386 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
12387 // chroma context per chroma cell
12388 // ([`Neighbours::around_mi_422_chroma`], the block-8
12389 // rule) -- the plain rect walk samples one chroma cell
12390 // twice at ss_x 1. Every pre-existing shape keeps its own
12391 // walk.
12392 // lane-av1422mi24: the plain rect walk's double-count
12393 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
12394 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
12395 // read its above dc votes twice and its U dc_sign one
12396 // ctx row high (t422 frame 1). Route every ss (1,0)
12397 // unit through the every-second-above-cell sampling;
12398 // 4:2:0/4:4:4 keep the plain walk verbatim.
12399 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
12400 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
12401 } else {
12402 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
12403 };
12404 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
12405 let cfl = m.alpha.map(|(au, av)| {
12406 let alpha = if plane_idx == 1 { au } else { av };
12407 (
12408 alpha,
12409 if chroma_422_pair_wide {
12410 // The unit's co-located luma is the PAIR's
12411 // 8-px-wide band at the floored mi column.
12412 cfl_src_rect(
12413 (mi_c & !1) * MI + cu_col * luma_span_x,
12414 py + cu_row * luma_span_y,
12415 luma_span_x,
12416 luma_span_y,
12417 )
12418 } else {
12419 cfl_src_rect(
12420 px + cu_col * luma_span_x,
12421 py + cu_row * luma_span_y,
12422 luma_span_x,
12423 luma_span_y,
12424 )
12425 },
12426 )
12427 });
12428 // lane-av1-422kf: the palette colour map is consumed per
12429 // unit here like every other chroma arm (`av1_visit_palette`
12430 // feeds the whole plane block; window it to this unit).
12431 // Without this the square chroma rows decoded a uv-palette
12432 // strip's chroma as plain DC (class same-symbols-silent-
12433 // prediction: the rng stayed in sync, only the prediction
12434 // was dropped).
12435 if let Some((ub, vb)) = &m.palette_uv {
12436 let buf = if plane_idx == 1 { ub } else { vb };
12437 set_palette_pred(
12438 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
12439 fctx,
12440 );
12441 }
12442 // 32x32 does not fit read_coeffs_rect's scratch (768). The
12443 // square reader is the path every other 32x32 chroma unit uses.
12444 let levels = if uw == uh {
12445 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12446 read_plane(
12447 dec,
12448 cdfs,
12449 set,
12450 scan,
12451 plane_idx,
12452 cu_around[plane_idx],
12453 m.mode,
12454 m.uv_predict_mode,
12455 m.angle_delta_uv,
12456 reach,
12457 plane,
12458 cu_x,
12459 cu_y,
12460 uw,
12461 uw,
12462 base_q_idx,
12463 cfl,
12464 None,
12465 bigger.then_some(3),
12466 m.smooth_neighbor_uv,
12467 fctx,
12468 )?
12469 } else {
12470 let skip_ctx = usize::from(cu_around[plane_idx].0)
12471 + usize::from(cu_around[plane_idx].1)
12472 + usize::from(bigger) * 3;
12473 let mut coding = cdfs.txb(set, m.uv_predict_mode);
12474 let (levels, tx_type) = read_coeffs_rect(
12475 dec,
12476 &mut coding,
12477 scan,
12478 uw,
12479 uh,
12480 skip_ctx,
12481 dc_sign_ctx(cu_around[plane_idx].2),
12482 default_tx,
12483 plane_idx,
12484 )?;
12485 let residual = dequant_and_inverse_typed_wh(
12486 &levels,
12487 uw,
12488 uh,
12489 crate::decode::bit_depth(fctx),
12490 block_q_idx(fctx),
12491 plane_q_delta(plane_idx, fctx).0,
12492 plane_q_delta(plane_idx, fctx).1,
12493 tx_type,
12494 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
12495 );
12496 push_intra_rect(
12497 plane_idx,
12498 cu_x,
12499 cu_y,
12500 uw,
12501 uh,
12502 m.uv_predict_mode,
12503 m.angle_delta_uv,
12504 reach,
12505 &residual,
12506 cfl,
12507 None,
12508 m.smooth_neighbor_uv,
12509 fctx,
12510 );
12511 levels
12512 };
12513 neighbours.record_mi_chroma(
12514 cu_mi,
12515 luma_span_x,
12516 luma_span_y,
12517 plane_idx,
12518 &levels,
12519 );
12520 tiled_chroma_units.push((
12521 cu_mi,
12522 plane_idx,
12523 levels.clone(),
12524 luma_span_x,
12525 luma_span_y,
12526 ));
12527 last[plane_idx - 1] = levels;
12528 }
12529 }
12530 }
12531 (last[0].clone(), last[1].clone())
12532 } else {
12533 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
12534 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12535 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
12536 // so only the 16x8/8x16 pair takes the mode-indexed default.
12537 let default_tx = if chroma_w.max(chroma_h) >= 32 {
12538 TxType::DctDct
12539 } else {
12540 default_intra_tx_type(m.uv_predict_mode as u8)
12541 };
12542 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
12543 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
12544 // counts every chroma column's whole-unit dc sign twice (the t422
12545 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
12546 // row high). Luma keeps the per-mi gather; the two chroma planes
12547 // take [`Neighbours::around_mi_422_chroma`]'s every-second
12548 // above-cell sampling, like every other 4:2:2 chroma gather.
12549 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
12550 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12551 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
12552 around[1] = c[1];
12553 around[2] = c[2];
12554 }
12555 let mut grids: Vec<Grid> = Vec::with_capacity(2);
12556 for plane_idx in 1..=2 {
12557 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
12558 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
12559 let (levels, tx_type) = read_coeffs_rect(
12560 dec,
12561 &mut coding,
12562 chroma_scan,
12563 chroma_w,
12564 chroma_h,
12565 skip_ctx,
12566 dc_sign_ctx(around[plane_idx].2),
12567 default_tx,
12568 plane_idx,
12569 )?;
12570 // The same delta_q proof the unsplit rect64 path records
12571 // (lane-rectsplit r4: lifting the split-transform refusal moved
12572 // superblock strips onto this path, so only counting there would
12573 // leave the delta_q gate's counter silent for them).
12574 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
12575 hit!(RECT64_QIDX_DRIFT_HITS);
12576 }
12577 let residual = dequant_and_inverse_typed_wh(
12578 &levels,
12579 chroma_w,
12580 chroma_h,
12581 crate::decode::bit_depth(fctx),
12582 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
12583 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
12584 // reading `current_q_idx` here dropped the segment feature
12585 // that every other dequant site applies (class
12586 // `parsed-then-discarded`).
12587 block_q_idx(fctx),
12588 plane_q_delta(plane_idx, fctx).0,
12589 plane_q_delta(plane_idx, fctx).1,
12590 tx_type,
12591 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
12592 );
12593 let cfl = m
12594 .alpha
12595 .zip(ac)
12596 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
12597 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12598 if let Some((ub, vb)) = &m.palette_uv {
12599 let buf = if plane_idx == 1 { ub } else { vb };
12600 set_palette_pred(buf.clone(), fctx);
12601 }
12602 push_intra_rect(
12603 plane_idx,
12604 cpx,
12605 cpy,
12606 chroma_w,
12607 chroma_h,
12608 m.uv_predict_mode,
12609 m.angle_delta_uv,
12610 reach,
12611 &residual,
12612 cfl,
12613 None,
12614 m.smooth_neighbor_uv,
12615 fctx,
12616 );
12617 grids.push(levels);
12618 }
12619 let mut it = grids.into_iter();
12620 (it.next().unwrap(), it.next().unwrap())
12621 };
12622 neighbours.record_split_luma_rect_mi(
12623 at_mi,
12624 bw,
12625 bh,
12626 m.mode,
12627 m.uv_predict_mode,
12628 [&u_grid, &v_grid],
12629 );
12630 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
12631 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12632 }
12633 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
12634 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12635 }
12636 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
12637 neighbours.fill_lf_grid_rect(
12638 (mi_r, mi_c),
12639 bw / MI,
12640 bh / MI,
12641 tx_w as u8,
12642 tx_h as u8,
12643 0,
12644 fctx,
12645 );
12646 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12647 let (rng, _) = dec.debug_state();
12648 eprintln!(
12649 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
12650 tx={tx_w}x{tx_h} rng={rng}"
12651 );
12652 }
12653 Ok(())
12654}
12655
12656/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
12657/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
12658/// because it predicts squares only. Every pixel here goes through the rect
12659/// machinery the key-frame paths already prove: [`decode_rect_split`], which
12660/// at `depth == 0` is the unsplit strip as a single transform unit and
12661/// beyond it the per-unit walk of [`depth_to_tx_wh`].
12662///
12663/// What is genuinely different from [`decode_block_rect`] is the mode
12664/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
12665/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
12666/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
12667/// intra-in-inter arm's own reads at the rect footprint, including its
12668/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
12669/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
12670/// square and this arm) and a nonzero luma angle delta refused by name.
12671///
12672/// The strip's own neighbour records (luma per transform unit, chroma, skip
12673/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
12674/// inter-side bands and the mi map.
12675#[allow(clippy::too_many_arguments)]
12676/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
12677/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
12678/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
12679/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
12680/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
12681/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
12682/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
12683/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
12684/// table here rather than a shift of `bw.min(bh)`.
12685fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12686 Some(match (bw.min(bh), bw.max(bh)) {
12687 (8, 16) => (1usize, 1usize),
12688 (16, 32) => (2, 2),
12689 (32, 64) => (3, 3),
12690 (8, 32) => (1, 2),
12691 (16, 64) => (2, 3),
12692 _ => return None,
12693 })
12694}
12695
12696/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
12697/// block path"): the shapes that can reach that arm, enumerated against the
12698/// MEASURED domain of the inter block path
12699/// ([`INTER_BLOCK_SHAPES`], the census the gate
12700/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
12701/// fills from three real streams).
12702///
12703/// [`decode_intra_rect_in_inter`] is called from one site, under
12704/// `write_w != side || write_h != side`, and only after two earlier arms have
12705/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
12706/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
12707/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
12708/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
12709/// and each of those has a row, so the refusal names a shape no measured
12710/// stream can present.
12711#[test]
12712fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12713 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12714 // names that string exactly (placeholders included) and pins its guard
12715 // site. The enumeration below establishes the shape domain; on its own it
12716 // never said WHICH string the domain was about, so under a real function
12717 // boundary -- rather than a window that ran into the next test -- the row
12718 // read as unanchored.
12719 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)";
12720 assert!(
12721 include_str!("decode.rs").contains(REFUSAL),
12722 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12723 );
12724 let mut checked = 0;
12725 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12726 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
12727 continue;
12728 }
12729 assert!(
12730 intra_in_inter_size_row(w, h).is_some(),
12731 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
12732 the \"no size-group/tx-category row\" refusal"
12733 );
12734 checked += 1;
12735 }
12736 assert_eq!(
12737 checked, 10,
12738 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
12739 lookup, not the 10 this claim was measured over"
12740 );
12741}
12742
12743/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
12744/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
12745/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
12746/// matched before the square arm's `log2` shortcut).
12747///
12748/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
12749/// row here"; the enumeration below is what proves no conformant block can
12750/// reach it.
12751pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
12752 Some(match (write_w, write_h) {
12753 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
12754 // below maps 128 to row 4 (BLOCK_16X32).
12755 (64, 128) => 14,
12756 (128, 64) => 15,
12757 (128, 128) => 16,
12758 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
12759 (16, 32) => 4,
12760 (32, 16) => 5,
12761 (32, 64) => 6,
12762 (64, 32) => 7,
12763 (8, 32) => 8,
12764 (32, 8) => 9,
12765 (16, 64) => 10,
12766 (64, 16) => 11,
12767 // lane-inter4 r3: the 16x16-level rect inter leaves.
12768 (8, 16) => 12,
12769 (16, 8) => 13,
12770 _ => return None,
12771 })
12772}
12773
12774/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
12775/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
12776/// `block_size_wide`/`block_size_high`).
12777#[cfg(test)]
12778const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12779 (4, 4),
12780 (4, 8),
12781 (8, 4),
12782 (8, 8),
12783 (8, 16),
12784 (16, 8),
12785 (16, 16),
12786 (16, 32),
12787 (32, 16),
12788 (32, 32),
12789 (32, 64),
12790 (64, 32),
12791 (64, 64),
12792 (64, 128),
12793 (128, 64),
12794 (128, 128),
12795 (4, 16),
12796 (16, 4),
12797 (8, 32),
12798 (32, 8),
12799 (16, 64),
12800 (64, 16),
12801];
12802
12803/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
12804/// shape with no CDF row here" names a shape no conformant stream can present.
12805///
12806/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
12807/// whose `write_w.min(write_h) >= 8` clause is libaom's
12808/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
12809/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
12810/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
12811/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
12812/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
12813/// clause rejects before the lookup.
12814#[test]
12815fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12816 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12817 // names it and pins its guard site.
12818 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
12819 assert!(
12820 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
12821 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12822 );
12823 let mut rows = std::collections::BTreeSet::new();
12824 let mut excluded = 0;
12825 for (w, h) in BLOCK_SIZES_ALL_WH {
12826 if w.min(h) < 8 {
12827 excluded += 1;
12828 assert!(
12829 w == 4 || h == 4,
12830 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
12831 );
12832 continue;
12833 }
12834 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
12835 panic!(
12836 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
12837 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
12838 )
12839 });
12840 assert!(
12841 row < 17,
12842 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
12843 );
12844 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
12845 }
12846 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
12847 assert_eq!(
12848 rows.len(),
12849 17,
12850 "17 eligible footprints must fill all 17 rows of the motion_mode table"
12851 );
12852}
12853
12854/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
12855/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
12856/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
12857/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
12858/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
12859/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
12860/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
12861/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
12862#[test]
12863fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
12864 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
12865 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
12866 let ss10_invalid: &[(&str, bool)] = &[
12867 ("4x4", false),
12868 ("4x8", true),
12869 ("8x4", false),
12870 ("8x8", false),
12871 ("8x16", true),
12872 ("16x8", false),
12873 ("16x16", false),
12874 ("16x32", true),
12875 ("32x16", false),
12876 ("32x32", false),
12877 ("32x64", true),
12878 ("64x32", false),
12879 ("64x64", false),
12880 ("64x128", true),
12881 ("128x64", false),
12882 ("128x128", false),
12883 ("4x16", true),
12884 ("16x4", false),
12885 ("8x32", true),
12886 ("32x8", false),
12887 ("16x64", true),
12888 ("64x16", false),
12889 ];
12890 for (footprint, invalid10) in ss10_invalid {
12891 let (w, h) = footprint.split_once('x').unwrap();
12892 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
12893 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
12894 // valid because a (2, 4) plane area rounds UP to the 4x4 read
12895 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
12896 // [`decode_rect_split`] at all.
12897 if (bw, bh) == (4, 4) {
12898 continue;
12899 }
12900 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
12901 for (ss_x, ss_y) in [(false, false), (true, true)] {
12902 assert!(
12903 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
12904 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
12905 );
12906 }
12907 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
12908 // BLOCK_INVALID column, anchored at the floored mi column.
12909 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
12910 assert_eq!(
12911 pair.is_some(),
12912 *invalid10 && bw == 4,
12913 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
12914 );
12915 if let Some((block_w, block_h, x, ctx_col)) = pair {
12916 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
12917 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
12918 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
12919 // An even-column strip anchors at its own cell.
12920 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
12921 Some((_, _, x, c)) => (x, c),
12922 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
12923 };
12924 assert_eq!(
12925 (x_even, col_even),
12926 (12, 6),
12927 "even column keeps its own cell"
12928 );
12929 }
12930 }
12931 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
12932 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
12933 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
12934 for (bw, bh) in [
12935 (8usize, 16),
12936 (16, 32),
12937 (32, 64),
12938 (64, 128),
12939 (8, 32),
12940 (16, 64),
12941 ] {
12942 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
12943 }
12944}
12945
12946fn decode_intra_rect_in_inter(
12947 dec: &mut SymbolDecoder,
12948 cdfs: &mut Cdfs,
12949 neighbours: &mut Neighbours,
12950 at: (usize, usize),
12951 bw: usize,
12952 bh: usize,
12953 skip: bool,
12954 allow_screen_content_tools: bool,
12955 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
12956 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
12957 strip16: Option<(bool, bool)>,
12958 y: &mut PlaneBuf<'static>,
12959 u: &mut PlaneBuf<'static>,
12960 v: &mut PlaneBuf<'static>,
12961 base_q_idx: u8,
12962 fctx: &crate::decode::FrameCtx,
12963) -> Result<()> {
12964 // `at` is in MI units (the inter path's own unit since lane-inter4);
12965 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
12966 // below are still keyed by.
12967 let (mi_r, mi_c) = at;
12968 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
12969 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
12970 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
12971 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
12972 // finding -- the category is NOT the same for every strip size).
12973 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
12974 // it is refused by name rather than read from the wrong CDF row.
12975 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
12976 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
12977 // tx-depth category is 1 -- but nothing here has to know either, because
12978 // the strip decodes through the very body the KEY FRAME path proves for
12979 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
12980 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
12981 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
12982 // inter-frame difference is the mode-info read, which
12983 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
12984 // `y_mode[0]` plus the `skip` this caller already read.
12985 if let Some((horz, has_chroma)) = strip16 {
12986 // lane-t900 r22: the screen-content refusal here was STALE (class
12987 // stale-premise): [`decode_rect4_16_strip`] takes
12988 // `allow_screen_content_tools` and reads the whole palette syntax
12989 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
12990 // pair) -- the key frame proves that body. Lifted with the 10-bit
12991 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
12992 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
12993 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
12994 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
12995 let res = decode_rect4_16_strip(
12996 dec,
12997 cdfs,
12998 neighbours,
12999 (mi_r, mi_c),
13000 horz,
13001 has_chroma,
13002 // The inter strips of the same partition publish their own
13003 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
13004 // has nothing to add here.
13005 None,
13006 y,
13007 u,
13008 v,
13009 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13010 allow_screen_content_tools,
13011 base_q_idx,
13012 fctx.tx_select_inter.with(std::cell::Cell::get),
13013 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13014 fctx,
13015 );
13016 fctx.intra_in_inter_mode.with(|c| c.set(None));
13017 let (mode, uv, (tx_w, tx_h)) = res?;
13018 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
13019 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
13020 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
13021 // block of an inter frame, intra ones included, and
13022 // `txfm_partition_update` for the var-tx context. The key-frame body
13023 // writes neither (a key frame has no var-tx tree and its own readers
13024 // use the deblock grid), so the block AFTER this strip read a stale
13025 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
13026 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
13027 // 16x16 row.
13028 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13029 for i in 0..bw / MI {
13030 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13031 *cell = tx_w as u8;
13032 }
13033 }
13034 for i in 0..bh / MI {
13035 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13036 *cell = tx_h as u8;
13037 }
13038 }
13039 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
13040 // coarse 16-px cell holds one entry for the whole 16x16 and the last
13041 // block to write it wins).
13042 neighbours.above_mode[c] = mode;
13043 neighbours.left_mode[r] = mode;
13044 if let Some(uvm) = uv {
13045 neighbours.above_uv_mode[c] = uvm;
13046 neighbours.left_uv_mode[r] = uvm;
13047 }
13048 neighbours.above_side[c] = bw;
13049 neighbours.left_side[r] = bh;
13050 if crate::envflags::env_flag!("EC_INTRA16X4") {
13051 eprintln!(
13052 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
13053 mi_c * MI,
13054 mi_r * MI
13055 );
13056 }
13057 hit_do! {
13058 INTRA16X4_IN_INTER_HITS.with(|h| {
13059 let mut v = h.get();
13060 v[usize::from(!horz)] += 1;
13061 v[2] += usize::from(has_chroma);
13062 h.set(v);
13063 });
13064 }
13065 return Ok(());
13066 }
13067 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
13068 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
13069 // puts BLOCK_128X64/64X128/128X128 in group 3 and
13070 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
13071 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
13072 // block decodes through the very body the KEY FRAME path proves for this
13073 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
13074 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
13075 // `Reach` rule and the frame-edge write clip). The only inter-frame
13076 // differences live inside that body: the mode-info read
13077 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
13078 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
13079 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
13080 // palette (>64) do not exist at this size and are refused by name there.
13081 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
13082 // `intra128_in_inter_witness2.obu` (gate
13083 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
13084 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
13085 // all 15 frames, so the hits are counted out of exact frames (class
13086 // `counter-from-refused-stream`). What r16/r17 could not find, and what
13087 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
13088 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
13089 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
13090 // where the frame EDGE forces it: a partial last superblock row has
13091 // `has_rows128 == false`, so the 128x64 top half is implied, and a
13092 // partial last column implies the 64x128 left half. Put content no
13093 // reference holds (a fresh smooth ramp) in exactly those two bands of an
13094 // inter frame and the encoder codes those forced halves INTRA.
13095 if bw.max(bh) == 128 {
13096 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
13097 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
13098 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
13099 // palette_syntax`), so a 128-root half consumes no palette syntax and
13100 // a screen-content frame's half is syntactically identical to the
13101 // non-screen one this arm already decodes byte-exact.
13102 if coeff_trace_on() {
13103 // lane-t900 r16: which decode-order frame this arm fires in --
13104 // interleaved with the `EC_COEFF_FRAME` markers, this is what
13105 // proves the hit is counted out of a frame that compares exact
13106 // (class `counter-from-refused-stream`).
13107 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
13108 }
13109 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
13110 let res = decode_block_128rect(
13111 dec,
13112 cdfs,
13113 neighbours,
13114 (r, c),
13115 bw,
13116 bh,
13117 y,
13118 u,
13119 v,
13120 base_q_idx,
13121 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13122 allow_screen_content_tools,
13123 fctx.tx_select_inter.with(std::cell::Cell::get),
13124 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13125 fctx,
13126 );
13127 fctx.intra_in_inter_mode.with(|c| c.set(None));
13128 return res;
13129 }
13130 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
13131 if crate::envflags::env_flag!("EC_OBMCREC") {
13132 eprintln!(
13133 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
13134 );
13135 }
13136 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
13137 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
13138 // can arrive here are enumerated against the measured block-shape
13139 // census ([`INTER_BLOCK_SHAPES`]) by
13140 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
13141 // -- every one of them has a row, so this arm names a shape no stream
13142 // has been able to present.
13143 return Err(unsupported(format!(
13144 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13145 )));
13146 };
13147 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13148 // screen-content frame ("palette syntax is consumed for square blocks
13149 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13150 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13151 // it, while the 2:1 reader inlined further down now codes the same syntax
13152 // itself. A real `--tune-content=screen` inter stream reached this refusal
13153 // on 8x16 / 16x8 strips (gate
13154 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13155 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13156 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13157 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13158 // luma/chroma transform tables, the per-unit split walk and the strip's
13159 // own neighbour records). The ONLY difference on an inter frame is the
13160 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13161 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13162 // this caller already read. `tx_cat` above is the same category those
13163 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13164 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13165 if bw.max(bh) == 4 * bw.min(bh) {
13166 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13167 fctx.intra_in_inter_mode
13168 .with(|c| c.set(Some((size_group, skip))));
13169 let res = if bw.max(bh) == 64 {
13170 decode_block_rect64(
13171 dec,
13172 cdfs,
13173 neighbours,
13174 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13175 bw,
13176 bh,
13177 y,
13178 u,
13179 v,
13180 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13181 allow_screen_content_tools,
13182 base_q_idx,
13183 fctx.tx_select_inter.with(std::cell::Cell::get),
13184 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13185 fctx,
13186 )
13187 } else {
13188 decode_block_rect4(
13189 dec,
13190 cdfs,
13191 neighbours,
13192 (mi_r, mi_c),
13193 bw,
13194 bh,
13195 None,
13196 y,
13197 u,
13198 v,
13199 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13200 allow_screen_content_tools,
13201 base_q_idx,
13202 fctx.tx_select_inter.with(std::cell::Cell::get),
13203 fctx,
13204 )
13205 .map(|_| ())
13206 };
13207 fctx.intra_in_inter_mode.with(|c| c.set(None));
13208 res?;
13209 let shape = match (bw, bh) {
13210 (64, 16) => 0,
13211 (16, 64) => 1,
13212 (32, 8) => 2,
13213 _ => 3,
13214 };
13215 hit_do! {
13216 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13217 let mut v = h.get();
13218 v[shape] += 1;
13219 h.set(v);
13220 });
13221 }
13222 return Ok(());
13223 }
13224 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13225 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13226 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13227 // own, so a cross-decoder bisection could only see the block's first
13228 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13229 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13230 if step_trace {
13231 eprintln!(
13232 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13233 dec.debug_state().0
13234 );
13235 }
13236 if mode >= 13 {
13237 return Err(unsupported(
13238 "an intra mode this decoder does not code (round 2)",
13239 ));
13240 }
13241 // lane-angleinter (merged on main for the square intra-in-inter arm):
13242 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
13243 // directional predictor; this arm refused a nonzero one before the merge.
13244 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13245 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
13246 } else {
13247 0
13248 };
13249 if angle_delta_y != 0 {
13250 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
13251 }
13252 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
13253 // superblock-level strip reads the no-CFL alphabet -- the same split
13254 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
13255 //
13256 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
13257 // (libaom `decodemv.c:933`).
13258 let has_chroma = !mono(fctx);
13259 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
13260 let uv_mode = if !has_chroma {
13261 DC_PRED
13262 } else if cfl_allowed {
13263 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13264 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13265 } else {
13266 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13267 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13268 };
13269 if step_trace {
13270 eprintln!(
13271 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
13272 u8::from(cfl_allowed),
13273 dec.debug_state().0
13274 );
13275 }
13276 if (9..=12).contains(&uv_mode) {
13277 hit!(SMOOTH_UV_HITS);
13278 }
13279 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
13280 Some(read_cfl_alphas(dec, cdfs))
13281 } else {
13282 None
13283 };
13284 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13285 DC_PRED
13286 } else {
13287 uv_mode
13288 };
13289 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13290 hit!(DIRECTIONAL_UV_HITS);
13291 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13292 } else {
13293 0
13294 };
13295 if angle_delta_uv != 0 {
13296 hit!(UV_ANGLE_DELTA_HITS);
13297 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
13298 }
13299 // `read_palette_mode_info` (spec 5.11.13), in the position
13300 // `read_intra_block_mode_info` writes it: after the chroma mode and
13301 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
13302 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
13303 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
13304 // skipping the syntax here desynced the tile at the strip's own symbol.
13305 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
13306 // context and colour cache at its own mi position, and the two
13307 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
13308 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
13309 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
13310 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
13311 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13312 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13313 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
13314 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
13315 let use_palette_y =
13316 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
13317 if use_palette_y {
13318 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13319 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
13320 }
13321 // A 2:1 strip of at least 8x8 is always a chroma reference, so
13322 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
13323 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13324 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
13325 let use_palette_uv = has_chroma
13326 && uv_mode == DC_PRED
13327 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
13328 if crate::envflags::env_flag!("EC_PALSYN") {
13329 eprintln!(
13330 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
13331 use_palette_y as i32,
13332 use_palette_uv as i32,
13333 dec.debug_state().0
13334 );
13335 }
13336 if use_palette_uv {
13337 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13338 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
13339 palette_uv_pending = Some((n, u_colors, v_colors));
13340 }
13341 }
13342 // lane-fiinter (merged on main for the square intra-in-inter arm):
13343 // `read_filter_intra_mode_info` is the tail of
13344 // `read_intra_block_mode_info`, after the palette syntax (refused whole
13345 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
13346 // 2:1 strips with both sides <= 32 -- their own CDF rows
13347 // ([`filter_intra_size_class_rect`]).
13348 let mut filter_intra = None;
13349 if mode == DC_PRED
13350 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
13351 // `av1_filter_intra_allowed` excludes a palette-Y block.
13352 && palette_y_pending.is_none()
13353 && let Some(class) = filter_intra_size_class_rect(bw, bh)
13354 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
13355 {
13356 hit!(FILTER_INTRA_HITS);
13357 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
13358 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
13359 }
13360 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
13361 let palette_y = palette_y_pending.map(|(n, colors)| {
13362 let map = decode_color_index_map_wh(
13363 dec,
13364 cdfs,
13365 n,
13366 bw,
13367 bh,
13368 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13369 false,
13370 );
13371 hit!(PALETTE_HITS);
13372 hit!(PALETTE_RECT_HITS);
13373 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
13374 PaletteY {
13375 size: n,
13376 colors,
13377 map,
13378 }
13379 });
13380 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13381 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
13382 let on = palette_onscreen_uv(
13383 (bw, bh),
13384 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13385 (cw, ch),
13386 (ss_x(fctx), ss_y(fctx)),
13387 );
13388 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
13389 hit!(PALETTE_UV_HITS);
13390 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
13391 PaletteUv {
13392 size: n,
13393 u_colors,
13394 v_colors,
13395 map,
13396 }
13397 });
13398 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
13399 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
13400 // chroma ones -- [`decode_block_rect`]'s own pair.
13401 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
13402 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
13403 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
13404 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
13405 // one exactly as [`decode_leaf8`] already does (class
13406 // context-read-from-one-cell).
13407 let coarse_pair = neighbours.modes_above_left(r, c);
13408 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
13409 if (nb_above_mode, nb_left_mode) != coarse_pair {
13410 hit!(EDGE_FILTER_MI_FIX_HITS);
13411 }
13412 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13413 if smooth_neighbor {
13414 hit!(SMOOTH_LUMA_HITS);
13415 }
13416 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13417 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13418 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
13419 // an inter frame codes no depth symbol either (`xd->lossless` is per
13420 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
13421 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
13422 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
13423 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
13424 let d = match tx_cat {
13425 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
13426 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
13427 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
13428 };
13429 if step_trace {
13430 eprintln!(
13431 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
13432 dec.debug_state().0
13433 );
13434 }
13435 d
13436 } else {
13437 0
13438 };
13439 if depth != 0 || lossless(fctx) {
13440 hit!(TX_DEPTH_HITS);
13441 // lane-intrasplit r1: a split intra strip in an inter frame walks the
13442 // key frame's own per-TU path ([`decode_rect_split`] below); what was
13443 // wrong when this refusal was written was the depth SYMBOL, not the walk.
13444 hit_do! {
13445 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
13446 let mut v = h.get();
13447 v[depth.min(2)] += 1;
13448 h.set(v);
13449 });
13450 }
13451 }
13452 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
13453 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
13454 // the two are indistinguishable when the diagnostic fires on splits alone.
13455 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
13456 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
13457 }
13458 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13459 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
13460 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
13461 // of an inter frame, intra ones included -- with the skip term 0 it
13462 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
13463 // and `left_txfm_context` to `tx_size_high` over its height. This strip
13464 // wrote neither, so the next block's var-tx `txfm_partition` context read
13465 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
13466 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
13467 // mi(16,0) and desyncing the tile at that symbol.
13468 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13469 let modes = RectStripModes {
13470 skip,
13471 mode,
13472 angle_delta_y,
13473 uv_predict_mode,
13474 angle_delta_uv,
13475 alpha,
13476 filter_intra,
13477 smooth_neighbor,
13478 smooth_neighbor_uv,
13479 palette_y: palette_y
13480 .as_ref()
13481 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
13482 palette_uv: palette_uv.as_ref().map(|p| {
13483 (
13484 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13485 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13486 )
13487 }),
13488 };
13489 decode_rect_split(
13490 dec,
13491 cdfs,
13492 neighbours,
13493 (mi_r, mi_c),
13494 bw,
13495 bh,
13496 tx_w,
13497 tx_h,
13498 &modes,
13499 y,
13500 u,
13501 v,
13502 base_q_idx,
13503 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13504 fctx,
13505 )?;
13506 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
13507 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
13508 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
13509 // left column over its height. This arm wrote neither before lane-intrasplit
13510 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
13511 // context across the strip's footprint.
13512 for i in 0..bw / MI {
13513 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13514 *cell = tx_w as u8;
13515 }
13516 }
13517 for i in 0..bh / MI {
13518 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13519 *cell = tx_h as u8;
13520 }
13521 }
13522 // The strip's own palette state into the mi-granular neighbour bands, so
13523 // the next block's colour cache and `palette_y_mode` context are libaom's.
13524 record_strip_palette(
13525 neighbours,
13526 (mi_r, mi_c),
13527 bw,
13528 bh,
13529 palette_y.as_ref().map_or(0, |p| p.size),
13530 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
13531 palette_uv.as_ref().map_or(0, |p| p.size),
13532 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
13533 );
13534 let class = match bw.max(bh) {
13535 64 => 0,
13536 32 => 1,
13537 _ => 2,
13538 };
13539 hit_do! {
13540 INTRA_RECT_IN_INTER_HITS.with(|h| {
13541 let mut v = h.get();
13542 v[class] += 1;
13543 h.set(v);
13544 });
13545 }
13546 Ok(())
13547}
13548
13549/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
13550/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
13551///
13552/// libaom treats an intrabc block as INTER for everything except the mode-info
13553/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
13554/// (`blockd.h:373`), so
13555///
13556/// * `parse_decode_block` reads the transform size through the INTER var-tx
13557/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
13558/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
13559/// whose leaves publish their own resolved size back;
13560/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
13561/// frame's own pre-loop-filter reconstruction, at the coded block vector
13562/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
13563/// * `decode_token_recon_block`'s inter branch then reads one residual per
13564/// transform unit, through the INTER coefficient sets
13565/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
13566/// inheriting the colocated luma unit's coded `tx_type`.
13567///
13568/// Text order is libaom's: transform tree, prediction, luma residual, chroma
13569/// residual, bookkeeping. A skipped block codes no residual at all -- the
13570/// prediction is the reconstruction.
13571#[allow(clippy::too_many_arguments)]
13572fn decode_intrabc_rect(
13573 dec: &mut SymbolDecoder,
13574 cdfs: &mut Cdfs,
13575 neighbours: &mut Neighbours,
13576 (mi_r, mi_c): (usize, usize),
13577 (bw, bh): (usize, usize),
13578 skip: bool,
13579 (dv_row, dv_col): (i32, i32),
13580 y: &mut PlaneBuf<'static>,
13581 u: &mut PlaneBuf<'static>,
13582 v: &mut PlaneBuf<'static>,
13583 base_q_idx: u8,
13584 fctx: &crate::decode::FrameCtx,
13585) -> Result<()> {
13586 hit!(INTRABC_RECT_HITS);
13587 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
13588 let idx = usize::from(bh > bw);
13589 if skip {
13590 INTRABC_RECT_SKIPPED_HITS.with(|c| {
13591 let mut seen = c.get();
13592 seen[idx] += 1;
13593 c.set(seen);
13594 });
13595 } else {
13596 INTRABC_RECT_CODED_HITS.with(|c| {
13597 let mut seen = c.get();
13598 seen[idx] += 1;
13599 c.set(seen);
13600 });
13601 }
13602 let (px, py) = (mi_c * MI, mi_r * MI);
13603 // lane-whtshape: a LOSSLESS block's chroma plane block is
13604 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
13605 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
13606 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
13607 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
13608 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
13609 // walk below coded 2 units per plane where libaom codes 8.
13610 //
13611 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
13612 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
13613 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
13614 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
13615 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
13616 // the block at mi (92, 104) read all_zero=0 here against the oracle's
13617 // all_zero=1 -- the bit position forks there. Identical arithmetic at
13618 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
13619 // witness is the identity arm of this lane's gate.
13620 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13621 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
13622 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
13623 // shape this helper is called at, so the uv plane block is ONE unit --
13624 // the same call `decode_token_recon_block`'s own chroma loop makes.
13625 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13626 // lane-av1-intrabc r2: the square stride the proven INTER path uses
13627 // (`side`). The residual grids, the prediction windows AND
13628 // `TxParams::stride` are all laid out at it -- the block's own width
13629 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
13630 // exceeds the stride).
13631 let side = bw.max(bh);
13632 let cside = cw.max(ch);
13633 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
13634 // or bottom frame edge reads no transform-tree symbol for the units
13635 // outside it.
13636 let mi_cols = 2 * y.true_width.div_ceil(8);
13637 let mi_rows = 2 * y.true_height.div_ceil(8);
13638 let leaves = read_block_tx_size_rect(
13639 dec,
13640 cdfs,
13641 neighbours,
13642 (mi_r, mi_c),
13643 (bw, bh),
13644 (mi_cols, mi_rows),
13645 skip,
13646 fctx,
13647 )?;
13648 if leaves.is_some() {
13649 hit!(INTRABC_RECT_VARTX_HITS);
13650 }
13651 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
13652 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
13653 }
13654 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
13655 if crate::envflags::env_flag!("EC_IBCBLOCK") {
13656 eprintln!(
13657 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
13658 cw={cw} ch={ch} cside={cside} skip={skip}"
13659 );
13660 }
13661 // The whole-block prediction: `predict_inter_block` runs once, before any
13662 // coefficient is read. `flush_recon` first -- the source is this frame's
13663 // own reconstruction, including the writes this superblock has queued.
13664 flush_recon(fctx, y, u, v);
13665 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
13666 // reads it at the square stride, so re-lay it -- the same step the inter
13667 // path takes for its own square prediction buffer.
13668 let mut pred_y_dense = vec![0u16; bw * bh];
13669 mc::predict_with_filter(
13670 &y.data,
13671 y.width,
13672 y.true_width,
13673 y.true_height,
13674 mv_to_q4(px, dv_col, 0),
13675 mv_to_q4(py, dv_row, 0),
13676 bw,
13677 bh,
13678 mc::InterpFilterKind::Bilinear,
13679 &mut pred_y_dense,
13680 fctx,
13681 );
13682 let mut pred_y = vec![0u16; side * side];
13683 for row in 0..bh {
13684 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13685 }
13686 let mut pred_u_dense = vec![0u16; cw * ch];
13687 mc::predict_with_filter(
13688 &u.data,
13689 u.width,
13690 u.true_width,
13691 u.true_height,
13692 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13693 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13694 cw,
13695 ch,
13696 mc::InterpFilterKind::Bilinear,
13697 &mut pred_u_dense,
13698 fctx,
13699 );
13700 let mut pred_u = vec![0u16; cside * cside];
13701 for row in 0..ch {
13702 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13703 }
13704 let mut pred_v_dense = vec![0u16; cw * ch];
13705 mc::predict_with_filter(
13706 &v.data,
13707 v.width,
13708 v.true_width,
13709 v.true_height,
13710 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13711 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13712 cw,
13713 ch,
13714 mc::InterpFilterKind::Bilinear,
13715 &mut pred_v_dense,
13716 fctx,
13717 );
13718 let mut pred_v = vec![0u16; cside * cside];
13719 for row in 0..ch {
13720 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13721 }
13722 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13723 let luma_tx_type: TxType;
13724 let (luma_grid, u_grid, v_grid);
13725 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
13726 // kept so their per-4x4 slices can be re-stamped over the whole-block
13727 // record in the tail. `None` on every other arm.
13728 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
13729 if skip {
13730 // No residual syntax at all: the prediction IS the block.
13731 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
13732 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
13733 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
13734 push_mc_rect(
13735 0,
13736 px,
13737 py,
13738 side,
13739 bw,
13740 bh,
13741 Pred::Inline(&pred_y, side),
13742 &ZERO_RESIDUAL[..side * side],
13743 fctx,
13744 );
13745 push_mc_rect(
13746 1,
13747 cpx,
13748 cpy,
13749 cside,
13750 cw,
13751 ch,
13752 Pred::Inline(&pred_u, cside),
13753 &ZERO_RESIDUAL[..cside * cside],
13754 fctx,
13755 );
13756 push_mc_rect(
13757 2,
13758 cpx,
13759 cpy,
13760 cside,
13761 cw,
13762 ch,
13763 Pred::Inline(&pred_v, cside),
13764 &ZERO_RESIDUAL[..cside * cside],
13765 fctx,
13766 );
13767 if let Some(ls) = leaves.as_ref() {
13768 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
13769 // skip arm performs -- libaom `av1_reset_entropy_context`
13770 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
13771 // SKIPPED block zeroes its whole entropy-band footprint. This
13772 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
13773 // so a skipped lossless strip whose `leaves` resolved (every
13774 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13775 // returns the 4x4 grid before it looks at `skip`) left the
13776 // PREVIOUS occupant's luma bands standing and the NEXT block's
13777 // partition parse diverged from libaom's: the 320x242 lossless
13778 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
13779 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
13780 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13781 for &(row, col, tw, th) in ls {
13782 neighbours.record_mi_luma_rect(
13783 (mi_r + row, mi_c + col),
13784 tw,
13785 th,
13786 &ZERO_RESIDUAL[..tw * th],
13787 );
13788 }
13789 }
13790 luma_tx_type = TxType::DctDct;
13791 luma_grid = Grid::Zero(side * side);
13792 u_grid = Grid::Zero(cside * cside);
13793 v_grid = Grid::Zero(cside * cside);
13794 } else {
13795 match leaves.as_ref() {
13796 None => {
13797 // One whole-block rectangular transform unit.
13798 // lane-av1422mi24: at ss (1,0) the chroma above span is
13799 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
13800 // the per-mi gather counts every chroma column's whole-unit
13801 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
13802 // strip's U dc_sign read ctx 1 where the oracle's cell sum
13803 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
13804 // chroma planes take
13805 // [`Neighbours::around_mi_422_chroma`]'s every-second
13806 // above-cell sampling, like every other 4:2:2 chroma gather.
13807 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13808 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13809 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13810 around[1] = c[1];
13811 around[2] = c[2];
13812 }
13813 let (grid, tx_type) = read_inter_plane_rect(
13814 dec,
13815 cdfs,
13816 rect_inter_luma_set(bw, bh, fctx)?,
13817 (bw, bh),
13818 side,
13819 0,
13820 around[0],
13821 0,
13822 y,
13823 px,
13824 py,
13825 Pred::Inline(&pred_y, side),
13826 None,
13827 None,
13828 fctx,
13829 )?;
13830 luma_tx_type = tx_type;
13831 luma_grid = embed_grid_stride(&grid, bw, bh, side);
13832 let (ug, _) = read_inter_plane_rect(
13833 dec,
13834 cdfs,
13835 rect_inter_chroma_set(cw, ch)?,
13836 (cw, ch),
13837 cside,
13838 1,
13839 around[1],
13840 0,
13841 u,
13842 cpx,
13843 cpy,
13844 Pred::Inline(&pred_u, cside),
13845 Some(luma_tx_type),
13846 None,
13847 fctx,
13848 )?;
13849 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13850 let (vg, _) = read_inter_plane_rect(
13851 dec,
13852 cdfs,
13853 rect_inter_chroma_set(cw, ch)?,
13854 (cw, ch),
13855 cside,
13856 2,
13857 around[2],
13858 0,
13859 v,
13860 cpx,
13861 cpy,
13862 Pred::Inline(&pred_v, cside),
13863 Some(luma_tx_type),
13864 None,
13865 fctx,
13866 )?;
13867 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13868 }
13869 Some(leaves) => {
13870 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
13871 // the split override to LUMA only, per leaf -- the step the
13872 // proven inter var-tx path applies right after its own residual
13873 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
13874 // leaf's own transform edges are never filtered.
13875 for &(row, col, tw, th) in leaves.iter() {
13876 neighbours.fill_lf_grid_leaf_luma(
13877 (mi_r + row, mi_c + col),
13878 tw / MI,
13879 th / MI,
13880 tw as u8,
13881 th as u8,
13882 );
13883 }
13884 // One residual per transform unit, in the order the tree coded
13885 // them; each unit reads its own neighbour-magnitude context off
13886 // the units already decoded before it, and every unit adds onto
13887 // its own window of the block's single prediction.
13888 let mut first_tx_type = TxType::DctDct;
13889 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
13890 let tu_mi = (mi_r + row, mi_c + col);
13891 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13892 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13893 let (tu_grid, tu_tx_type) = if tw == th {
13894 let scan = default_scan(tw.min(32));
13895 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
13896 read_inter_plane(
13897 dec,
13898 cdfs,
13899 inter_txbset_for(tw, reduced),
13900 scan,
13901 0,
13902 neighbours.around_mi(tu_mi, tw)[0],
13903 0,
13904 y,
13905 tu_px,
13906 tu_py,
13907 tw,
13908 base_q_idx,
13909 tu_pred,
13910 None,
13911 Some(tu_skip_ctx),
13912 fctx,
13913 )?
13914 } else {
13915 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
13916 read_inter_plane_rect(
13917 dec,
13918 cdfs,
13919 rect_inter_luma_set(tw, th, fctx)?,
13920 (tw, th),
13921 side,
13922 0,
13923 neighbours.around_mi_rect(tu_mi, tw, th)[0],
13924 0,
13925 y,
13926 tu_px,
13927 tu_py,
13928 tu_pred,
13929 None,
13930 Some(tu_skip_ctx),
13931 fctx,
13932 )?
13933 };
13934 if idx == 0 {
13935 first_tx_type = tu_tx_type;
13936 }
13937 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
13938 }
13939 // `av1_get_tx_type`'s chroma lookup lands on the colocated
13940 // LUMA unit, which for a split block is the top-left one.
13941 luma_tx_type = first_tx_type;
13942 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
13943 // `None` arm above -- the per-mi rect gather double-counts
13944 // each chroma column's whole-unit dc sign at ss (1,0).
13945 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13946 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13947 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13948 around[1] = c[1];
13949 around[2] = c[2];
13950 }
13951 if lossless(fctx) {
13952 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
13953 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
13954 // lossless block before it looks at a tree, `read_tx_mode`
13955 // already forced `ONLY_4X4` for the frame, and
13956 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
13957 // -- so this block's chroma plane block is a
13958 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
13959 // (`decode_token_recon_block`: every U unit, then every V
13960 // unit), not the single rect unit the two
13961 // `read_inter_plane_rect` calls below read. That single
13962 // 8x4 unit is what reached the lossless WHT with the wrong
13963 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
13964 // replaced). Same helper, same walk, as the inter 8x8 and
13965 // 128 paths.
13966 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
13967 let mut uo = vec![0i32; cside * cside];
13968 let mut vo = vec![0i32; cside * cside];
13969 read_inter_chroma_lossless(
13970 dec,
13971 cdfs,
13972 neighbours,
13973 u,
13974 v,
13975 Pred::Inline(&pred_u, cside),
13976 Pred::Inline(&pred_v, cside),
13977 (mi_r, mi_c),
13978 (cpx, cpy),
13979 (0, 0),
13980 (cw, ch),
13981 (cw, ch),
13982 cside,
13983 0,
13984 base_q_idx,
13985 &mut uo,
13986 &mut vo,
13987 fctx,
13988 )?;
13989 // The per-unit walk stamped every unit's own coefficient
13990 // context, but the whole-block `record_split_luma_rect_mi`
13991 // in the tail rewrites every chroma cell with ONE composed
13992 // state, which drops the per-unit DC signs and levels (class
13993 // `override-slot-on-one-arm` -- the same one
13994 // `decode_rect_split`'s `ll_chroma_units` replay exists
13995 // for). The grids are kept here and replayed AFTER that
13996 // record, from the same 4x4 slices, so the same states.
13997 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
13998 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
13999 ll_chroma = Some((uo, vo));
14000 luma_grid = Grid::Zero(side * side);
14001 } else {
14002 let (ug, _) = read_inter_plane_rect(
14003 dec,
14004 cdfs,
14005 rect_inter_chroma_set(cw, ch)?,
14006 (cw, ch),
14007 cside,
14008 1,
14009 around[1],
14010 0,
14011 u,
14012 cpx,
14013 cpy,
14014 Pred::Inline(&pred_u, cside),
14015 Some(luma_tx_type),
14016 None,
14017 fctx,
14018 )?;
14019 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14020 let (vg, _) = read_inter_plane_rect(
14021 dec,
14022 cdfs,
14023 rect_inter_chroma_set(cw, ch)?,
14024 (cw, ch),
14025 cside,
14026 2,
14027 around[2],
14028 0,
14029 v,
14030 cpx,
14031 cpy,
14032 Pred::Inline(&pred_v, cside),
14033 Some(luma_tx_type),
14034 None,
14035 fctx,
14036 )?;
14037 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14038 luma_grid = Grid::Zero(side * side);
14039 }
14040 }
14041 }
14042 }
14043 let _ = luma_tx_type;
14044 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
14045 // next block reads a neighbour mode, its own block size in both `TXFM`
14046 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
14047 // state (a stale entry would feed the next block's colour cache), and its
14048 // DV into the intrabc mi grid the next block's DV predictor reads.
14049 if leaves.is_some() {
14050 neighbours.record_split_luma_rect_mi(
14051 (mi_r, mi_c),
14052 bw,
14053 bh,
14054 DC_PRED,
14055 DC_PRED,
14056 [&u_grid, &v_grid],
14057 );
14058 } else {
14059 neighbours.record_rect_mi(
14060 (mi_r, mi_c),
14061 bw,
14062 bh,
14063 DC_PRED,
14064 DC_PRED,
14065 &[&luma_grid, &u_grid, &v_grid],
14066 );
14067 }
14068 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
14069 // the whole-block record above, so the NEXT block reads the per-unit DC
14070 // signs and levels libaom's plane-major walk left behind instead of one
14071 // composed state for the whole plane block.
14072 if let Some((uo, vo)) = ll_chroma {
14073 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
14074 for ur in 0..ch / 4 {
14075 for uc in 0..cw / 4 {
14076 let mut unit = Vec::with_capacity(16);
14077 for r in 0..4 {
14078 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
14079 }
14080 neighbours.record_mi_chroma(
14081 // lane-av1lm444loss-corr: the MI STEP between chroma
14082 // units is that same footprint expressed in luma mi
14083 // cells, `(4 << ss) / MI` -- which is exactly what
14084 // `decode_inter_block`'s reference `mu_chroma_units`
14085 // construction writes (decode.rs:43688,
14086 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
14087 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
14088 // this replaces is 4:2:0-only arithmetic that happens
14089 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
14090 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
14091 // SAME value, so 4:2:0 is unchanged by construction.
14092 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
14093 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
14094 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
14095 // The step therefore lands every replayed unit at 4x
14096 // its own mi row/column on a 4:4:4 lossless frame, and
14097 // the whole block's per-unit states are stamped over
14098 // cells that belong to other blocks (or to nothing).
14099 (
14100 mi_r + ur * ((4 << ss_y(fctx)) / MI),
14101 mi_c + uc * ((4 << ss_x(fctx)) / MI),
14102 ),
14103 4 << ss_x(fctx),
14104 4 << ss_y(fctx),
14105 plane_idx,
14106 &Grid::Own(unit),
14107 );
14108 }
14109 }
14110 }
14111 }
14112 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14113 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14114 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14115 neighbours.fill_lf_grid_rect(
14116 (mi_r, mi_c),
14117 bw / MI,
14118 bh / MI,
14119 bw.min(64) as u8,
14120 bh.min(64) as u8,
14121 0,
14122 fctx,
14123 );
14124 record_intrabc_mi_rect(
14125 mi_r,
14126 mi_c,
14127 bw / MI,
14128 bh / MI,
14129 Some((dv_row, dv_col)),
14130 neighbours,
14131 fctx,
14132 );
14133 Ok(())
14134}
14135
14136/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
14137/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
14138/// `decode_block_128rect` refused by name before this port. libaom decodes
14139/// such a block through the INTER machinery (an intrabc block
14140/// `is_inter_block`): `predict_inter_block` copies the whole block from this
14141/// frame's own reconstruction at the integer block vector once, then
14142/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
14143/// per chunk every plane, luma units at the block's own resolved transform
14144/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
14145/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
14146/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
14147/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
14148/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14149/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14150#[allow(clippy::too_many_arguments)]
14151fn decode_intrabc_128rect(
14152 dec: &mut SymbolDecoder,
14153 cdfs: &mut Cdfs,
14154 neighbours: &mut Neighbours,
14155 (mi_r, mi_c): (usize, usize),
14156 (bw, bh): (usize, usize),
14157 skip: bool,
14158 (dv_row, dv_col): (i32, i32),
14159 y: &mut PlaneBuf<'static>,
14160 u: &mut PlaneBuf<'static>,
14161 v: &mut PlaneBuf<'static>,
14162 base_q_idx: u8,
14163 fctx: &crate::decode::FrameCtx,
14164) -> Result<()> {
14165 hit!(INTRABC_128RECT_HITS);
14166 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14167 let (rng, _) = dec.debug_state();
14168 eprintln!(
14169 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14170 );
14171 }
14172 let (px, py) = (mi_c * MI, mi_r * MI);
14173 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14174 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14175 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14176 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14177 // `/2` origin and extent made the prediction window half as tall as
14178 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14179 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14180 // `bw / 2, bh / 2` line-for-line.
14181 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14182 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14183 // The square strides the proven INTER path lays its residual grids,
14184 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14185 // note): 128/64 here.
14186 let side = bw.max(bh);
14187 let cside = cw.max(ch);
14188 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14189 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14190 let mi_cols = 2 * y.true_width.div_ceil(8);
14191 let mi_rows = 2 * y.true_height.div_ceil(8);
14192 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14193 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14194 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14195 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14196 // arms (lane-sb128c r7).
14197 let leaves = read_block_tx_size_rect(
14198 dec,
14199 cdfs,
14200 neighbours,
14201 (mi_r, mi_c),
14202 (bw, bh),
14203 (mi_cols, mi_rows),
14204 skip,
14205 fctx,
14206 )?;
14207 // Whole-block prediction, once, before any coefficient is read
14208 // (`predict_inter_block`); the source is this frame's own
14209 // reconstruction, including the writes this superblock has queued.
14210 flush_recon(fctx, y, u, v);
14211 let mut pred_y_dense = vec![0u16; bw * bh];
14212 mc::predict_with_filter(
14213 &y.data,
14214 y.width,
14215 y.true_width,
14216 y.true_height,
14217 mv_to_q4(px, dv_col, 0),
14218 mv_to_q4(py, dv_row, 0),
14219 bw,
14220 bh,
14221 mc::InterpFilterKind::Bilinear,
14222 &mut pred_y_dense,
14223 fctx,
14224 );
14225 let mut pred_y = vec![0u16; side * side];
14226 for row in 0..bh {
14227 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14228 }
14229 let mut pred_u_dense = vec![0u16; cw * ch];
14230 mc::predict_with_filter(
14231 &u.data,
14232 u.width,
14233 u.true_width,
14234 u.true_height,
14235 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14236 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14237 cw,
14238 ch,
14239 mc::InterpFilterKind::Bilinear,
14240 &mut pred_u_dense,
14241 fctx,
14242 );
14243 let mut pred_u = vec![0u16; cside * cside];
14244 for row in 0..ch {
14245 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14246 }
14247 let mut pred_v_dense = vec![0u16; cw * ch];
14248 mc::predict_with_filter(
14249 &v.data,
14250 v.width,
14251 v.true_width,
14252 v.true_height,
14253 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14254 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14255 cw,
14256 ch,
14257 mc::InterpFilterKind::Bilinear,
14258 &mut pred_v_dense,
14259 fctx,
14260 );
14261 let mut pred_v = vec![0u16; cside * cside];
14262 for row in 0..ch {
14263 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14264 }
14265 let (luma_grid, u_grid, v_grid);
14266 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
14267 // contexts per transform unit -- the replay after this fn's end-of-block
14268 // record restores them (the record itself re-stamps both planes with ONE
14269 // composed state, class `override-slot-on-one-arm`).
14270 let mut mu_chroma = false;
14271 if skip {
14272 // No residual syntax at all: the prediction IS the block. Strides are
14273 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
14274 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
14275 push_mc_rect(
14276 0,
14277 px,
14278 py,
14279 side,
14280 bw,
14281 bh,
14282 Pred::Inline(&pred_y, side),
14283 &ZERO_RESIDUAL[..side * side],
14284 fctx,
14285 );
14286 push_mc_rect(
14287 1,
14288 cpx,
14289 cpy,
14290 cside,
14291 cw,
14292 ch,
14293 Pred::Inline(&pred_u, cside),
14294 &ZERO_RESIDUAL[..cside * cside],
14295 fctx,
14296 );
14297 push_mc_rect(
14298 2,
14299 cpx,
14300 cpy,
14301 cside,
14302 cw,
14303 ch,
14304 Pred::Inline(&pred_v, cside),
14305 &ZERO_RESIDUAL[..cside * cside],
14306 fctx,
14307 );
14308 if let Some(ls) = leaves.as_ref() {
14309 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
14310 // grid before it looks at `skip`; the skipped block still zeroes
14311 // its entropy-band footprint over every unit (libaom
14312 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
14313 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
14314 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14315 for &(row, col, tw, th) in ls {
14316 neighbours.record_mi_luma_rect(
14317 (mi_r + row, mi_c + col),
14318 tw,
14319 th,
14320 &ZERO_RESIDUAL[..tw * th],
14321 );
14322 }
14323 }
14324 luma_grid = Grid::Zero(side * side);
14325 u_grid = Grid::Zero(cside * cside);
14326 v_grid = Grid::Zero(cside * cside);
14327 } else {
14328 let leaves = leaves
14329 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
14330 // libaom `get_transform_size`'s split override applies to LUMA only,
14331 // per leaf -- each unit's own transform edges get filtered
14332 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
14333 for &(row, col, tw, th) in leaves.iter() {
14334 neighbours.fill_lf_grid_leaf_luma(
14335 (mi_r + row, mi_c + col),
14336 tw / MI,
14337 th / MI,
14338 tw as u8,
14339 th as u8,
14340 );
14341 }
14342 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14343 let mut u_units: Vec<i32> = Vec::new();
14344 let mut v_units: Vec<i32> = Vec::new();
14345 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
14346 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
14347 // top-left sample is outside the frame codes nothing.
14348 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
14349 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
14350 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
14351 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
14352 for (pos, &idx) in order.iter().enumerate() {
14353 let (row, col, tw, th) = leaves[idx];
14354 debug_assert_eq!(
14355 tw, th,
14356 "a square TX_64X64 tree root only yields square leaves"
14357 );
14358 let tu_mi = (mi_r + row, mi_c + col);
14359 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14360 if tu_px >= y.true_width || tu_py >= y.true_height {
14361 continue;
14362 }
14363 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14364 let scan = default_scan(tw.min(32));
14365 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14366 let (tu_grid, tu_tx_type) = read_inter_plane(
14367 dec,
14368 cdfs,
14369 inter_txbset_for(tw, reduced),
14370 &scan,
14371 0,
14372 neighbours.around_mi(tu_mi, tw)[0],
14373 0,
14374 y,
14375 tu_px,
14376 tu_py,
14377 tw,
14378 base_q_idx,
14379 tu_pred,
14380 None,
14381 Some(tu_skip_ctx),
14382 fctx,
14383 )?;
14384 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
14385 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14386 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
14387 // mu chunk before the next one starts: once this chunk's leaves
14388 // are done, its chroma is read immediately (the inter 128 path's
14389 // interleave).
14390 let chunk = (row / 16, col / 16);
14391 let done = pos + 1 == order.len()
14392 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
14393 if done {
14394 let (cr, cc) = chunk;
14395 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
14396 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
14397 // within the chunk, plane-major inside the chunk.
14398 let cu_tx = 32usize;
14399 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
14400 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
14401 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
14402 // plane block is 32x64 there), four at 4:4:4. The old
14403 // `chunk_chroma = cside * 64 / side` walked a
14404 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
14405 // axes: at 4:2:2 it read HALF the chroma units of a chunk
14406 // (one 32x32 at the chunk's top-left instead of two), left
14407 // the chunk's lower 32 chroma rows with no residual at all,
14408 // and stamped every unit's entropy context over a 16x16-mi
14409 // luma span instead of 16x8. The same defect and the same
14410 // per-axis repair as `decode_inter_block`'s
14411 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
14412 // witnessed on `422_sb128_3f.obu`).
14413 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14414 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14415 // The unit's own footprint on the LUMA mi grid, per axis:
14416 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
14417 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
14418 // `record_mi_chroma` stamp exactly the unit's own cells.
14419 let unit_luma_w = cu_tx << ss_x(fctx);
14420 let unit_luma_h = cu_tx << ss_y(fctx);
14421 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
14422 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
14423 });
14424 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
14425 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
14426 let units_x = chunk_w_mi / (unit_luma_w / MI);
14427 let units_y = chunk_h_mi / (unit_luma_h / MI);
14428 if lossless(fctx) {
14429 // TX_4X4 chroma units over this chunk (lane-lossless2's
14430 // walk, shared with the inter 128 path).
14431 read_inter_chroma_lossless(
14432 dec,
14433 cdfs,
14434 neighbours,
14435 u,
14436 v,
14437 Pred::Inline(&pred_u, cside),
14438 Pred::Inline(&pred_v, cside),
14439 (mi_r, mi_c),
14440 (cpx, cpy),
14441 (cc * chunk_chroma_w, cr * chunk_chroma_h),
14442 (chunk_chroma_w, chunk_chroma_h),
14443 (cw, ch),
14444 cside,
14445 0,
14446 base_q_idx,
14447 &mut u_units,
14448 &mut v_units,
14449 fctx,
14450 )?;
14451 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
14452 // every TX_4X4 unit's own context (`record_mi_chroma`
14453 // inside the walk) -- the end-of-block record below must
14454 // not overwrite them with the composed grid (the inter
14455 // 128 path sets the same flag on this arm).
14456 mu_chroma = true;
14457 continue;
14458 }
14459 let cu_scan = default_scan(cu_tx);
14460 for plane_idx in 1..3 {
14461 let (src, buf) = if plane_idx == 1 {
14462 (Pred::Inline(&pred_u, cside), &mut *u)
14463 } else {
14464 (Pred::Inline(&pred_v, cside), &mut *v)
14465 };
14466 for ur in 0..units_y {
14467 for uc in 0..units_x {
14468 let unit_mi = (
14469 mi_r + cr * 16 + ur * (unit_luma_h / MI),
14470 mi_c + cc * 16 + uc * (unit_luma_w / MI),
14471 );
14472 // Per unit, AFTER the earlier units' stamps: this
14473 // unit's coefficient context must see them.
14474 let cu_around =
14475 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
14476 if crate::envflags::env_flag!("EC_ECDUMP") {
14477 for p in 1..3 {
14478 let ab: Vec<String> = (0..unit_luma_w / MI)
14479 .map(|k| {
14480 format!(
14481 "{:?}/{}",
14482 neighbours.above[unit_mi.1 + k][p].dc,
14483 neighbours.above[unit_mi.1 + k][p].level
14484 )
14485 })
14486 .collect();
14487 let lf: Vec<String> = (0..unit_luma_h / MI)
14488 .map(|k| {
14489 format!(
14490 "{:?}/{}",
14491 neighbours.left[unit_mi.0 + k][p].dc,
14492 neighbours.left[unit_mi.0 + k][p].level
14493 )
14494 })
14495 .collect();
14496 eprintln!(
14497 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
14498 cu_around[p].0,
14499 cu_around[p].1,
14500 cu_around[p].2,
14501 ab.join(","),
14502 lf.join(",")
14503 );
14504 }
14505 }
14506 let (cu_x, cu_y) = (
14507 cpx + cc * chunk_chroma_w + uc * cu_tx,
14508 cpy + cr * chunk_chroma_h + ur * cu_tx,
14509 );
14510 // `av1_get_tx_type` (blockd.h:1291): an inter
14511 // block's chroma unit never codes a tx_type; it
14512 // inherits the coded type of the luma leaf
14513 // covering its own quadrant (all of this chunk's
14514 // leaves are read by now).
14515 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
14516 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
14517 // The prediction window is the block's own square
14518 // `cside` buffer with the unit's true per-axis
14519 // position inside it.
14520 let cu_pred = src.offset(
14521 (cr * chunk_chroma_h + ur * cu_tx) * cside
14522 + cc * chunk_chroma_w
14523 + uc * cu_tx,
14524 );
14525 let cu_grid = read_inter_plane(
14526 dec,
14527 cdfs,
14528 TxbSet::Chroma32,
14529 &cu_scan,
14530 plane_idx,
14531 cu_around[plane_idx],
14532 0,
14533 buf,
14534 cu_x,
14535 cu_y,
14536 cu_tx,
14537 base_q_idx,
14538 cu_pred,
14539 Some(covering.unwrap_or(TxType::DctDct)),
14540 Some(3),
14541 fctx,
14542 )?
14543 .0;
14544 // Immediately, so the NEXT unit reads this one's
14545 // coefficient context.
14546 neighbours.record_mi_chroma(
14547 unit_mi,
14548 unit_luma_w,
14549 unit_luma_h,
14550 plane_idx,
14551 &cu_grid,
14552 );
14553 if crate::envflags::env_flag!("EC_ECDUMP") {
14554 let st = crate::decode::neighbour_state(&cu_grid);
14555 eprintln!(
14556 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
14557 st.dc, st.level
14558 );
14559 }
14560 hit!(CHROMA_SPLIT_TX_HITS);
14561 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
14562 // lane-av1-ibcrect: per-unit chroma context -- the
14563 // end-of-block record's composed-grid re-stamp
14564 // must not stand (replayed below).
14565 mu_chroma = true;
14566 let dst = mu_units(
14567 if plane_idx == 1 {
14568 &mut u_units
14569 } else {
14570 &mut v_units
14571 },
14572 cside * cside,
14573 );
14574 for rr in 0..cu_tx {
14575 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
14576 + cc * chunk_chroma_w
14577 + uc * cu_tx;
14578 dst[start..start + cu_tx]
14579 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
14580 }
14581 }
14582 }
14583 }
14584 }
14585 }
14586 // The block-level luma bands were recorded per leaf above; the
14587 // composed chroma grids carry every unit in place.
14588 luma_grid = Grid::Zero(side * side);
14589 u_grid = if u_units.is_empty() {
14590 Grid::Zero(cside * cside)
14591 } else {
14592 Grid::Own(std::mem::take(&mut u_units))
14593 };
14594 v_grid = if v_units.is_empty() {
14595 Grid::Zero(cside * cside)
14596 } else {
14597 Grid::Own(std::mem::take(&mut v_units))
14598 };
14599 }
14600 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
14601 // neighbour reads a mode, zeroed palette state, the skip grid, the
14602 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
14603 // and the DV into the intrabc mi grid.
14604 if skip {
14605 neighbours.record_rect_mi(
14606 (mi_r, mi_c),
14607 bw,
14608 bh,
14609 DC_PRED,
14610 DC_PRED,
14611 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
14612 );
14613 } else {
14614 neighbours.record_split_luma_rect_mi(
14615 (mi_r, mi_c),
14616 bw,
14617 bh,
14618 DC_PRED,
14619 DC_PRED,
14620 [&u_grid[..], &v_grid[..]],
14621 );
14622 }
14623 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
14624 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
14625 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
14626 // both planes with ONE `neighbour_state(composed_grid)` over the whole
14627 // span -- level = the SUM of every unit's levels and dc = the top-left
14628 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
14629 // inter block: the next block read a stale `dc_sign_ctx` one row low).
14630 // Measured on this shape: the 128x64 block at mi(64,32) of the
14631 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
14632 // into chunk-0's cells and the block below read `txb_skip` off the sum.
14633 // Replay every coded unit's own state after the record, in mu-chunk order
14634 // so a later unit still wins over an earlier one on the shared seam cells
14635 // (the composed construction `mu_chroma_units` uses, transcribed here).
14636 if mu_chroma {
14637 let cu = if lossless(fctx) { 4usize } else { 32usize };
14638 // The unit's own footprint on the LUMA mi grid (the chroma context
14639 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
14640 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
14641 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
14642 let unit_luma_w = cu << ss_x(fctx);
14643 let unit_luma_h = cu << ss_y(fctx);
14644 // A 64x64 mu chunk's chroma plane block is PER-AXIS
14645 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
14646 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
14647 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
14648 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14649 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14650 if lossless(fctx) {
14651 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
14652 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
14653 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
14654 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
14655 // enumerate it, and this arm re-stamps only the 4x4 at each
14656 // chunk's top-left with a 2x2-mi span. The twin
14657 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
14658 // instead raster-walks the WHOLE plane block at `cu` steps, and
14659 // that is the correct shape here too. It is left as-is on purpose:
14660 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
14661 // it would change 4:2:0 LOSSLESS output -- which this lane's
14662 // byte-identity requirement forbids doing on an unverified
14663 // reconstruction. Measured unreachability: this arm is entered
14664 // 0 times by the whole `lossless` and `intrabc` gate battery
14665 // (temporary env-gated counter in the arm). Unblock: one
14666 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
14667 // intrabc strip (`--lossless=1 --sb-size=128
14668 // --min-partition-size=64 --enable-rect-partitions=1
14669 // --enable-intrabc=1` over near-match screen content).
14670 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14671 for cr in 0..rows {
14672 for cc in 0..cols {
14673 let unit_mi = (
14674 mi_r + cr * (unit_luma_h / MI),
14675 mi_c + cc * (unit_luma_w / MI),
14676 );
14677 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14678 let mut unit = Vec::with_capacity(cu * cu);
14679 for rr in 0..cu {
14680 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
14681 unit.extend_from_slice(&grid[start..start + cu]);
14682 }
14683 neighbours.record_mi_chroma(
14684 unit_mi,
14685 unit_luma_w,
14686 unit_luma_h,
14687 plane_idx,
14688 &unit,
14689 );
14690 }
14691 }
14692 }
14693 } else {
14694 // The chunk count on each axis, then EVERY unit inside each
14695 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
14696 // span, and its own quadrant of the composed plane grid -- the
14697 // twin's loop (decode_inter_block's `mu_chroma_units`,
14698 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
14699 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
14700 // the grid PER UNIT, which only agrees when a chunk holds exactly
14701 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
14702 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
14703 // 2 or 4, so the old body reached only the first of the stacked
14704 // units and the rest of the chunk kept the composed-grid smearing
14705 // this replay exists to undo. A unit the frame edge clipped codes
14706 // nothing and carries no composed samples beyond the clip, so it
14707 // replays as the zero state exactly like libaom's uncoded unit.
14708 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
14709 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14710 for cr in 0..rows {
14711 for cc in 0..cols {
14712 for kr in 0..ur {
14713 for kc in 0..uc {
14714 let unit_mi = (
14715 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
14716 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
14717 );
14718 let (cy, cx) =
14719 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
14720 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14721 let mut unit = Vec::with_capacity(cu * cu);
14722 for rr in 0..cu {
14723 let start = (cy + rr) * cside + cx;
14724 unit.extend_from_slice(&grid[start..start + cu]);
14725 }
14726 neighbours.record_mi_chroma(
14727 unit_mi,
14728 unit_luma_w,
14729 unit_luma_h,
14730 plane_idx,
14731 &unit,
14732 );
14733 }
14734 }
14735 }
14736 }
14737 }
14738 }
14739 }
14740 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14741 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14742 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14743 neighbours.fill_lf_grid_rect(
14744 (mi_r, mi_c),
14745 bw / MI,
14746 bh / MI,
14747 bw.min(64) as u8,
14748 bh.min(64) as u8,
14749 0,
14750 fctx,
14751 );
14752 record_intrabc_mi_rect(
14753 mi_r,
14754 mi_c,
14755 bw / MI,
14756 bh / MI,
14757 Some((dv_row, dv_col)),
14758 neighbours,
14759 fctx,
14760 );
14761 Ok(())
14762}
14763
14764/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
14765/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
14766/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
14767/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
14768/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
14769/// has no rectangular-transform coefficient reader, and a chroma plane here
14770/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
14771/// with no depth-based square-tiling escape the way luma's own resolved
14772/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
14773/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
14774#[allow(clippy::too_many_arguments)]
14775fn decode_block_rect(
14776 dec: &mut SymbolDecoder,
14777 cdfs: &mut Cdfs,
14778 neighbours: &mut Neighbours,
14779 at: (usize, usize),
14780 bw: usize,
14781 bh: usize,
14782 y: &mut PlaneBuf<'static>,
14783 u: &mut PlaneBuf<'static>,
14784 v: &mut PlaneBuf<'static>,
14785 enable_filter_intra: bool,
14786 allow_screen_content_tools: bool,
14787 base_q_idx: u8,
14788 tx_select: bool,
14789 reduced_tx_set: bool,
14790 fctx: &crate::decode::FrameCtx,
14791) -> Result<()> {
14792 let (r, c) = at;
14793 let (px, py) = (c * SUB, r * SUB);
14794 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14795 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14796 let palette_uv_cache = neighbours.palette_uv_cache(at);
14797 let (
14798 skip,
14799 mode,
14800 angle_delta_y,
14801 uv_mode,
14802 angle_delta_uv,
14803 alpha,
14804 filter_intra,
14805 palette_y,
14806 palette_uv,
14807 intrabc,
14808 ) = read_intra_mode_rect(
14809 dec,
14810 cdfs,
14811 nb_above_mode,
14812 nb_left_mode,
14813 true,
14814 true,
14815 bw,
14816 bh,
14817 enable_filter_intra,
14818 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14819 allow_screen_content_tools,
14820 Some((palette_ctx, &palette_cache)),
14821 &palette_uv_cache,
14822 r * (SUB / MI),
14823 c * (SUB / MI),
14824 fctx,
14825 )?;
14826
14827 if let Some((dv_row, dv_col)) = intrabc {
14828 return decode_intrabc_rect(
14829 dec,
14830 cdfs,
14831 neighbours,
14832 (r * (SUB / MI), c * (SUB / MI)),
14833 (bw, bh),
14834 skip,
14835 (dv_row, dv_col),
14836 y,
14837 u,
14838 v,
14839 base_q_idx,
14840 fctx,
14841 );
14842 }
14843 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14844 if smooth_neighbor {
14845 hit!(SMOOTH_LUMA_HITS);
14846 }
14847 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
14848 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
14849 // `uv_mode`, not the luma one.
14850 let smooth_neighbor_uv =
14851 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14852 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
14853 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
14854 // rectangle just as happily), so a `use_filter_intra` strip at this level
14855 // predicts instead of refusing. The below-16x16 leaf arm
14856 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
14857 if filter_intra.is_some() {
14858 hit!(FILTER_INTRA_RECT_HITS);
14859 }
14860 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14861 DC_PRED
14862 } else {
14863 uv_mode
14864 };
14865 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14866 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
14867 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
14868 // one did not, so with `--enable-tx-size-search=0` -- which several gate
14869 // recipes use -- the decoder consumed a symbol the encoder never wrote and
14870 // desynced the tile from that point on. That is why both strips of the
14871 // pinned HORZ quadrant were wrong from their very first pixel, and why our
14872 // range after the read equalled the oracle's range for the whole block.
14873 // lane-av1mixloss: the lossless-segment early return
14874 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
14875 // rect block codes no depth symbol here either (class sweep of the sub8
14876 // leaf's fix).
14877 let depth = if tx_select && !lossless(fctx) {
14878 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
14879 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
14880 // intra-only frame publishes them from every block too
14881 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
14882 // 1920x792 128-superblock stream,
14883 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
14884 // `tx_size_cat2` row 1 where libaom reads row 2.
14885 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
14886 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
14887 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14888 eprintln!(
14889 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
14890 dec.debug_state().0
14891 );
14892 }
14893 d
14894 } else {
14895 0
14896 };
14897 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
14898 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
14899 publish_txfm_bands_if_in_inter(
14900 neighbours,
14901 (mi_r, mi_c),
14902 depth_to_tx_wh(bw, bh, depth, fctx),
14903 (bw, bh),
14904 fctx,
14905 );
14906 if depth != 0 || lossless(fctx) {
14907 hit!(TX_DEPTH_HITS);
14908 // lane-rectsplit r1: a split transform is predicted and reconstructed
14909 // per transform unit, each unit taking its edges from the previous
14910 // unit's reconstruction inside this same strip (spec 5.11.36) --
14911 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
14912 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14913 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
14914 eprintln!(
14915 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
14916 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
14917 angle_y={angle_delta_y}"
14918 );
14919 }
14920 let modes = RectStripModes {
14921 skip,
14922 mode,
14923 angle_delta_y,
14924 uv_predict_mode,
14925 angle_delta_uv,
14926 alpha,
14927 filter_intra,
14928 smooth_neighbor,
14929 smooth_neighbor_uv,
14930 palette_y: palette_y
14931 .as_ref()
14932 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
14933 palette_uv: palette_uv.as_ref().map(|p| {
14934 (
14935 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14936 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14937 )
14938 }),
14939 };
14940 if palette_y.is_some() || palette_uv.is_some() {
14941 hit!(PALETTE_SPLIT_TX_HITS);
14942 }
14943 decode_rect_split(
14944 dec,
14945 cdfs,
14946 neighbours,
14947 (mi_r, mi_c),
14948 bw,
14949 bh,
14950 tx_w,
14951 tx_h,
14952 &modes,
14953 y,
14954 u,
14955 v,
14956 base_q_idx,
14957 reduced_tx_set,
14958 fctx,
14959 )?;
14960 // This early return skips this fn's own tail, so the palette
14961 // neighbour state has to be stamped HERE too: without it a split-tx
14962 // strip left the above/left palette arrays holding a DEAD block's
14963 // colours, and the next block's colour cache
14964 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
14965 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
14966 // and only those pixels were wrong (lane-palette2 r10).
14967 let (py_size, py_colors) = palette_y
14968 .as_ref()
14969 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14970 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14971 let (puv_size, puv_colors) = palette_uv
14972 .as_ref()
14973 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14974 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14975 hit!(RECT_PARTITION_HITS);
14976 return Ok(());
14977 }
14978 let (tx_w, tx_h) = (bw, bh);
14979 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14980 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14981 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14982 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14983 let (rng, _) = dec.debug_state();
14984 eprintln!(
14985 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
14986 skip={} tx={depth} rng={rng}",
14987 skip as i32
14988 );
14989 }
14990 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
14991 // block's prediction is the reconstructed colour-index map, set fresh
14992 // right before each `reconstruct_rect` call below (lane-palette2 r4).
14993 if let Some(ref pyv) = palette_y {
14994 let buf: Vec<u16> = pyv
14995 .map
14996 .iter()
14997 .map(|&idx| pyv.colors[idx as usize])
14998 .collect();
14999 set_palette_pred(buf, fctx);
15000 }
15001 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15002 (
15003 puv.map
15004 .iter()
15005 .map(|&idx| puv.u_colors[idx as usize])
15006 .collect(),
15007 puv.map
15008 .iter()
15009 .map(|&idx| puv.v_colors[idx as usize])
15010 .collect(),
15011 )
15012 });
15013 if skip {
15014 push_intra_rect(
15015 0,
15016 px,
15017 py,
15018 bw,
15019 bh,
15020 mode,
15021 angle_delta_y,
15022 reach,
15023 &ZERO_RESIDUAL[..bw * bh],
15024 None,
15025 filter_intra,
15026 smooth_neighbor,
15027 fctx,
15028 );
15029 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15030 if let Some((ub, _)) = &palette_uv_bufs {
15031 set_palette_pred(ub.clone(), fctx);
15032 }
15033 push_intra_rect(
15034 1,
15035 cpx,
15036 cpy,
15037 chroma_w,
15038 chroma_h,
15039 uv_predict_mode,
15040 angle_delta_uv,
15041 reach,
15042 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15043 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15044 None,
15045 smooth_neighbor_uv,
15046 fctx,
15047 );
15048 if let Some((_, vb)) = &palette_uv_bufs {
15049 set_palette_pred(vb.clone(), fctx);
15050 }
15051 push_intra_rect(
15052 2,
15053 cpx,
15054 cpy,
15055 chroma_w,
15056 chroma_h,
15057 uv_predict_mode,
15058 angle_delta_uv,
15059 reach,
15060 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15061 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15062 None,
15063 smooth_neighbor_uv,
15064 fctx,
15065 );
15066 neighbours.record_rect(
15067 at,
15068 bw,
15069 bh,
15070 mode,
15071 uv_predict_mode,
15072 &[
15073 &ZERO_RESIDUAL[..bw * bh],
15074 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15075 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15076 ],
15077 );
15078 } else {
15079 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
15080 // reduces both size pairs to their square-up CDF sets
15081 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
15082 // doc comments); the scan order and 2D context tables are the real
15083 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
15084 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
15085 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
15086 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
15087 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
15088 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15089 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15090 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15091 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
15092 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
15093 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
15094 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
15095 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
15096 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
15097 // default follows the >=32 rule below -- the same pairing the
15098 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
15099 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
15100 // is reachable there.
15101 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
15102 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15103 _ => {
15104 return Err(unsupported(
15105 "a rectangular chroma transform whose size has no coefficient table",
15106 ));
15107 }
15108 };
15109 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
15110 TxType::DctDct
15111 } else {
15112 default_intra_tx_type(uv_predict_mode as u8)
15113 };
15114 // lane-rectwire r3: real coefficients desync a pixel-exact gate
15115 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
15116 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
15117 // pixel (not a subtle context-table off-by-one), while the sibling
15118 // non-rect quadrants of the same frame match. Range-ladder bisection
15119 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
15120 // but the intra key-frame path has no traced symbol between the
15121 // partition read and the first coefficient block (mode/skip/tx_depth
15122 // reads are all untraced in libaom's decodeframe.c intra path, unlike
15123 // the inter EC_TRACE_MODE this round added), so a same-length range
15124 // comparison wasn't reachable within budget -- see
15125 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
15126 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
15127 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
15128 // libaom and match). lane-rectwire r4: range-ladder against the
15129 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
15130 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
15131 // both confirmed in sync -- rng=58692 on both sides right after
15132 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
15133 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
15134 // immediately after: ours moves rng 58692 -> 43570, which cannot be
15135 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
15136 // its own tx_size read) unless oracle's tx symbol is a near-certainty
15137 // CDF that barely narrows the range -- i.e. this decoder's
15138 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
15139 // a 32x16/16x32 strip is the first diverging symbol, not the
15140 // coefficient-context math r3 already cleared. Not confirmed byte-
15141 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
15142 // `read_tx_size`'s own rng, not attempted this round -- budget), so
15143 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
15144 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
15145 // it unconditionally where both square paths gate on `tx_select`. With
15146 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
15147 // decoder consumed one that was never there.
15148 {
15149 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15150 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15151 // strip's chroma is a square (side/2, side) block whose above cells
15152 // spread over `side` LUMA mi columns, so the per-mi rect gather
15153 // double-counts every chroma column's whole-unit dc sign. Measured on
15154 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15155 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15156 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15157 // 45260 whose pre-state, bit position and symbol all match and only
15158 // the CDF row differs, and the first divergence in the EC_SYMR
15159 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15160 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15161 let mut around = neighbours.around_rect(at, bw, bh);
15162 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15163 let c2 =
15164 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15165 around[1] = c2[1];
15166 around[2] = c2[2];
15167 }
15168 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15169 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15170 dec,
15171 &mut luma_coding,
15172 luma_scan,
15173 bw,
15174 bh,
15175 0,
15176 dc_sign_ctx(around[0].2),
15177 TxType::DctDct,
15178 0,
15179 )?;
15180 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15181 let (rng, _) = dec.debug_state();
15182 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15183 }
15184 let luma_residual = dequant_and_inverse_typed_wh(
15185 &luma_levels,
15186 bw,
15187 bh,
15188 crate::decode::bit_depth(fctx),
15189 block_q_idx(fctx),
15190 plane_q_delta(0, fctx).0,
15191 plane_q_delta(0, fctx).1,
15192 luma_tx_type,
15193 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15194 );
15195 push_intra_rect(
15196 0,
15197 px,
15198 py,
15199 bw,
15200 bh,
15201 mode,
15202 angle_delta_y,
15203 reach,
15204 &luma_residual,
15205 None,
15206 filter_intra,
15207 smooth_neighbor,
15208 fctx,
15209 );
15210 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15211 if let Some((ub, _)) = &palette_uv_bufs {
15212 set_palette_pred(ub.clone(), fctx);
15213 }
15214 let u_default_tx = chroma_default_tx;
15215 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15216 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15217 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15218 dec,
15219 &mut u_coding,
15220 chroma_scan,
15221 chroma_w,
15222 chroma_h,
15223 u_skip_ctx,
15224 dc_sign_ctx(around[1].2),
15225 u_default_tx,
15226 fctx,
15227 1,
15228 )?;
15229 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15230 let (rng, _) = dec.debug_state();
15231 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15232 }
15233 let u_residual = dequant_and_inverse_typed_wh(
15234 &u_levels,
15235 chroma_w,
15236 chroma_h,
15237 crate::decode::bit_depth(fctx),
15238 block_q_idx(fctx),
15239 plane_q_delta(1, fctx).0,
15240 plane_q_delta(1, fctx).1,
15241 u_tx_type,
15242 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15243 );
15244 push_intra_rect(
15245 1,
15246 cpx,
15247 cpy,
15248 chroma_w,
15249 chroma_h,
15250 uv_predict_mode,
15251 angle_delta_uv,
15252 reach,
15253 &u_residual,
15254 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15255 None,
15256 smooth_neighbor_uv,
15257 fctx,
15258 );
15259 if let Some((_, vb)) = &palette_uv_bufs {
15260 set_palette_pred(vb.clone(), fctx);
15261 }
15262 let v_default_tx = chroma_default_tx;
15263 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15264 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
15265 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
15266 dec,
15267 &mut v_coding,
15268 chroma_scan,
15269 chroma_w,
15270 chroma_h,
15271 v_skip_ctx,
15272 dc_sign_ctx(around[2].2),
15273 v_default_tx,
15274 fctx,
15275 2,
15276 )?;
15277 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15278 let (rng, _) = dec.debug_state();
15279 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15280 }
15281 let v_residual = dequant_and_inverse_typed_wh(
15282 &v_levels,
15283 chroma_w,
15284 chroma_h,
15285 crate::decode::bit_depth(fctx),
15286 block_q_idx(fctx),
15287 plane_q_delta(2, fctx).0,
15288 plane_q_delta(2, fctx).1,
15289 v_tx_type,
15290 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15291 );
15292 push_intra_rect(
15293 2,
15294 cpx,
15295 cpy,
15296 chroma_w,
15297 chroma_h,
15298 uv_predict_mode,
15299 angle_delta_uv,
15300 reach,
15301 &v_residual,
15302 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15303 None,
15304 smooth_neighbor_uv,
15305 fctx,
15306 );
15307 neighbours.record_rect(
15308 at,
15309 bw,
15310 bh,
15311 mode,
15312 uv_predict_mode,
15313 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15314 );
15315 hit!(RECT_COEFF_HITS);
15316 }
15317 }
15318 let (py_size, py_colors) = palette_y
15319 .as_ref()
15320 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15321 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15322 let (puv_size, puv_colors) = palette_uv
15323 .as_ref()
15324 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15325 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15326 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15327 neighbours.fill_lf_grid_rect(
15328 (mi_r, mi_c),
15329 bw / MI,
15330 bh / MI,
15331 tx_w as u8,
15332 tx_h as u8,
15333 0,
15334 fctx,
15335 );
15336 hit!(RECT_PARTITION_HITS);
15337 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15338 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
15339 }
15340 Ok(())
15341}
15342
15343/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
15344/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
15345/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
15346/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
15347/// the second strip of a HORZ/VERT split sits offset by half the 16x16
15348/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
15349/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
15350/// previous strip is directly above (same column, `mi_h` rows up) or
15351/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
15352/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
15353/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
15354/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
15355/// this strip's real position, never the coarse `record_rect` (which the
15356/// caller uses once, after both strips, exactly like the `VERT_B` arm next
15357/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
15358/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
15359/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
15360/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
15361/// half-width, unhalved height), the two size classes one level
15362/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
15363#[allow(clippy::too_many_arguments)]
15364fn decode_leaf_rect(
15365 dec: &mut SymbolDecoder,
15366 cdfs: &mut Cdfs,
15367 neighbours: &mut Neighbours,
15368 outer_at: (usize, usize),
15369 leaf_mi: (usize, usize),
15370 bw: usize,
15371 bh: usize,
15372 prev_leaf: Option<((usize, usize), usize)>,
15373 y: &mut PlaneBuf<'static>,
15374 u: &mut PlaneBuf<'static>,
15375 v: &mut PlaneBuf<'static>,
15376 enable_filter_intra: bool,
15377 allow_screen_content_tools: bool,
15378 base_q_idx: u8,
15379 tx_select: bool,
15380 reduced_tx_set: bool,
15381 fctx: &crate::decode::FrameCtx,
15382) -> Result<usize> {
15383 let _ = base_q_idx;
15384 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15385 eprintln!(
15386 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
15387 dec.debug_state().0
15388 );
15389 }
15390 let (r, c) = outer_at;
15391 let mut above_mode = neighbours.above_mode[c];
15392 let mut left_mode = neighbours.left_mode[r];
15393 let (mi_w, mi_h) = (bw / MI, bh / MI);
15394 if let Some(((pr, pc), pmode)) = prev_leaf {
15395 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
15396 above_mode = pmode;
15397 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
15398 left_mode = pmode;
15399 }
15400 }
15401 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
15402 // cannot hold the modes a split (or a pair of strips) leaves behind, so
15403 // when the map holds the block at exactly this strip's above/left mi it
15404 // is the neighbour libaom's `above_mi`/`left_mi` reads.
15405 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
15406 // availability-correct -- four 16x8 strips share one coarse 16x16
15407 // `left_mode` cell too, so the fallback must not stand in for an absent
15408 // tile-edge neighbour.
15409 let (above_mode, left_mode) =
15410 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15411 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15412 if smooth_neighbor {
15413 hit!(SMOOTH_LUMA_HITS);
15414 }
15415 // The palette-Y mode CDF row is picked by the neighbours' palette use
15416 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
15417 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
15418 // a palette narrows the wrong interval and desyncs the tile even when the
15419 // decoded bit is the same. The cell is the 16px-SUB cell containing the
15420 // leaf (the palette neighbour arrays have no finer granularity).
15421 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
15422 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
15423 // exclusion and the neighbour palette lookup itself are mi-granular
15424 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
15425 let pal_at = leaf_mi;
15426 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15427 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15428 let (
15429 skip,
15430 mode,
15431 angle_delta_y,
15432 uv_mode,
15433 angle_delta_uv,
15434 alpha,
15435 filter_intra,
15436 palette_y,
15437 palette_uv,
15438 intrabc,
15439 ) = read_intra_mode_rect(
15440 dec,
15441 cdfs,
15442 above_mode,
15443 left_mode,
15444 true,
15445 true,
15446 bw,
15447 bh,
15448 enable_filter_intra,
15449 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15450 allow_screen_content_tools,
15451 Some((palette_ctx, &palette_cache)),
15452 &palette_uv_cache,
15453 leaf_mi.0,
15454 leaf_mi.1,
15455 fctx,
15456 )?;
15457
15458 if let Some((dv_row, dv_col)) = intrabc {
15459 decode_intrabc_rect(
15460 dec,
15461 cdfs,
15462 neighbours,
15463 leaf_mi,
15464 (bw, bh),
15465 skip,
15466 (dv_row, dv_col),
15467 y,
15468 u,
15469 v,
15470 base_q_idx,
15471 fctx,
15472 )?;
15473 return Ok(DC_PRED);
15474 }
15475 // lane-kf900 r4: palette prediction on this shape, the same colour-index
15476 // map -> base colours buffer [`decode_block_rect`] hands each
15477 // `reconstruct_rect` through [`set_palette_pred`].
15478 if palette_y.is_some() || palette_uv.is_some() {
15479 hit!(RECT4_PALETTE_HITS);
15480 }
15481 let palette_y_buf: Option<Vec<u16>> = palette_y
15482 .as_ref()
15483 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15484 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15485 (
15486 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15487 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15488 )
15489 });
15490 let (pal_y_size, pal_y_colors) = palette_y
15491 .as_ref()
15492 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15493 let (pal_uv_size, pal_uv_colors) = palette_uv
15494 .as_ref()
15495 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15496 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15497 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
15498 }
15499 if filter_intra.is_some() {
15500 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
15501 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
15502 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
15503 // below already makes; this refusal was square-only prose.
15504 hit!(FILTER_INTRA_RECT_HITS);
15505 hit!(FILTER_INTRA_RECT_SUB16_HITS);
15506 }
15507 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15508 DC_PRED
15509 } else {
15510 uv_mode
15511 };
15512 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
15513 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
15514 // a constant `false`.
15515 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
15516 let depth = if tx_select && !lossless(fctx) {
15517 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
15518 // every other rect reader now does -- a no-op on a key frame.
15519 // lane-av1mixloss: libaom `read_tx_size`'s first line
15520 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
15521 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
15522 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
15523 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
15524 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
15525 // read was the leaf's own txb_skip.
15526 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
15527 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
15528 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
15529 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
15530 // count (3), different CDF row: a wrong-table read of a real symbol,
15531 // the class that cost lane-rectsplit r1 its 64x32 depth.
15532 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
15533 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
15534 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
15535 // function also decodes) sit at depth 2, so they read
15536 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
15537 // while `tx_size_cat2` belongs to the 32-level shapes
15538 // ([`decode_block_rect`]). Both tables carry three symbols, so the
15539 // wrong one decodes a plausible depth from the wrong probabilities:
15540 // the range diverges silently at the first such leaf and every later
15541 // symbol in the tile is read from the wrong place (class
15542 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
15543 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
15544 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15545 eprintln!(
15546 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
15547 leaf_mi.0,
15548 leaf_mi.1,
15549 dec.debug_state().0
15550 );
15551 }
15552 d
15553 } else {
15554 0
15555 };
15556 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
15557 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15558 publish_txfm_bands_if_in_inter(
15559 neighbours,
15560 leaf_mi,
15561 depth_to_tx_wh(bw, bh, depth, fctx),
15562 (bw, bh),
15563 fctx,
15564 );
15565 if depth != 0 || lossless(fctx) {
15566 // The same per-transform-unit walk the bigger strips take
15567 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
15568 // depth 2), addressed at this leaf's own mi position.
15569 hit!(TX_DEPTH_HITS);
15570 hit!(SUB16_SPLIT_HITS);
15571 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15572 let modes = RectStripModes {
15573 skip,
15574 mode,
15575 angle_delta_y,
15576 uv_predict_mode,
15577 angle_delta_uv,
15578 alpha,
15579 filter_intra,
15580 smooth_neighbor,
15581 // lane-rectsplitx r3: the split arm hard-coded `false` here while
15582 // the unsplit arm below passes the real neighbour answer -- chroma
15583 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
15584 smooth_neighbor_uv,
15585 palette_y: palette_y_buf.clone(),
15586 palette_uv: palette_uv_bufs.clone(),
15587 };
15588 if palette_y.is_some() || palette_uv.is_some() {
15589 hit!(PALETTE_SPLIT_TX_HITS);
15590 }
15591 decode_rect_split(
15592 dec,
15593 cdfs,
15594 neighbours,
15595 leaf_mi,
15596 bw,
15597 bh,
15598 tx_w,
15599 tx_h,
15600 &modes,
15601 y,
15602 u,
15603 v,
15604 base_q_idx,
15605 reduced_tx_set,
15606 fctx,
15607 )?;
15608 record_strip_palette(
15609 neighbours,
15610 pal_at,
15611 bw,
15612 bh,
15613 pal_y_size,
15614 pal_y_colors,
15615 pal_uv_size,
15616 pal_uv_colors,
15617 );
15618 return Ok(mode);
15619 }
15620 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15621 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15622 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15623 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15624 let (luma_levels, u_levels, v_levels);
15625 if skip {
15626 luma_levels = Grid::Zero(bw * bh);
15627 u_levels = Grid::Zero(chroma_w * chroma_h);
15628 v_levels = Grid::Zero(chroma_w * chroma_h);
15629 if let Some(b) = &palette_y_buf {
15630 set_palette_pred(b.clone(), fctx);
15631 }
15632 push_intra_rect(
15633 0,
15634 px,
15635 py,
15636 bw,
15637 bh,
15638 mode,
15639 angle_delta_y,
15640 reach,
15641 &luma_levels,
15642 None,
15643 filter_intra,
15644 smooth_neighbor,
15645 fctx,
15646 );
15647 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15648 if let Some((ub, _)) = &palette_uv_bufs {
15649 set_palette_pred(ub.clone(), fctx);
15650 }
15651 push_intra_rect(
15652 1,
15653 cpx,
15654 cpy,
15655 chroma_w,
15656 chroma_h,
15657 uv_predict_mode,
15658 angle_delta_uv,
15659 reach,
15660 &u_levels,
15661 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15662 None,
15663 smooth_neighbor_uv,
15664 fctx,
15665 );
15666 if let Some((_, vb)) = &palette_uv_bufs {
15667 set_palette_pred(vb.clone(), fctx);
15668 }
15669 push_intra_rect(
15670 2,
15671 cpx,
15672 cpy,
15673 chroma_w,
15674 chroma_h,
15675 uv_predict_mode,
15676 angle_delta_uv,
15677 reach,
15678 &v_levels,
15679 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15680 None,
15681 smooth_neighbor_uv,
15682 fctx,
15683 );
15684 } else {
15685 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
15686 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
15687 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
15688 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
15689 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
15690 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
15691 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
15692 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
15693 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
15694 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
15695 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
15696 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
15697 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
15698 if bw == 16 {
15699 (&SCAN_16X8, &SCAN_16X8)
15700 } else {
15701 (&SCAN_8X16, &SCAN_8X16)
15702 }
15703 } else if chroma_422 {
15704 if bw == 16 {
15705 (&SCAN_16X8, default_scan(8))
15706 } else {
15707 (&SCAN_8X16, default_scan(8))
15708 }
15709 } else if bw == 16 {
15710 (&SCAN_16X8, &SCAN_8X4)
15711 } else {
15712 (&SCAN_8X16, &SCAN_4X8)
15713 };
15714 let chroma_rect_set = if ss_x(fctx) == 0 {
15715 TxbSet::ChromaRect16x8
15716 } else if chroma_422 {
15717 TxbSet::Chroma8
15718 } else {
15719 TxbSet::ChromaRect8x4
15720 };
15721 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
15722 // (side/2, side) block, so `side` chroma 4-px cells above it spread
15723 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
15724 // mi cells, and both carry the covering unit's whole-unit dc sign.
15725 // The per-mi rect gather therefore double-counts every chroma
15726 // column's sign. `around_mi_422_chroma`'s every-second above-cell
15727 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
15728 // gather in this file already routes through it (see the gate at this
15729 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
15730 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
15731 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
15732 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
15733 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
15734 // divergence in the frame (the bit offset is a clean constant through
15735 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
15736 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15737 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
15738 if chroma_422 {
15739 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
15740 around[1] = c[1];
15741 around[2] = c[2];
15742 }
15743 let luma_set = if reduced_tx_set {
15744 TxbSet::LumaRect16x8
15745 } else {
15746 TxbSet::LumaRect16x8Set1
15747 };
15748 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
15749 let (l_levels, luma_tx_type) = read_coeffs_rect(
15750 dec,
15751 &mut luma_coding,
15752 luma_scan,
15753 bw,
15754 bh,
15755 0,
15756 dc_sign_ctx(around[0].2),
15757 TxType::DctDct,
15758 0,
15759 )?;
15760 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15761 let nz: Vec<(usize, i32)> = l_levels
15762 .iter()
15763 .copied()
15764 .enumerate()
15765 .filter(|(_, v)| *v != 0)
15766 .collect();
15767 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
15768 }
15769 luma_levels = l_levels;
15770 let luma_residual = dequant_and_inverse_typed_wh(
15771 &luma_levels,
15772 bw,
15773 bh,
15774 crate::decode::bit_depth(fctx),
15775 block_q_idx(fctx),
15776 plane_q_delta(0, fctx).0,
15777 plane_q_delta(0, fctx).1,
15778 luma_tx_type,
15779 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15780 );
15781 if let Some(b) = &palette_y_buf {
15782 set_palette_pred(b.clone(), fctx);
15783 }
15784 push_intra_rect(
15785 0,
15786 px,
15787 py,
15788 bw,
15789 bh,
15790 mode,
15791 angle_delta_y,
15792 reach,
15793 &luma_residual,
15794 None,
15795 filter_intra,
15796 smooth_neighbor,
15797 fctx,
15798 );
15799 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15800 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15801 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15802 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15803 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
15804 dec,
15805 &mut u_coding,
15806 chroma_scan,
15807 chroma_w,
15808 chroma_h,
15809 u_skip_ctx,
15810 dc_sign_ctx(around[1].2),
15811 u_default_tx,
15812 fctx,
15813 1,
15814 )?;
15815 u_levels = u_l;
15816 let u_residual = dequant_and_inverse_typed_wh(
15817 &u_levels,
15818 chroma_w,
15819 chroma_h,
15820 crate::decode::bit_depth(fctx),
15821 block_q_idx(fctx),
15822 plane_q_delta(1, fctx).0,
15823 plane_q_delta(1, fctx).1,
15824 u_tx_type,
15825 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15826 );
15827 if let Some((ub, _)) = &palette_uv_bufs {
15828 set_palette_pred(ub.clone(), fctx);
15829 }
15830 push_intra_rect(
15831 1,
15832 cpx,
15833 cpy,
15834 chroma_w,
15835 chroma_h,
15836 uv_predict_mode,
15837 angle_delta_uv,
15838 reach,
15839 &u_residual,
15840 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15841 None,
15842 smooth_neighbor_uv,
15843 fctx,
15844 );
15845 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15846 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15847 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15848 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
15849 dec,
15850 &mut v_coding,
15851 chroma_scan,
15852 chroma_w,
15853 chroma_h,
15854 v_skip_ctx,
15855 dc_sign_ctx(around[2].2),
15856 v_default_tx,
15857 fctx,
15858 2,
15859 )?;
15860 v_levels = v_l;
15861 let v_residual = dequant_and_inverse_typed_wh(
15862 &v_levels,
15863 chroma_w,
15864 chroma_h,
15865 crate::decode::bit_depth(fctx),
15866 block_q_idx(fctx),
15867 plane_q_delta(2, fctx).0,
15868 plane_q_delta(2, fctx).1,
15869 v_tx_type,
15870 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15871 );
15872 if let Some((_, vb)) = &palette_uv_bufs {
15873 set_palette_pred(vb.clone(), fctx);
15874 }
15875 push_intra_rect(
15876 2,
15877 cpx,
15878 cpy,
15879 chroma_w,
15880 chroma_h,
15881 uv_predict_mode,
15882 angle_delta_uv,
15883 reach,
15884 &v_residual,
15885 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15886 None,
15887 smooth_neighbor_uv,
15888 fctx,
15889 );
15890 hit!(RECT_LEAF_COEFF_HITS);
15891 }
15892 neighbours.record_mi_rect(
15893 leaf_mi,
15894 bw,
15895 bh,
15896 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15897 );
15898 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
15899 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15900 // The leaf's own palette state (`0` clears, as this site always did
15901 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
15902 // AXIS only until the pair's closing leaf: the coarse cell holds one
15903 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
15904 // real left neighbour leaf 1 reads (lane-kf900 r4).
15905 record_strip_palette(
15906 neighbours,
15907 pal_at,
15908 bw,
15909 bh,
15910 pal_y_size,
15911 pal_y_colors,
15912 pal_uv_size,
15913 pal_uv_colors,
15914 );
15915 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
15916 // rows -- record the whole span, not one cell.
15917 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
15918 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
15919 Ok(mode)
15920}
15921
15922/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
15923/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
15924/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
15925/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
15926/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
15927/// strip's mode so this one's mode context sees its true above/left
15928/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
15929///
15930/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
15931/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
15932/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
15933/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
15934/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
15935/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
15936/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
15937///
15938/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
15939/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
15940/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
15941/// unexamined.
15942#[allow(clippy::too_many_arguments)]
15943fn decode_block_rect4(
15944 dec: &mut SymbolDecoder,
15945 cdfs: &mut Cdfs,
15946 neighbours: &mut Neighbours,
15947 strip_mi: (usize, usize),
15948 bw: usize,
15949 bh: usize,
15950 prev_strip: Option<((usize, usize), usize)>,
15951 y: &mut PlaneBuf<'static>,
15952 u: &mut PlaneBuf<'static>,
15953 v: &mut PlaneBuf<'static>,
15954 enable_filter_intra: bool,
15955 allow_screen_content_tools: bool,
15956 base_q_idx: u8,
15957 tx_select: bool,
15958 fctx: &crate::decode::FrameCtx,
15959) -> Result<(usize, usize)> {
15960 let _ = base_q_idx;
15961 let (mi_r, mi_c) = strip_mi;
15962 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
15963 let (mi_w, mi_h) = (bw / MI, bh / MI);
15964 let mut above_mode = neighbours.above_mode[c];
15965 let mut left_mode = neighbours.left_mode[r];
15966 if let Some(((pr, pc), pmode)) = prev_strip {
15967 if pc == mi_c && mi_r == pr + mi_h {
15968 above_mode = pmode;
15969 } else if pr == mi_r && mi_c == pc + mi_w {
15970 left_mode = pmode;
15971 }
15972 }
15973 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
15974 // availability-correct neighbour modes (see
15975 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
15976 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
15977 let (above_mode, left_mode) =
15978 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
15979 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
15980 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
15981 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
15982 // wrong interval, so a screen-content tile desynced at the first strip
15983 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
15984 let pal_at = (mi_r, mi_c);
15985 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15986 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15987 let (
15988 skip,
15989 mode,
15990 angle_delta_y,
15991 uv_mode,
15992 angle_delta_uv,
15993 alpha,
15994 filter_intra,
15995 palette_y,
15996 palette_uv,
15997 intrabc,
15998 ) = read_intra_mode_rect(
15999 dec,
16000 cdfs,
16001 above_mode,
16002 left_mode,
16003 true,
16004 true,
16005 bw,
16006 bh,
16007 enable_filter_intra,
16008 neighbours.skip_txfm_ctx(mi_r, mi_c),
16009 allow_screen_content_tools,
16010 Some((palette_ctx, &palette_cache)),
16011 &palette_uv_cache,
16012 mi_r,
16013 mi_c,
16014 fctx,
16015 )?;
16016 if let Some((dv_row, dv_col)) = intrabc {
16017 decode_intrabc_rect(
16018 dec,
16019 cdfs,
16020 neighbours,
16021 strip_mi,
16022 (bw, bh),
16023 skip,
16024 (dv_row, dv_col),
16025 y,
16026 u,
16027 v,
16028 base_q_idx,
16029 fctx,
16030 )?;
16031 return Ok((DC_PRED, DC_PRED));
16032 }
16033 // lane-kf900 r4: palette prediction on this shape, exactly as
16034 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
16035 // mapped through the base colours IS the prediction (it reads no edge
16036 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
16037 if palette_y.is_some() || palette_uv.is_some() {
16038 hit!(RECT4_PALETTE_HITS);
16039 }
16040 let palette_y_buf: Option<Vec<u16>> = palette_y
16041 .as_ref()
16042 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16043 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16044 (
16045 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16046 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16047 )
16048 });
16049 let (pal_y_size, pal_y_colors) = palette_y
16050 .as_ref()
16051 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16052 let (pal_uv_size, pal_uv_colors) = palette_uv
16053 .as_ref()
16054 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16055 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16056 if smooth_neighbor {
16057 hit!(SMOOTH_LUMA_HITS);
16058 }
16059 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
16060 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
16061 // `r * (SUB / MI)` names a different mi column and the chroma
16062 // edge-filter strength was read from the wrong neighbour (measured:
16063 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
16064 // with luma bit-exact).
16065 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
16066 if filter_intra.is_some() {
16067 hit!(FILTER_INTRA_RECT_HITS);
16068 if bw > bh {
16069 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
16070 } else {
16071 hit!(FILTER_INTRA_RECT4_VERT_HITS);
16072 }
16073 }
16074 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16075 DC_PRED
16076 } else {
16077 uv_mode
16078 };
16079 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
16080 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
16081 // depth symbol here either (class sweep of the sub8 leaf's fix).
16082 let depth = if tx_select && !lossless(fctx) {
16083 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
16084 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
16085 // intra-only frame publishes them from every block too
16086 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
16087 // 1920x792 128-superblock stream,
16088 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
16089 // `tx_size_cat2` row 1 where libaom reads row 2.
16090 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
16091 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
16092 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16093 eprintln!(
16094 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
16095 dec.debug_state().0
16096 );
16097 }
16098 d
16099 } else {
16100 0
16101 };
16102 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
16103 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
16104 publish_txfm_bands_if_in_inter(
16105 neighbours,
16106 (mi_r, mi_c),
16107 depth_to_tx_wh(bw, bh, depth, fctx),
16108 (bw, bh),
16109 fctx,
16110 );
16111 if depth != 0 || lossless(fctx) {
16112 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
16113 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
16114 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
16115 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
16116 // both interleave in every real stream.
16117 hit!(TX_DEPTH_HITS);
16118 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16119 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
16120 // predicted -- depth 1 fires FIRST in every attempt that splits at
16121 // all, so a depth-2-only lift could never be gated. The r1 mismatch
16122 // was never the rect unit: it was the neighbour MODE the strip reads
16123 // (see `modes_above_left_mi`).
16124 let which = if depth == 1 {
16125 &RECT4_SPLIT_DEPTH1_HITS
16126 } else {
16127 &RECT4_SPLIT_DEPTH2_HITS
16128 };
16129 hit_do! { which.with(|c| c.set(c.get() + 1)); }
16130 let modes = RectStripModes {
16131 skip,
16132 mode,
16133 angle_delta_y,
16134 uv_predict_mode,
16135 angle_delta_uv,
16136 alpha,
16137 filter_intra,
16138 smooth_neighbor,
16139 smooth_neighbor_uv,
16140 palette_y: palette_y_buf.clone(),
16141 palette_uv: palette_uv_bufs.clone(),
16142 };
16143 if palette_y.is_some() || palette_uv.is_some() {
16144 hit!(PALETTE_SPLIT_TX_HITS);
16145 }
16146 decode_rect_split(
16147 dec,
16148 cdfs,
16149 neighbours,
16150 (mi_r, mi_c),
16151 bw,
16152 bh,
16153 tx_w,
16154 tx_h,
16155 &modes,
16156 y,
16157 u,
16158 v,
16159 base_q_idx,
16160 false,
16161 fctx,
16162 )?;
16163 record_strip_palette(
16164 neighbours,
16165 pal_at,
16166 bw,
16167 bh,
16168 pal_y_size,
16169 pal_y_colors,
16170 pal_uv_size,
16171 pal_uv_colors,
16172 );
16173 if bw > bh {
16174 hit!(RECT4_32_HORZ_HITS);
16175 } else {
16176 hit!(RECT4_32_VERT_HITS);
16177 }
16178 if !skip {
16179 hit!(RECT4_COEFF_HITS);
16180 }
16181 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16182 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16183 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16184 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16185 // transform size in both TXFM_CONTEXT bands. Without it the next block
16186 // reads the row's stale value.
16187 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16188 return Ok((mode, uv_predict_mode));
16189 }
16190 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16191 // that is 8 px tall, so each strip stamps every cell it touches and the
16192 // LAST strip wins -- which is the right answer for the block below/right
16193 // of the 32x32, the only reader outside it. Written after this strip's
16194 // own context read above, never before.
16195 for cell in 0..bw.div_ceil(SUB) {
16196 neighbours.above_mode[c + cell] = mode;
16197 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16198 neighbours.above_side[c + cell] = bw;
16199 }
16200 for cell in 0..bh.div_ceil(SUB) {
16201 neighbours.left_mode[r + cell] = mode;
16202 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16203 neighbours.left_side[r + cell] = bh;
16204 }
16205 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16206 // [`decode_leaf_rect`] does (the split arm above records these through
16207 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16208 // `sub8_mode_row` holding the previous block, and the next 32x32's
16209 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16210 // fixture).
16211 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16212 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16213 let (px, py) = (mi_c * MI, mi_r * MI);
16214 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16215 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16216 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16217 // lane-av1-444: the strip's chroma shape follows the subsampling.
16218 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16219 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16220 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16221 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16222 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16223 // and 1/1 only -- so the table is exhaustive.
16224 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16225 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16226 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16227 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16228 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16229 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16230 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
16231 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
16232 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
16233 // [`decode_rect_split`]'s chroma table use.
16234 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
16235 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
16236 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
16237 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
16238 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
16239 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
16240 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
16241 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
16242 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
16243 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
16244 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
16245 // instead of refusing; no coefficient-table row is added, because
16246 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
16247 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
16248 // 4:2:2-only.
16249 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
16250 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
16251 // lane-av1-422p: the units' own set/scan -- the whole-rect read
16252 // below never sees this row, the `chroma422_rect32` arm chunks
16253 // first. Anything else is still a named-lane gap.
16254 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
16255 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
16256 };
16257 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
16258 let (luma_levels, u_levels, v_levels) = if skip {
16259 (
16260 vec![0i32; bw * bh],
16261 vec![0i32; chroma_w * chroma_h],
16262 vec![0i32; chroma_w * chroma_h],
16263 )
16264 } else if chroma422_rect32 {
16265 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
16266 // plane-major (every U unit, then every V) -- the walk the pinned
16267 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
16268 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
16269 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
16270 // Luma is the same single TX_8X32 rect the general arm reads.
16271 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16272 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16273 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16274 dec,
16275 &mut luma_coding,
16276 luma_scan,
16277 bw,
16278 bh,
16279 0,
16280 dc_sign_ctx(around[0].2),
16281 TxType::DctDct,
16282 0,
16283 )?;
16284 hit!(RECT4_COEFF_HITS);
16285 let luma_residual = dequant_and_inverse_typed_wh(
16286 &luma_levels,
16287 bw,
16288 bh,
16289 crate::decode::bit_depth(fctx),
16290 block_q_idx(fctx),
16291 plane_q_delta(0, fctx).0,
16292 plane_q_delta(0, fctx).1,
16293 luma_tx_type,
16294 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16295 );
16296 if let Some(b) = &palette_y_buf {
16297 set_palette_pred(b.clone(), fctx);
16298 }
16299 push_intra_rect(
16300 0,
16301 px,
16302 py,
16303 bw,
16304 bh,
16305 mode,
16306 angle_delta_y,
16307 reach,
16308 &luma_residual,
16309 None,
16310 filter_intra,
16311 smooth_neighbor,
16312 fctx,
16313 );
16314 // CfL parameters are computed ONCE per block over the strip's luma
16315 // (`are_parameters_computed`) and shared by all four units, as in
16316 // every other chunk arm.
16317 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16318 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
16319 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16320 for unit_row in 0..4usize {
16321 let unit_mi = (mi_r + unit_row * 2, mi_c);
16322 let unit_reach = tu_reach_rect(
16323 bw,
16324 bh,
16325 0,
16326 unit_row * 8,
16327 8,
16328 8,
16329 reach,
16330 px,
16331 py,
16332 y.width,
16333 y.height,
16334 fctx,
16335 );
16336 if let Some((ub, vb)) = &palette_uv_bufs {
16337 let pbuf = if plane == 1 { ub } else { vb };
16338 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16339 }
16340 // Each unit is read and recorded IMMEDIATELY: unit row 0's
16341 // `txb_skip_ctx` still sees the real above/left neighbour
16342 // states, a lower unit sees this block's own upper unit's
16343 // (libaom's per-unit `set_entropy_context`), and the lower
16344 // unit predicts off the upper one's reconstructed samples.
16345 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
16346 let unit_grid = read_rect_chroma_unit(
16347 dec,
16348 cdfs,
16349 TxbSet::ChromaRect8x4,
16350 &SCAN_4X8,
16351 4,
16352 8,
16353 plane,
16354 chroma_around[plane],
16355 uv_predict_mode,
16356 angle_delta_uv,
16357 unit_reach,
16358 buf,
16359 cpx,
16360 cpy + unit_row * 8,
16361 base_q_idx,
16362 // `get_txb_ctx_general`'s chroma branch
16363 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
16364 // here, `num_pels_log2_lookup[255]` = 255 (the +255
16365 // byte of the decodetxb copy at 0xc0de70,
16366 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
16367 // ctx_offset is 10 -- the port's offset-7-first
16368 // `txb_skip_chroma_8` stores the offset-10 rows at
16369 // rows 3..6, hence +3.
16370 Some(3),
16371 alpha
16372 .zip(ac)
16373 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16374 smooth_neighbor_uv,
16375 fctx,
16376 )?;
16377 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
16378 unit_grids.push((unit_mi, plane, unit_grid));
16379 }
16380 }
16381 // The whole-block stamp rewrites the chroma cells ONE state wide,
16382 // which would erase the unit boundary the next block reads (class
16383 // `override-slot-on-one-arm`), so it carries zero chroma grids and
16384 // the per-unit writes replay after it. Its luma cells and side
16385 // spans are this arm's own bookkeeping.
16386 let zero_chroma = vec![0i32; chroma_w * chroma_h];
16387 neighbours.record_mi_rect(
16388 (mi_r, mi_c),
16389 bw,
16390 bh,
16391 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
16392 );
16393 for (unit_mi, plane, grid) in &unit_grids {
16394 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
16395 }
16396 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16397 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16398 record_strip_palette(
16399 neighbours,
16400 pal_at,
16401 bw,
16402 bh,
16403 pal_y_size,
16404 pal_y_colors,
16405 pal_uv_size,
16406 pal_uv_colors,
16407 );
16408 if bw > bh {
16409 hit!(RECT4_32_HORZ_HITS);
16410 } else {
16411 hit!(RECT4_32_VERT_HITS);
16412 }
16413 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16414 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16415 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16416 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16417 // transform size in both TXFM_CONTEXT bands. Without it the next block
16418 // reads the row's stale value.
16419 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16420 return Ok((mode, uv_predict_mode));
16421 } else {
16422 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16423 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16424 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16425 dec,
16426 &mut luma_coding,
16427 luma_scan,
16428 bw,
16429 bh,
16430 0,
16431 dc_sign_ctx(around[0].2),
16432 TxType::DctDct,
16433 0,
16434 )?;
16435 let mut planes = Vec::with_capacity(2);
16436 for plane in 1..3 {
16437 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
16438 // stands only while it is a member of this tx size's set; a
16439 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
16440 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
16441 // to DCT_DCT there, and ADST is undefined at widths above 16.
16442 let default_tx = if chroma_w.max(chroma_h) >= 32 {
16443 TxType::DctDct
16444 } else {
16445 default_intra_tx_type(uv_predict_mode as u8)
16446 };
16447 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
16448 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
16449 let (levels, tx_type) = read_chroma_coeffs_rect(
16450 dec,
16451 &mut coding,
16452 chroma_scan,
16453 chroma_w,
16454 chroma_h,
16455 skip_ctx,
16456 dc_sign_ctx(around[plane].2),
16457 default_tx,
16458 fctx,
16459 plane,
16460 )?;
16461 planes.push((levels, tx_type));
16462 }
16463 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
16464 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
16465 hit!(RECT4_COEFF_HITS);
16466 let luma_residual = dequant_and_inverse_typed_wh(
16467 &luma_levels,
16468 bw,
16469 bh,
16470 crate::decode::bit_depth(fctx),
16471 block_q_idx(fctx),
16472 plane_q_delta(0, fctx).0,
16473 plane_q_delta(0, fctx).1,
16474 luma_tx_type,
16475 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16476 );
16477 if let Some(b) = &palette_y_buf {
16478 set_palette_pred(b.clone(), fctx);
16479 }
16480 push_intra_rect(
16481 0,
16482 px,
16483 py,
16484 bw,
16485 bh,
16486 mode,
16487 angle_delta_y,
16488 reach,
16489 &luma_residual,
16490 None,
16491 filter_intra,
16492 smooth_neighbor,
16493 fctx,
16494 );
16495 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16496 for (plane, _buf, levels, tx_type) in [
16497 (1usize, &mut *u, &u_levels, u_tx_type),
16498 (2, &mut *v, &v_levels, v_tx_type),
16499 ] {
16500 let residual = dequant_and_inverse_typed_wh(
16501 levels,
16502 chroma_w,
16503 chroma_h,
16504 crate::decode::bit_depth(fctx),
16505 block_q_idx(fctx),
16506 plane_q_delta(plane, fctx).0,
16507 plane_q_delta(plane, fctx).1,
16508 tx_type,
16509 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
16510 );
16511 if let Some((ub, vb)) = &palette_uv_bufs {
16512 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
16513 }
16514 push_intra_rect(
16515 plane,
16516 cpx,
16517 cpy,
16518 chroma_w,
16519 chroma_h,
16520 uv_predict_mode,
16521 angle_delta_uv,
16522 reach,
16523 &residual,
16524 alpha
16525 .zip(ac)
16526 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16527 None,
16528 smooth_neighbor_uv,
16529 fctx,
16530 );
16531 }
16532 neighbours.record_mi_rect(
16533 (mi_r, mi_c),
16534 bw,
16535 bh,
16536 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16537 );
16538 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16539 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16540 record_strip_palette(
16541 neighbours,
16542 pal_at,
16543 bw,
16544 bh,
16545 pal_y_size,
16546 pal_y_colors,
16547 pal_uv_size,
16548 pal_uv_colors,
16549 );
16550 if bw > bh {
16551 hit!(RECT4_32_HORZ_HITS);
16552 } else {
16553 hit!(RECT4_32_VERT_HITS);
16554 }
16555 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16556 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16557 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16558 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16559 // transform size in both TXFM_CONTEXT bands. Without it the next block
16560 // reads the row's stale value.
16561 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16562 return Ok((mode, uv_predict_mode));
16563 };
16564 if let Some(b) = &palette_y_buf {
16565 set_palette_pred(b.clone(), fctx);
16566 }
16567 push_intra_rect(
16568 0,
16569 px,
16570 py,
16571 bw,
16572 bh,
16573 mode,
16574 angle_delta_y,
16575 reach,
16576 &luma_levels,
16577 None,
16578 filter_intra,
16579 smooth_neighbor,
16580 fctx,
16581 );
16582 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16583 if chroma422_rect32 {
16584 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
16585 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
16586 // arm walks the same four TX_4X8 units per plane -- the lower unit
16587 // predicts off the upper one's predicted samples. No coefficients
16588 // are coded; the tail's whole-block zero stamp below is the state
16589 // libaom's `set_entropy_context` leaves.
16590 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16591 for unit_row in 0..4usize {
16592 let unit_reach = tu_reach_rect(
16593 bw,
16594 bh,
16595 0,
16596 unit_row * 8,
16597 8,
16598 8,
16599 reach,
16600 px,
16601 py,
16602 y.width,
16603 y.height,
16604 fctx,
16605 );
16606 if let Some((ub, vb)) = &palette_uv_bufs {
16607 let pbuf = if plane == 1 { ub } else { vb };
16608 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16609 }
16610 push_intra_rect(
16611 plane,
16612 cpx,
16613 cpy + unit_row * 8,
16614 4,
16615 8,
16616 uv_predict_mode,
16617 angle_delta_uv,
16618 unit_reach,
16619 &ZERO_RESIDUAL[..4 * 8],
16620 alpha
16621 .zip(ac)
16622 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16623 None,
16624 smooth_neighbor_uv,
16625 fctx,
16626 );
16627 }
16628 }
16629 } else {
16630 if let Some((ub, _)) = &palette_uv_bufs {
16631 set_palette_pred(ub.clone(), fctx);
16632 }
16633 push_intra_rect(
16634 1,
16635 cpx,
16636 cpy,
16637 chroma_w,
16638 chroma_h,
16639 uv_predict_mode,
16640 angle_delta_uv,
16641 reach,
16642 &u_levels,
16643 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16644 None,
16645 smooth_neighbor_uv,
16646 fctx,
16647 );
16648 if let Some((_, vb)) = &palette_uv_bufs {
16649 set_palette_pred(vb.clone(), fctx);
16650 }
16651 push_intra_rect(
16652 2,
16653 cpx,
16654 cpy,
16655 chroma_w,
16656 chroma_h,
16657 uv_predict_mode,
16658 angle_delta_uv,
16659 reach,
16660 &v_levels,
16661 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16662 None,
16663 smooth_neighbor_uv,
16664 fctx,
16665 );
16666 }
16667 neighbours.record_mi_rect(
16668 (mi_r, mi_c),
16669 bw,
16670 bh,
16671 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16672 );
16673 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16674 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16675 record_strip_palette(
16676 neighbours,
16677 pal_at,
16678 bw,
16679 bh,
16680 pal_y_size,
16681 pal_y_colors,
16682 pal_uv_size,
16683 pal_uv_colors,
16684 );
16685 if bw > bh {
16686 hit!(RECT4_32_HORZ_HITS);
16687 } else {
16688 hit!(RECT4_32_VERT_HITS);
16689 }
16690 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16691 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16692 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16693 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16694 // transform size in both TXFM_CONTEXT bands. Without it the next block
16695 // reads the row's stale value.
16696 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16697 Ok((mode, uv_predict_mode))
16698}
16699
16700/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
16701/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
16702/// down, and the first shape here whose luma block is a single mi row (or
16703/// column).
16704///
16705/// What is new at this size is CHROMA. `is_chroma_reference`
16706/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
16707/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
16708/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
16709/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
16710/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
16711/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
16712/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
16713///
16714/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
16715/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
16716/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
16717/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
16718/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
16719/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
16720/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
16721/// shape's own CDF row.
16722///
16723/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
16724/// refuses by name rather than guess-decode.
16725#[allow(clippy::too_many_arguments)]
16726fn decode_rect4_16(
16727 dec: &mut SymbolDecoder,
16728 cdfs: &mut Cdfs,
16729 neighbours: &mut Neighbours,
16730 at16: (usize, usize),
16731 horz: bool,
16732 y: &mut PlaneBuf<'static>,
16733 u: &mut PlaneBuf<'static>,
16734 v: &mut PlaneBuf<'static>,
16735 enable_filter_intra: bool,
16736 allow_screen_content_tools: bool,
16737 base_q_idx: u8,
16738 tx_select: bool,
16739 reduced_tx_set: bool,
16740 fctx: &crate::decode::FrameCtx,
16741) -> Result<()> {
16742 let (r, c) = at16;
16743 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
16744 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
16745 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
16746 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
16747 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
16748 let mut prev: Option<((usize, usize), usize)> = None;
16749 let mut last_mode = DC_PRED;
16750 let mut last_uv_mode = DC_PRED;
16751 for i in 0..4usize {
16752 let lmi = if horz {
16753 (mi_row0 + i, mi_col0)
16754 } else {
16755 (mi_row0, mi_col0 + i)
16756 };
16757 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
16758 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
16759 // already >= 4x4) -- there is no 4:2:0 pair to close.
16760 // lane-av1-422o: the parity rule is per axis, straight out of
16761 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
16762 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
16763 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
16764 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
16765 // every ss_x == 1 format -- the ODD strip closes the pair and reads
16766 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
16767 // even mi_col, so `i % 2 == 1` is that clause.)
16768 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
16769 let (mode, uv, _tx) = decode_rect4_16_strip(
16770 dec,
16771 cdfs,
16772 neighbours,
16773 lmi,
16774 horz,
16775 has_chroma,
16776 prev,
16777 y,
16778 u,
16779 v,
16780 enable_filter_intra,
16781 allow_screen_content_tools,
16782 base_q_idx,
16783 tx_select,
16784 reduced_tx_set,
16785 fctx,
16786 )?;
16787 if let Some(m) = uv {
16788 last_uv_mode = m;
16789 }
16790 last_mode = mode;
16791 prev = Some((lmi, mode));
16792 }
16793 // The coarse 16-px cell holds one entry for the whole 16x16: the last
16794 // strip is what a block below (right) sees through it, the mi-exact maps
16795 // above answering everything finer.
16796 neighbours.above_mode[c] = last_mode;
16797 neighbours.left_mode[r] = last_mode;
16798 neighbours.above_uv_mode[c] = last_uv_mode;
16799 neighbours.left_uv_mode[r] = last_uv_mode;
16800 neighbours.above_side[c] = bw;
16801 neighbours.left_side[r] = bh;
16802 Ok(())
16803}
16804
16805/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
16806/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
16807/// block path can decode a SINGLE intra strip of a partition whose other
16808/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
16809/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
16810/// every strip publishes its own mi-exact mode). Returns
16811/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
16812/// Intrabc reconstruction for a rect strip that OWNS its chroma
16813/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
16814/// pair goes through [`decode_rect4_16_intrabc`].
16815///
16816/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
16817/// (predict once, then one residual per transform unit on the INTER sets,
16818/// chroma inherits luma's `tx_type`), written against the helpers that exist
16819/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
16820/// merge with lane-av1-intrabc should keep one of the two bodies; the call
16821/// shape is the same.
16822#[allow(clippy::too_many_arguments)]
16823fn decode_intrabc_owned_rect(
16824 dec: &mut SymbolDecoder,
16825 cdfs: &mut Cdfs,
16826 neighbours: &mut Neighbours,
16827 (mi_r, mi_c): (usize, usize),
16828 (bw, bh): (usize, usize),
16829 skip: bool,
16830 (dv_row, dv_col): (i32, i32),
16831 y: &mut PlaneBuf<'static>,
16832 u: &mut PlaneBuf<'static>,
16833 v: &mut PlaneBuf<'static>,
16834 base_q_idx: u8,
16835 tx_select: bool,
16836 reduced_tx_set: bool,
16837 fctx: &crate::decode::FrameCtx,
16838) -> Result<()> {
16839 let _ = base_q_idx;
16840 let (px, py) = (mi_c * MI, mi_r * MI);
16841 // lane-av1chromahalvings r5: libaom-WRONG at 4:4:4 -- `av1_get_max_uv_txsize`
16842 // is `ss_size_lookup[bsize]` and `get_vartx_max_txsize` (blockd.h:1447) reads
16843 // that plane block as `max_txsize_rect_lookup[plane_bsize]`, so chroma extent
16844 // == luma extent at ss (0,0) -- and the chroma MV origins below are the
16845 // prediction half of the same defect. MEASURED on the 4:4:4 LOSSY witness
16846 // fixtures/r512.obu, chroma-only, luma byte-exact on both inter frames.
16847 // BLOCKED, not missing: with the ss-derived extent the decode REFUSES --
16848 // "a rectangular inter chroma transform unit whose shape has no coefficient
16849 // table set here" -- because a 4:4:4 32x64 chroma plane block needs a
16850 // `TxbSet` this crate lacks. The fix is a new coefficient set, not a swap.
16851 // Left as the halving deliberately: turning a decoding stream into a
16852 // refusal is a behaviour change with its own decision. See
16853 // lanes/av1chromahalvings.report.md r5.
16854 if crate::envflags::env_flag!("EC_HALVSWEEP") {
16855 eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
16856 }
16857 let (cw, ch) = (bw / 2, bh / 2);
16858 let side = bw.max(bh);
16859 let cside = cw.max(ch);
16860 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16861 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
16862 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16863 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
16864 // false; the real bit is the caller's `tx_select`. Restored before return.
16865 fctx.tx_select_inter.with(|c| c.set(tx_select));
16866 let restore = ReducedTxRestore {
16867 fctx,
16868 saved_reduced,
16869 saved_tx,
16870 };
16871
16872 flush_recon(fctx, y, u, v);
16873 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
16874 let pred_u = predict_intrabc_window(
16875 u,
16876 px / 2,
16877 py / 2,
16878 cw,
16879 ch,
16880 dv_col,
16881 dv_row,
16882 false,
16883 cside,
16884 fctx,
16885 );
16886 let pred_v = predict_intrabc_window(
16887 v,
16888 px / 2,
16889 py / 2,
16890 cw,
16891 ch,
16892 dv_col,
16893 dv_row,
16894 false,
16895 cside,
16896 fctx,
16897 );
16898
16899 let mi_cols = 2 * y.true_width.div_ceil(8);
16900 let mi_rows = 2 * y.true_height.div_ceil(8);
16901 let leaves = read_block_tx_size_rect(
16902 dec,
16903 cdfs,
16904 neighbours,
16905 (mi_r, mi_c),
16906 (bw, bh),
16907 (mi_cols, mi_rows),
16908 skip,
16909 fctx,
16910 )?;
16911 let mut luma_tx_type = TxType::DctDct;
16912 let luma_grid;
16913 let u_grid;
16914 let v_grid;
16915 if skip {
16916 // `reconstruct_mc_rect` indexes the residual at the square stride.
16917 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
16918 push_mc_rect(
16919 0,
16920 px,
16921 py,
16922 side,
16923 bw,
16924 bh,
16925 Pred::Inline(&pred_y, side),
16926 &ZERO_RESIDUAL[..side * bh],
16927 fctx,
16928 );
16929 push_mc_rect(
16930 1,
16931 px / 2,
16932 py / 2,
16933 cside,
16934 cw,
16935 ch,
16936 Pred::Inline(&pred_u, cside),
16937 &ZERO_RESIDUAL[..cside * ch],
16938 fctx,
16939 );
16940 push_mc_rect(
16941 2,
16942 px / 2,
16943 py / 2,
16944 cside,
16945 cw,
16946 ch,
16947 Pred::Inline(&pred_v, cside),
16948 &ZERO_RESIDUAL[..cside * ch],
16949 fctx,
16950 );
16951 if let Some(ls) = leaves.as_ref() {
16952 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
16953 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
16954 // whole entropy-band footprint. The non-skip arm below writes
16955 // those bands per transform unit and the tail's
16956 // `record_split_luma_rect_mi` writes chroma only, so without
16957 // this walk a skipped strip whose `leaves` resolved (every
16958 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
16959 // returns the 4x4 grid before it looks at `skip`) leaked the
16960 // PREVIOUS occupant's luma bands into the next block's
16961 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
16962 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
16963 // stream left a stale 7 in left[48] and mi(48,68)'s first
16964 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
16965 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
16966 for &(row, col, tw, th) in ls {
16967 neighbours.record_mi_luma_rect(
16968 (mi_r + row, mi_c + col),
16969 tw,
16970 th,
16971 &ZERO_RESIDUAL[..tw * th],
16972 );
16973 }
16974 }
16975 luma_grid = Grid::Zero(side * side);
16976 u_grid = Grid::Zero(cside * cside);
16977 v_grid = Grid::Zero(cside * cside);
16978 } else if let Some(ls) = leaves.as_ref() {
16979 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
16980 let tu_mi = (mi_r + row, mi_c + col);
16981 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16982 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
16983 let (g, tt) = if tw == th {
16984 read_inter_plane(
16985 dec,
16986 cdfs,
16987 inter_txbset_for(tw, reduced_tx_set),
16988 &default_scan(tw.min(32)),
16989 0,
16990 neighbours.around_mi(tu_mi, tw)[0],
16991 0,
16992 y,
16993 tu_px,
16994 tu_py,
16995 tw,
16996 base_q_idx,
16997 tu_pred,
16998 None,
16999 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17000 fctx,
17001 )?
17002 } else {
17003 read_inter_plane_rect(
17004 dec,
17005 cdfs,
17006 rect_inter_luma_set(tw, th, fctx)?,
17007 (tw, th),
17008 side,
17009 0,
17010 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17011 0,
17012 y,
17013 tu_px,
17014 tu_py,
17015 tu_pred,
17016 None,
17017 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17018 fctx,
17019 )?
17020 };
17021 if idx == 0 {
17022 luma_tx_type = tt;
17023 }
17024 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17025 if tw != th {
17026 neighbours.fill_lf_grid_leaf_luma(
17027 (tu_mi.0, tu_mi.1),
17028 tw / MI,
17029 th / MI,
17030 tw as u8,
17031 th as u8,
17032 );
17033 }
17034 }
17035 luma_grid = Grid::Zero(side * side);
17036 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17037 let (ug, _) = read_inter_plane_rect(
17038 dec,
17039 cdfs,
17040 rect_inter_chroma_set(cw, ch)?,
17041 (cw, ch),
17042 cside,
17043 1,
17044 around[1],
17045 0,
17046 u,
17047 px / 2,
17048 py / 2,
17049 Pred::Inline(&pred_u, cside),
17050 Some(luma_tx_type),
17051 None,
17052 fctx,
17053 )?;
17054 let (vg, _) = read_inter_plane_rect(
17055 dec,
17056 cdfs,
17057 rect_inter_chroma_set(cw, ch)?,
17058 (cw, ch),
17059 cside,
17060 2,
17061 around[2],
17062 0,
17063 v,
17064 px / 2,
17065 py / 2,
17066 Pred::Inline(&pred_v, cside),
17067 Some(luma_tx_type),
17068 None,
17069 fctx,
17070 )?;
17071 u_grid = ug;
17072 v_grid = vg;
17073 } else {
17074 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17075 let (g, tt) = read_inter_plane_rect(
17076 dec,
17077 cdfs,
17078 rect_inter_luma_set(bw, bh, fctx)?,
17079 (bw, bh),
17080 side,
17081 0,
17082 around[0],
17083 0,
17084 y,
17085 px,
17086 py,
17087 Pred::Inline(&pred_y, side),
17088 None,
17089 None,
17090 fctx,
17091 )?;
17092 luma_tx_type = tt;
17093 luma_grid = g;
17094 let (ug, _) = read_inter_plane_rect(
17095 dec,
17096 cdfs,
17097 rect_inter_chroma_set(cw, ch)?,
17098 (cw, ch),
17099 cside,
17100 1,
17101 around[1],
17102 0,
17103 u,
17104 px / 2,
17105 py / 2,
17106 Pred::Inline(&pred_u, cside),
17107 Some(luma_tx_type),
17108 None,
17109 fctx,
17110 )?;
17111 let (vg, _) = read_inter_plane_rect(
17112 dec,
17113 cdfs,
17114 rect_inter_chroma_set(cw, ch)?,
17115 (cw, ch),
17116 cside,
17117 2,
17118 around[2],
17119 0,
17120 v,
17121 px / 2,
17122 py / 2,
17123 Pred::Inline(&pred_v, cside),
17124 Some(luma_tx_type),
17125 None,
17126 fctx,
17127 )?;
17128 u_grid = ug;
17129 v_grid = vg;
17130 }
17131 drop(restore);
17132 if leaves.is_some() {
17133 neighbours.record_split_luma_rect_mi(
17134 (mi_r, mi_c),
17135 bw,
17136 bh,
17137 DC_PRED,
17138 DC_PRED,
17139 [&u_grid, &v_grid],
17140 );
17141 } else {
17142 neighbours.record_rect_mi(
17143 (mi_r, mi_c),
17144 bw,
17145 bh,
17146 DC_PRED,
17147 DC_PRED,
17148 &[&luma_grid, &u_grid, &v_grid],
17149 );
17150 }
17151 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17152 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17153 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17154 neighbours.fill_lf_grid_rect(
17155 (mi_r, mi_c),
17156 bw / MI,
17157 bh / MI,
17158 bw.min(64) as u8,
17159 bh.min(64) as u8,
17160 0,
17161 fctx,
17162 );
17163 record_intrabc_mi_rect(
17164 mi_r,
17165 mi_c,
17166 bw / MI,
17167 bh / MI,
17168 Some((dv_row, dv_col)),
17169 neighbours,
17170 fctx,
17171 );
17172 let _ = luma_tx_type;
17173 Ok(())
17174}
17175
17176fn predict_intrabc_window(
17177 plane: &PlaneBuf<'_>,
17178 px: usize,
17179 py: usize,
17180 w: usize,
17181 h: usize,
17182 dv_col: i32,
17183 dv_row: i32,
17184 luma: bool,
17185 stride: usize,
17186 fctx: &crate::decode::FrameCtx,
17187) -> Vec<u16> {
17188 let mut dense = vec![0u16; w * h];
17189 mc::predict_with_filter(
17190 &plane.data,
17191 plane.width,
17192 plane.true_width,
17193 plane.true_height,
17194 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
17195 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
17196 w,
17197 h,
17198 mc::InterpFilterKind::Bilinear,
17199 &mut dense,
17200 fctx,
17201 );
17202 let mut laid = vec![0u16; stride * stride];
17203 for row in 0..h {
17204 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
17205 }
17206 laid
17207}
17208
17209struct ReducedTxRestore<'a> {
17210 fctx: &'a crate::decode::FrameCtx,
17211 saved_reduced: bool,
17212 saved_tx: bool,
17213}
17214impl Drop for ReducedTxRestore<'_> {
17215 fn drop(&mut self) {
17216 self.fctx
17217 .reduced_tx_set_inter
17218 .with(|c| c.set(self.saved_reduced));
17219 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
17220 }
17221}
17222
17223/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
17224///
17225/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
17226/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
17227/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
17228/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
17229/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
17230/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
17231/// strip's own footprint, copied from this strip's DV. The block is
17232/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
17233/// the luma unit's coded `tx_type`.
17234///
17235/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
17236/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
17237/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
17238/// would code chroma on every strip.
17239#[allow(clippy::too_many_arguments)]
17240fn decode_rect4_16_intrabc(
17241 dec: &mut SymbolDecoder,
17242 cdfs: &mut Cdfs,
17243 neighbours: &mut Neighbours,
17244 lmi: (usize, usize),
17245 horz: bool,
17246 has_chroma: bool,
17247 skip: bool,
17248 (dv_row, dv_col): (i32, i32),
17249 y: &mut PlaneBuf<'static>,
17250 u: &mut PlaneBuf<'static>,
17251 v: &mut PlaneBuf<'static>,
17252 base_q_idx: u8,
17253 tx_select: bool,
17254 reduced_tx_set: bool,
17255 fctx: &crate::decode::FrameCtx,
17256) -> Result<(usize, Option<usize>, (usize, usize))> {
17257 let _ = base_q_idx;
17258 hit!(RECT4_16_INTRABC_HITS);
17259 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17260 let (mi_w, mi_h) = (bw / MI, bh / MI);
17261 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17262 let side = bw.max(bh);
17263 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
17264 // publishes `reduced_tx_set` into it; set it here too so a caller that
17265 // passed the bit explicitly cannot disagree with the set we read.
17266 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17267 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17268 let restored = scopeguard_reduced(fctx, saved_reduced);
17269
17270 flush_recon(fctx, y, u, v);
17271 let mut pred_y_dense = vec![0u16; bw * bh];
17272 mc::predict_with_filter(
17273 &y.data,
17274 y.width,
17275 y.true_width,
17276 y.true_height,
17277 mv_to_q4(px, dv_col, 0),
17278 mv_to_q4(py, dv_row, 0),
17279 bw,
17280 bh,
17281 mc::InterpFilterKind::Bilinear,
17282 &mut pred_y_dense,
17283 fctx,
17284 );
17285 let mut pred_y = vec![0u16; side * side];
17286 for row in 0..bh {
17287 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
17288 }
17289
17290 // lane-av1444rect r2 (the class this lane named, second instance): the
17291 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
17292 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
17293 // unconditionally true -- the strip is its own chroma reference, there is
17294 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
17295 // (VERT_4) at the strip's own origin, with its coefficient context read
17296 // over that same extent. The old constants instead predicted and coded an
17297 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
17298 //
17299 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
17300 // --enable-palette=1 --cq-level=60 --min-partition-size=4
17301 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
17302 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
17303 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
17304 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
17305 // twin of the same recipe is byte-exact.
17306 //
17307 // 4:2:0 and 4:2:2 keep every constant below verbatim -- the arm is gated on
17308 // the full ss (0,0), not on a per-axis shift, so `pw / 2` and the literal
17309 // halving are untouched for both.
17310 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
17311 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
17312 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
17313 }
17314 let (pw, ph) = if own444 {
17315 (bw, bh)
17316 } else if horz {
17317 (16usize, 8usize)
17318 } else {
17319 (8, 16)
17320 };
17321 let (cw, ch) = if own444 { (bw, bh) } else { (pw / 2, ph / 2) };
17322 let pair_mi = if has_chroma {
17323 if own444 {
17324 lmi
17325 } else if horz {
17326 (lmi.0 - 1, lmi.1)
17327 } else {
17328 (lmi.0, lmi.1 - 1)
17329 }
17330 } else {
17331 lmi
17332 };
17333 let (cpx, cpy) = if has_chroma {
17334 if own444 {
17335 (px, py)
17336 } else {
17337 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
17338 }
17339 } else {
17340 (0, 0)
17341 };
17342 let cside = cw.max(ch);
17343 let (pred_u, pred_v) = if has_chroma {
17344 let mut ud = vec![0u16; cw * ch];
17345 mc::predict_with_filter(
17346 &u.data,
17347 u.width,
17348 u.true_width,
17349 u.true_height,
17350 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17351 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17352 cw,
17353 ch,
17354 mc::InterpFilterKind::Bilinear,
17355 &mut ud,
17356 fctx,
17357 );
17358 let mut us = vec![0u16; cside * cside];
17359 for row in 0..ch {
17360 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
17361 }
17362 let mut vd = vec![0u16; cw * ch];
17363 mc::predict_with_filter(
17364 &v.data,
17365 v.width,
17366 v.true_width,
17367 v.true_height,
17368 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17369 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17370 cw,
17371 ch,
17372 mc::InterpFilterKind::Bilinear,
17373 &mut vd,
17374 fctx,
17375 );
17376 let mut vs = vec![0u16; cside * cside];
17377 for row in 0..ch {
17378 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
17379 }
17380 (us, vs)
17381 } else {
17382 (Vec::new(), Vec::new())
17383 };
17384
17385 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
17386 // false for a key frame, so `read_block_tx_size_rect` would skip the
17387 // symbol; read it here against the parameter the intra path already uses.
17388 // A skipped intrabc block predicts the whole footprint once and codes
17389 // no residual (`decode_token_recon_block`'s inter branch). Lossless
17390 // still forces TX_4X4 when the block is coded.
17391 let leaves = if skip || (!lossless(fctx) && !tx_select) {
17392 None
17393 } else if lossless(fctx) {
17394 let mut leaves = Vec::new();
17395 for row in 0..bh / MI {
17396 for col in 0..bw / MI {
17397 leaves.push((row, col, 4usize, 4usize));
17398 }
17399 }
17400 Some(leaves)
17401 } else {
17402 let ctx = txfm_partition_ctx_rect(
17403 neighbours.above_txfm[lmi.1],
17404 neighbours.left_txfm[lmi.0],
17405 side,
17406 bw,
17407 bh,
17408 );
17409 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17410 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17411 let (rng, _) = dec.debug_state();
17412 eprintln!(
17413 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17414 lmi.0,
17415 lmi.1,
17416 u8::from(split)
17417 );
17418 }
17419 if !split {
17420 None
17421 } else {
17422 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
17423 let mi_cols = 2 * y.true_width.div_ceil(8);
17424 let mi_rows = 2 * y.true_height.div_ceil(8);
17425 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
17426 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
17427 let mut out = Vec::new();
17428 for row in (0..bh / MI).step_by(sub_h / MI) {
17429 for col in (0..bw / MI).step_by(sub_w / MI) {
17430 read_var_tx_size(
17431 dec,
17432 cdfs,
17433 neighbours,
17434 lmi,
17435 side,
17436 (max_w_mi, max_h_mi),
17437 (sub_w, sub_h),
17438 1,
17439 row,
17440 col,
17441 &mut out,
17442 );
17443 }
17444 }
17445 Some(out)
17446 }
17447 };
17448 let (tx_w, tx_h) = leaves
17449 .as_ref()
17450 .and_then(|ls| ls.first())
17451 .map_or((bw, bh), |l| (l.2, l.3));
17452
17453 let mut luma_tx_type = TxType::DctDct;
17454 let luma_grid;
17455 let mut u_grid = Grid::Zero(cw * ch);
17456 let mut v_grid = Grid::Zero(cw * ch);
17457 let chroma_stamped_per_unit;
17458
17459 if skip {
17460 push_mc_rect(
17461 0,
17462 px,
17463 py,
17464 side,
17465 bw,
17466 bh,
17467 Pred::Inline(&pred_y, side),
17468 &ZERO_RESIDUAL[..side * bh],
17469 fctx,
17470 );
17471 luma_grid = Grid::Zero(bw * bh);
17472 if has_chroma {
17473 push_mc_rect(
17474 1,
17475 cpx,
17476 cpy,
17477 cside,
17478 cw,
17479 ch,
17480 Pred::Inline(&pred_u, cside),
17481 &ZERO_RESIDUAL[..cside * ch],
17482 fctx,
17483 );
17484 push_mc_rect(
17485 2,
17486 cpx,
17487 cpy,
17488 cside,
17489 cw,
17490 ch,
17491 Pred::Inline(&pred_v, cside),
17492 &ZERO_RESIDUAL[..cside * ch],
17493 fctx,
17494 );
17495 }
17496 chroma_stamped_per_unit = false;
17497 } else if let Some(ls) = leaves.as_ref() {
17498 if lossless(fctx) {
17499 for &(row, col, _tw, _th) in ls {
17500 let tu_mi = (lmi.0 + row, lmi.1 + col);
17501 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17502 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17503 let (g, _) = read_inter_plane(
17504 dec,
17505 cdfs,
17506 if reduced_tx_set {
17507 TxbSet::Luma4Inter
17508 } else {
17509 TxbSet::Luma4InterSet1
17510 },
17511 &default_scan(4),
17512 0,
17513 neighbours.around_mi(tu_mi, 4)[0],
17514 0,
17515 y,
17516 tu_px,
17517 tu_py,
17518 4,
17519 base_q_idx,
17520 tu_pred,
17521 None,
17522 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
17523 fctx,
17524 )?;
17525 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
17526 }
17527 } else {
17528 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17529 let tu_mi = (lmi.0 + row, lmi.1 + col);
17530 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17531 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17532 let (g, tt) = if tw == th {
17533 read_inter_plane(
17534 dec,
17535 cdfs,
17536 inter_txbset_for(tw, reduced_tx_set),
17537 &default_scan(tw.min(32)),
17538 0,
17539 neighbours.around_mi(tu_mi, tw)[0],
17540 0,
17541 y,
17542 tu_px,
17543 tu_py,
17544 tw,
17545 base_q_idx,
17546 tu_pred,
17547 None,
17548 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17549 fctx,
17550 )?
17551 } else {
17552 read_inter_plane_rect(
17553 dec,
17554 cdfs,
17555 rect_inter_luma_set(tw, th, fctx)?,
17556 (tw, th),
17557 side,
17558 0,
17559 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17560 0,
17561 y,
17562 tu_px,
17563 tu_py,
17564 tu_pred,
17565 None,
17566 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17567 fctx,
17568 )?
17569 };
17570 if idx == 0 {
17571 luma_tx_type = tt;
17572 }
17573 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17574 }
17575 }
17576 luma_grid = Grid::Zero(bw * bh);
17577 chroma_stamped_per_unit = has_chroma && lossless(fctx);
17578 if has_chroma && lossless(fctx) {
17579 let (mut uo, mut vo) = (Vec::new(), Vec::new());
17580 read_inter_chroma_lossless(
17581 dec,
17582 cdfs,
17583 neighbours,
17584 u,
17585 v,
17586 Pred::Inline(&pred_u, cside),
17587 Pred::Inline(&pred_v, cside),
17588 pair_mi,
17589 (cpx, cpy),
17590 (0, 0),
17591 (cw, ch),
17592 (cw, ch),
17593 cside,
17594 0,
17595 base_q_idx,
17596 &mut uo,
17597 &mut vo,
17598 fctx,
17599 )?;
17600 u_grid = if uo.is_empty() {
17601 Grid::Zero(cw * ch)
17602 } else {
17603 Grid::Own(uo)
17604 };
17605 v_grid = if vo.is_empty() {
17606 Grid::Zero(cw * ch)
17607 } else {
17608 Grid::Own(vo)
17609 };
17610 } else if has_chroma {
17611 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17612 let (ug, _) = read_inter_plane_rect(
17613 dec,
17614 cdfs,
17615 rect_inter_chroma_set(cw, ch)?,
17616 (cw, ch),
17617 cside,
17618 1,
17619 around[1],
17620 0,
17621 u,
17622 cpx,
17623 cpy,
17624 Pred::Inline(&pred_u, cside),
17625 Some(luma_tx_type),
17626 None,
17627 fctx,
17628 )?;
17629 u_grid = ug;
17630 let (vg, _) = read_inter_plane_rect(
17631 dec,
17632 cdfs,
17633 rect_inter_chroma_set(cw, ch)?,
17634 (cw, ch),
17635 cside,
17636 2,
17637 around[2],
17638 0,
17639 v,
17640 cpx,
17641 cpy,
17642 Pred::Inline(&pred_v, cside),
17643 Some(luma_tx_type),
17644 None,
17645 fctx,
17646 )?;
17647 v_grid = vg;
17648 }
17649 } else {
17650 let around = neighbours.around_mi_rect(lmi, bw, bh);
17651 let (g, tt) = read_inter_plane_rect(
17652 dec,
17653 cdfs,
17654 rect_inter_luma_set(bw, bh, fctx)?,
17655 (bw, bh),
17656 side,
17657 0,
17658 around[0],
17659 0,
17660 y,
17661 px,
17662 py,
17663 Pred::Inline(&pred_y, side),
17664 None,
17665 None,
17666 fctx,
17667 )?;
17668 luma_tx_type = tt;
17669 luma_grid = g;
17670 chroma_stamped_per_unit = false;
17671 if has_chroma {
17672 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17673 let (ug, _) = read_inter_plane_rect(
17674 dec,
17675 cdfs,
17676 rect_inter_chroma_set(cw, ch)?,
17677 (cw, ch),
17678 cside,
17679 1,
17680 around[1],
17681 0,
17682 u,
17683 cpx,
17684 cpy,
17685 Pred::Inline(&pred_u, cside),
17686 Some(luma_tx_type),
17687 None,
17688 fctx,
17689 )?;
17690 u_grid = ug;
17691 let (vg, _) = read_inter_plane_rect(
17692 dec,
17693 cdfs,
17694 rect_inter_chroma_set(cw, ch)?,
17695 (cw, ch),
17696 cside,
17697 2,
17698 around[2],
17699 0,
17700 v,
17701 cpx,
17702 cpy,
17703 Pred::Inline(&pred_v, cside),
17704 Some(luma_tx_type),
17705 None,
17706 fctx,
17707 )?;
17708 v_grid = vg;
17709 }
17710 }
17711 drop(restored);
17712
17713 if leaves.is_none() {
17714 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
17715 }
17716 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
17717 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17718 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17719 for cell in 0..mi_w {
17720 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
17721 *slot = bw as u8;
17722 }
17723 }
17724 for cell in 0..mi_h {
17725 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
17726 *slot = bh as u8;
17727 }
17728 }
17729 let mut last_uv = None;
17730 if has_chroma {
17731 hit!(RECT4_16_CHROMA_HITS);
17732 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
17733 if !chroma_stamped_per_unit {
17734 let u_state = neighbour_state(&u_grid);
17735 let v_state = neighbour_state(&v_grid);
17736 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17737 let bound_h = round_up_even(neighbours.mi_rows);
17738 let bound_w = round_up_even(neighbours.mi_cols);
17739 for cell in 0..(ph / MI) {
17740 if pair_mi.0 + cell < bound_h
17741 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
17742 {
17743 slot[1] = u_state;
17744 slot[2] = v_state;
17745 }
17746 }
17747 for cell in 0..(pw / MI) {
17748 if pair_mi.1 + cell < bound_w
17749 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
17750 {
17751 slot[1] = u_state;
17752 slot[2] = v_state;
17753 }
17754 }
17755 }
17756 last_uv = Some(DC_PRED);
17757 }
17758 if horz {
17759 hit!(RECT4_16_HORZ_HITS);
17760 } else {
17761 hit!(RECT4_16_VERT_HITS);
17762 }
17763 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
17764 if leaves.is_none() {
17765 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
17766 // with `skip && is_inter`, or the unsplit unit). A split tree already
17767 // published per leaf inside `read_var_tx_size`.
17768 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
17769 }
17770 record_intrabc_mi_rect(
17771 lmi.0,
17772 lmi.1,
17773 mi_w,
17774 mi_h,
17775 Some((dv_row, dv_col)),
17776 neighbours,
17777 fctx,
17778 );
17779 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
17780}
17781
17782/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
17783/// including through `?`.
17784struct ReducedRestore<'a> {
17785 fctx: &'a crate::decode::FrameCtx,
17786 saved: bool,
17787}
17788impl Drop for ReducedRestore<'_> {
17789 fn drop(&mut self) {
17790 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
17791 }
17792}
17793fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
17794 ReducedRestore { fctx, saved }
17795}
17796
17797#[allow(clippy::too_many_arguments)]
17798fn decode_rect4_16_strip(
17799 dec: &mut SymbolDecoder,
17800 cdfs: &mut Cdfs,
17801 neighbours: &mut Neighbours,
17802 lmi: (usize, usize),
17803 horz: bool,
17804 has_chroma: bool,
17805 prev: Option<((usize, usize), usize)>,
17806 y: &mut PlaneBuf<'static>,
17807 u: &mut PlaneBuf<'static>,
17808 v: &mut PlaneBuf<'static>,
17809 enable_filter_intra: bool,
17810 allow_screen_content_tools: bool,
17811 base_q_idx: u8,
17812 tx_select: bool,
17813 reduced_tx_set: bool,
17814 fctx: &crate::decode::FrameCtx,
17815) -> Result<(usize, Option<usize>, (usize, usize))> {
17816 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
17817 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17818 let (mi_w, mi_h) = (bw / MI, bh / MI);
17819 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
17820 let mut last_uv_mode: Option<usize> = None;
17821 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
17822 // aliases all four strips onto one entry, so the mi-exact map wins and
17823 // the previous strip stands in on the split axis.
17824 let mut above_mode = neighbours.above_mode[c];
17825 let mut left_mode = neighbours.left_mode[r];
17826 if let Some(((pr, pc), pmode)) = prev {
17827 if pc == lmi.1 && lmi.0 == pr + mi_h {
17828 above_mode = pmode;
17829 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
17830 left_mode = pmode;
17831 }
17832 }
17833 let (above_mode, left_mode) =
17834 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
17835 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
17836 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
17837 // off CDF row 0 and every cache hit off an empty cache.
17838 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
17839 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
17840 let (
17841 skip,
17842 mode,
17843 angle_delta_y,
17844 uv_mode,
17845 angle_delta_uv,
17846 alpha,
17847 filter_intra,
17848 palette_y,
17849 palette_uv,
17850 intrabc,
17851 ) = read_intra_mode_rect(
17852 dec,
17853 cdfs,
17854 above_mode,
17855 left_mode,
17856 true,
17857 has_chroma,
17858 bw,
17859 bh,
17860 enable_filter_intra,
17861 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
17862 allow_screen_content_tools,
17863 Some((palette_ctx, &palette_cache)),
17864 &palette_uv_cache,
17865 lmi.0,
17866 lmi.1,
17867 fctx,
17868 )?;
17869 if let Some(dv) = intrabc {
17870 return decode_rect4_16_intrabc(
17871 dec,
17872 cdfs,
17873 neighbours,
17874 lmi,
17875 horz,
17876 has_chroma,
17877 skip,
17878 dv,
17879 y,
17880 u,
17881 v,
17882 base_q_idx,
17883 tx_select,
17884 reduced_tx_set,
17885 fctx,
17886 );
17887 }
17888 if palette_y.is_some() || palette_uv.is_some() {
17889 hit!(RECT4_PALETTE_HITS);
17890 }
17891 // The colour-index map through the base colours IS the prediction.
17892 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
17893 // chroma transform this closing strip codes.
17894 let palette_y_buf: Option<Vec<u16>> = palette_y
17895 .as_ref()
17896 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
17897 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
17898 (
17899 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
17900 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
17901 )
17902 });
17903 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
17904 if smooth_neighbor {
17905 hit!(SMOOTH_LUMA_HITS);
17906 }
17907 if filter_intra.is_some() {
17908 hit!(FILTER_INTRA_RECT_HITS);
17909 }
17910 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
17911 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
17912 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
17913 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
17914 // lane-av1mixloss: the lossless-segment early return
17915 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
17916 // lossless-segment strip codes no depth symbol here either (class
17917 // sweep of the sub8 leaf's fix).
17918 let depth = if tx_select && !lossless(fctx) {
17919 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
17920 // (`get_tx_size_context`, libaom `pred_common.h:342`).
17921 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
17922 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
17923 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17924 eprintln!(
17925 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
17926 lmi.0,
17927 lmi.1,
17928 dec.debug_state().0
17929 );
17930 }
17931 d
17932 } else {
17933 0
17934 };
17935 if depth != 0 {
17936 hit!(TX_DEPTH_HITS);
17937 hit!(RECT4_16_SPLIT_HITS);
17938 }
17939 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
17940 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17941 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
17942 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
17943 if depth != 0 || lossless(fctx) {
17944 // [`decode_rect_split`]'s per-unit walk, inlined because the
17945 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
17946 // the strip (that function codes one chroma transform per block).
17947 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
17948 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
17949 // unit predicts off the units before it in raster order.
17950 let rect_unit = tx_w != tx_h;
17951 let zero_tu = vec![0i32; tx_w * tx_h];
17952 for tu_row in 0..bh / tx_h {
17953 for tu_col in 0..bw / tx_w {
17954 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
17955 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
17956 let tu_reach =
17957 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
17958 if let Some(b) = &palette_y_buf {
17959 let tu_buf: Vec<u16> = (0..tx_h)
17960 .flat_map(|i| {
17961 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
17962 b[base..base + tx_w].iter().copied()
17963 })
17964 .collect();
17965 set_palette_pred(tu_buf, fctx);
17966 }
17967 if skip {
17968 push_intra_rect(
17969 0,
17970 tu_px,
17971 tu_py,
17972 tx_w,
17973 tx_h,
17974 mode,
17975 angle_delta_y,
17976 tu_reach,
17977 &zero_tu,
17978 None,
17979 filter_intra,
17980 smooth_neighbor,
17981 fctx,
17982 );
17983 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
17984 } else if rect_unit {
17985 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
17986 // 32 coded positions and the `TX_4X4` `tx_type` row:
17987 // exactly [`TxbSet::LumaRect4x8`].
17988 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
17989 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
17990 let set = if reduced_tx_set {
17991 TxbSet::LumaRect4x8
17992 } else {
17993 TxbSet::LumaRect4x8Set1
17994 };
17995 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
17996 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
17997 let (tu_grid, tu_tx_type) = read_coeffs_rect(
17998 dec,
17999 &mut coding,
18000 tu_scan,
18001 tx_w,
18002 tx_h,
18003 tu_skip_ctx,
18004 dc_sign_ctx(tu_around.2),
18005 TxType::DctDct,
18006 0,
18007 )?;
18008 let residual = dequant_and_inverse_typed_wh(
18009 &tu_grid,
18010 tx_w,
18011 tx_h,
18012 crate::decode::bit_depth(fctx),
18013 block_q_idx(fctx),
18014 plane_q_delta(0, fctx).0,
18015 plane_q_delta(0, fctx).1,
18016 tu_tx_type,
18017 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
18018 );
18019 push_intra_rect(
18020 0,
18021 tu_px,
18022 tu_py,
18023 tx_w,
18024 tx_h,
18025 mode,
18026 angle_delta_y,
18027 tu_reach,
18028 &residual,
18029 None,
18030 filter_intra,
18031 smooth_neighbor,
18032 fctx,
18033 );
18034 if tu_grid.iter().any(|&l| l != 0) {
18035 hit!(RECT4_16_COEFF_HITS);
18036 }
18037 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
18038 } else {
18039 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
18040 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
18041 let tu_grid = read_plane(
18042 dec,
18043 cdfs,
18044 txbset_for(tx_w, reduced_tx_set),
18045 default_scan(tx_w),
18046 0,
18047 tu_around,
18048 mode,
18049 mode,
18050 angle_delta_y,
18051 tu_reach,
18052 y,
18053 tu_px,
18054 tu_py,
18055 tx_w,
18056 tx_w,
18057 base_q_idx,
18058 None,
18059 filter_intra,
18060 Some(tu_skip_ctx),
18061 smooth_neighbor,
18062 fctx,
18063 )?;
18064 if tu_grid.iter().any(|&l| l != 0) {
18065 hit!(RECT4_16_COEFF_HITS);
18066 }
18067 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
18068 }
18069 }
18070 }
18071 } else {
18072 let levels = if skip {
18073 let zeros = Grid::Zero(bw * bh);
18074 if let Some(b) = &palette_y_buf {
18075 set_palette_pred(b.clone(), fctx);
18076 }
18077 push_intra_rect(
18078 0,
18079 px,
18080 py,
18081 bw,
18082 bh,
18083 mode,
18084 angle_delta_y,
18085 reach,
18086 &zeros,
18087 None,
18088 filter_intra,
18089 smooth_neighbor,
18090 fctx,
18091 );
18092 zeros
18093 } else {
18094 // The strip's luma TU *is* the strip (`plane_bsize ==
18095 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
18096 // `txb_skip_ctx` at 0.
18097 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
18098 let set = if reduced_tx_set {
18099 TxbSet::LumaRect16x4
18100 } else {
18101 TxbSet::LumaRect16x4Set1
18102 };
18103 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18104 let (levels, tx_type) = read_coeffs_rect(
18105 dec,
18106 &mut coding,
18107 scan,
18108 bw,
18109 bh,
18110 0,
18111 dc_sign_ctx(around.2),
18112 TxType::DctDct,
18113 0,
18114 )?;
18115 let residual = dequant_and_inverse_typed_wh(
18116 &levels,
18117 bw,
18118 bh,
18119 crate::decode::bit_depth(fctx),
18120 block_q_idx(fctx),
18121 plane_q_delta(0, fctx).0,
18122 plane_q_delta(0, fctx).1,
18123 tx_type,
18124 block_iqmatrix(fctx, 0, bw, bh, tx_type),
18125 );
18126 if let Some(b) = &palette_y_buf {
18127 set_palette_pred(b.clone(), fctx);
18128 }
18129 push_intra_rect(
18130 0,
18131 px,
18132 py,
18133 bw,
18134 bh,
18135 mode,
18136 angle_delta_y,
18137 reach,
18138 &residual,
18139 None,
18140 filter_intra,
18141 smooth_neighbor,
18142 fctx,
18143 );
18144 hit!(RECT4_16_COEFF_HITS);
18145 levels
18146 };
18147 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
18148 }
18149 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18150 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18151 // `update_partition_context` writes `partition_context_lookup[
18152 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
18153 // the left (mirrored under VERT_4).
18154 for cell in 0..mi_w {
18155 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18156 *slot = bw as u8;
18157 }
18158 }
18159 for cell in 0..mi_h {
18160 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18161 *slot = bh as u8;
18162 }
18163 }
18164 if has_chroma {
18165 hit!(RECT4_16_CHROMA_HITS);
18166 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
18167 // own chroma reference and codes its own 16x4 / 4x16 chroma
18168 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
18169 // ss 0/0, so the neighbour reads below anchor at the strip.)
18170 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
18171 (lmi, bw, bh)
18172 } else if ss_y(fctx) == 0 && horz {
18173 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
18174 // 16x4 strip is its own chroma reference (`is_chroma_reference`
18175 // at ss(1,0): bh == 1 mi, so the row clause reduces to
18176 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
18177 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
18178 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
18179 // the pair merge below -- its own chroma block
18180 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
18181 // walk proved such leaves exist, and libaom codes the pair's
18182 // chroma from the closing strip; the chunk lives in the
18183 // `chroma422_pair16` arm below.)
18184 (lmi, bw, bh)
18185 } else if horz {
18186 ((lmi.0 - 1, lmi.1), 16, 8)
18187 } else {
18188 ((lmi.0, lmi.1 - 1), 8, 16)
18189 };
18190 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
18191 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
18192 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
18193 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
18194 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
18195 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
18196 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
18197 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
18198 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
18199 // `decode_token_recon_block` walks unit_width =
18200 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
18201 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
18202 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
18203 // walks per unit: `predict_and_reconstruct_intra_block` predicts
18204 // every unit regardless of `skip_txfm`.
18205 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
18206 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18207 DC_PRED
18208 } else {
18209 uv_mode
18210 };
18211 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
18212 hit!(RECT4_16_CHROMA_DIR_HITS);
18213 }
18214 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
18215 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
18216 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
18217 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
18218 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
18219 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
18220 // the pair's top-left luma mi, never this leaf's odd row/column.
18221 // Reading `lmi` here named the leaf directly above (a non-chroma
18222 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
18223 // SMOOTH neighbour: filt_type 0 instead of 1 turned
18224 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
18225 // directional chroma strip, moving 4 samples by 1.
18226 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
18227 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
18228 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
18229 // counter's mirror of the snapping form, and the shipped read offsets
18230 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
18231 //
18232 // lane-av1leftwit: this mirror is NOT evidence about the left read's
18233 // `+ss_y` term, whatever a report once said. It reads the leaf's own
18234 // (odd) mi row, which no decode call site does -- every one of them
18235 // uses the snapping form, whose base row is even -- and its result
18236 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
18237 // and worth keeping (the pair's chroma-reference read against the
18238 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
18239 // so it stays; the decode path's own reach for the `+ss_y` term is
18240 // `uv_left_1mi_split_hits()`.
18241 if smooth_neighbor_uv
18242 != neighbours.smooth_uv_neighbour_unsnapped(
18243 lmi.0,
18244 lmi.1,
18245 r,
18246 c,
18247 ss_x(fctx),
18248 ss_y(fctx),
18249 false,
18250 )
18251 {
18252 hit!(RECT4_16_UV_PAIR_FILT_HITS);
18253 }
18254 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
18255 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
18256 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
18257 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
18258 // the rect here consumed one symbol block too few and desynced
18259 // the next strip's `skip` (measured: lossless sb128 320x240,
18260 // mi(1,20) uv_mode matched, the following skip did not).
18261 let lossless_pair = lossless(fctx);
18262 let (u_levels, v_levels) = if lossless_pair {
18263 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
18264 if skip {
18265 for plane in 1..3usize {
18266 for rr in 0..ch / 4 {
18267 for cc in 0..cw / 4 {
18268 let (ox, oy) = (cc * 4, rr * 4);
18269 // The unit's origin and extent in LUMA pixels: `<< ss`
18270 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
18271 // at 4:4:4 -- the same form as the block-walk sibling
18272 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
18273 // only right at ss (1,1): at 4:4:4 it claims a 4x4
18274 // chroma unit is 8x8 luma, so `of_tu`'s
18275 // `col_off + tx_w < bw` test answers against a
18276 // footprint twice the real one and every unit past
18277 // the block's midpoint wrongly reports
18278 // `above_right = false` -- a directional chroma
18279 // strip then predicts from a neighbour libaom
18280 // never reads (measured: key frame 0, 4:4:4 lossless
18281 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
18282 // entropy bit-identical over 351109 EC_SYMR reads).
18283 let cu_reach = tu_reach(
18284 pw,
18285 ph,
18286 ox << ss_x(fctx),
18287 oy << ss_y(fctx),
18288 4 << ss_x(fctx),
18289 pair_reach,
18290 ppx,
18291 ppy,
18292 y.width,
18293 y.height,
18294 fctx,
18295 );
18296 if let Some((ub, vb)) = &palette_uv_bufs {
18297 let buf = if plane == 1 { ub } else { vb };
18298 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18299 }
18300 push_intra(
18301 plane,
18302 cpx + ox,
18303 cpy + oy,
18304 4,
18305 uv_predict_mode,
18306 angle_delta_uv,
18307 cu_reach,
18308 &ZERO_RESIDUAL[..16],
18309 None,
18310 None,
18311 smooth_neighbor_uv,
18312 fctx,
18313 );
18314 let cu_mi = (
18315 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18316 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18317 );
18318 neighbours.record_mi_chroma(
18319 cu_mi,
18320 4 << ss_x(fctx),
18321 4 << ss_y(fctx),
18322 plane,
18323 &ZERO_RESIDUAL[..16],
18324 );
18325 }
18326 }
18327 }
18328 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18329 } else {
18330 let scan4 = default_scan(4);
18331 // `get_txb_ctx`: offset 10 (our tables store it at +3)
18332 // when the plane block is larger than the transform.
18333 let offset = Some(3usize);
18334 let mut uo = vec![0i32; cw * ch];
18335 let mut vo = vec![0i32; cw * ch];
18336 for plane in 1..3usize {
18337 for rr in 0..ch / 4 {
18338 for cc in 0..cw / 4 {
18339 let (ox, oy) = (cc * 4, rr * 4);
18340 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
18341 continue;
18342 }
18343 // The unit's stamp is its own span: aom
18344 // `av1_set_entropy_contexts` (blockd.c:29)
18345 // memsets exactly `tx_size_wide_unit` x
18346 // `tx_size_high_unit` cells at the unit's own
18347 // `(aoff, loff)` -- for TX_4X4 ONE above cell
18348 // and ONE left cell. `(oy / 2, ox / 2)` +
18349 // `(8, 8)` is the 4:2:0 subsampled form (one
18350 // chroma cell = 8 luma px = 2 mi cells); at
18351 // 4:4:4 a unit is ONE mi cell, and the 2x2
18352 // smear let a 4-wide strip's later units
18353 // overwrite the NEXT COLUMN's above cell with
18354 // their own state -- a column aom never sees
18355 // this block write -- so the following block's
18356 // `all_zero` read the wrong `txb_skip` row
18357 // (frame-0 read #452, the llkf named gap).
18358 let cu_mi = (
18359 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18360 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18361 );
18362 // One luma-mi cell: the chroma entropy arrays
18363 // are subsampled, and our bands replicate that
18364 // one entry over the unit's two cells
18365 // (`read_intra_chroma_lossless`).
18366 let cu_around = neighbours.around_mi(cu_mi, MI);
18367 // Same ss-aware luma footprint as the skip arm
18368 // above -- `ox * 2 / 8` is the 4:2:0-only form and
18369 // mis-answers `of_tu` at 4:4:4 (see there).
18370 let cu_reach = tu_reach(
18371 pw,
18372 ph,
18373 ox << ss_x(fctx),
18374 oy << ss_y(fctx),
18375 4 << ss_x(fctx),
18376 pair_reach,
18377 ppx,
18378 ppy,
18379 y.width,
18380 y.height,
18381 fctx,
18382 );
18383 if let Some((ub, vb)) = &palette_uv_bufs {
18384 let buf = if plane == 1 { ub } else { vb };
18385 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18386 }
18387 let buf: &mut PlaneBuf<'static> =
18388 if plane == 1 { &mut *u } else { &mut *v };
18389 let cu_grid = read_plane(
18390 dec,
18391 cdfs,
18392 TxbSet::Chroma4,
18393 &scan4,
18394 plane,
18395 cu_around[plane],
18396 mode,
18397 uv_predict_mode,
18398 angle_delta_uv,
18399 cu_reach,
18400 buf,
18401 cpx + ox,
18402 cpy + oy,
18403 4,
18404 4,
18405 base_q_idx,
18406 None,
18407 None,
18408 offset,
18409 smooth_neighbor_uv,
18410 fctx,
18411 )?;
18412 neighbours.record_mi_chroma(
18413 cu_mi,
18414 4 << ss_x(fctx),
18415 4 << ss_y(fctx),
18416 plane,
18417 &cu_grid,
18418 );
18419 hit!(CHROMA_SPLIT_TX_HITS);
18420 let dst = if plane == 1 { &mut uo } else { &mut vo };
18421 for row in 0..4 {
18422 let start = (oy + row) * cw + ox;
18423 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
18424 }
18425 }
18426 }
18427 }
18428 (Grid::Own(uo), Grid::Own(vo))
18429 }
18430 } else if skip {
18431 let zeros = Grid::Zero(cw * ch);
18432 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
18433 // ~1000) predicts EVERY plane and only guards the residual on
18434 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
18435 // DC + alpha * luma-AC. Dropping the CfL term here left a
18436 // chroma-only bounded box on ReelC's key frames.
18437 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18438 if alpha.is_some() {
18439 hit!(CHROMA_SKIP_CFL_HITS);
18440 }
18441 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
18442 if chroma422_pair16 {
18443 // lane-av1-422o: two TX_4X8 units, each predicted on
18444 // its own edges (the lower one off the upper one's
18445 // samples); no coefficients are coded, and libaom's
18446 // `set_entropy_context` zeroed the block's own cells,
18447 // so the pair-wide zero stamp below stays correct.
18448 for unit_row in 0..2usize {
18449 let unit_reach = tu_reach_rect(
18450 pw,
18451 ph,
18452 0,
18453 unit_row * 8,
18454 8,
18455 8,
18456 pair_reach,
18457 ppx,
18458 ppy,
18459 y.width,
18460 y.height,
18461 fctx,
18462 );
18463 if let Some((ub, vb)) = &palette_uv_bufs {
18464 let pbuf = if plane == 1 { ub } else { vb };
18465 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18466 }
18467 push_intra_rect(
18468 plane,
18469 cpx,
18470 cpy + unit_row * 8,
18471 4,
18472 8,
18473 uv_predict_mode,
18474 angle_delta_uv,
18475 unit_reach,
18476 &ZERO_RESIDUAL[..4 * 8],
18477 alpha
18478 .zip(ac)
18479 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18480 None,
18481 smooth_neighbor_uv,
18482 fctx,
18483 );
18484 }
18485 } else {
18486 if let Some((ub, vb)) = &palette_uv_bufs {
18487 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18488 }
18489 push_intra_rect(
18490 plane,
18491 cpx,
18492 cpy,
18493 cw,
18494 ch,
18495 uv_predict_mode,
18496 angle_delta_uv,
18497 pair_reach,
18498 &zeros,
18499 alpha
18500 .zip(ac)
18501 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18502 None,
18503 smooth_neighbor_uv,
18504 fctx,
18505 );
18506 }
18507 }
18508 (zeros.clone(), zeros)
18509 } else if chroma422_pair16 {
18510 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
18511 // per plane, plane-major (every U unit, then every V). Each
18512 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
18513 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
18514 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
18515 // offset comes from `num_pels_log2_lookup[plane_bsize] >
18516 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
18517 // BLOCK_INVALID (255), and the byte at that table's +255 in
18518 // the pinned Release oracle is 255 (`cmpb` against the
18519 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
18520 // arm: +3 on the offset-7-first chroma tables. No tx_type
18521 // symbol (only y plane's is transmitted); the unit's type is
18522 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
18523 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
18524 // are computed ONCE per block (`are_parameters_computed`)
18525 // over the pair's luma, shared by both units. Each unit is
18526 // predicted and recorded immediately, so the lower unit
18527 // reads the upper one's coefficient context.
18528 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18529 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
18530 for unit_row in 0..2usize {
18531 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
18532 let unit_reach = tu_reach_rect(
18533 pw,
18534 ph,
18535 0,
18536 unit_row * 8,
18537 8,
18538 8,
18539 pair_reach,
18540 ppx,
18541 ppy,
18542 y.width,
18543 y.height,
18544 fctx,
18545 );
18546 if let Some((ub, vb)) = &palette_uv_bufs {
18547 let pbuf = if plane == 1 { ub } else { vb };
18548 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18549 }
18550 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
18551 let unit_grid = read_rect_chroma_unit(
18552 dec,
18553 cdfs,
18554 TxbSet::ChromaRect8x4,
18555 &SCAN_4X8,
18556 4,
18557 8,
18558 plane,
18559 chroma_around[plane],
18560 uv_predict_mode,
18561 angle_delta_uv,
18562 unit_reach,
18563 buf,
18564 cpx,
18565 cpy + unit_row * 8,
18566 base_q_idx,
18567 // lane-av1-422q: the offset-10 rows -- the same
18568 // measured rule as the 4x32 arm (plane_bsize
18569 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
18570 // num_pels_log2_lookup[255] = 0xff at the
18571 // 0xc0de70 copy -> +3 on the offset-7-first
18572 // chroma tables; see lanes/av1422q.report.md).
18573 Some(3),
18574 alpha
18575 .zip(ac)
18576 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18577 smooth_neighbor_uv,
18578 fctx,
18579 )?;
18580 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
18581 }
18582 }
18583 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18584 } else {
18585 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
18586 // every second luma-mi cell
18587 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
18588 // chroma 4-px column spans two luma mi columns, and the
18589 // plain per-mi gather counts each column's whole-unit dc
18590 // sign twice). The left extent is unsubsampled at ss_y 0,
18591 // so its per-mi cells already line up one-to-one.
18592 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
18593 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
18594 } else {
18595 neighbours.around_mi_rect(pair_mi, pw, ph)
18596 };
18597 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
18598 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
18599 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
18600 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
18601 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
18602 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
18603 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
18604 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
18605 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
18606 // (4,16) never reaches this row; `chroma422_pair16`
18607 // intercepts it above and chunks it into TX_4X8 units.)
18608 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
18609 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
18610 // pair's height: an 8x8 SQUARE chroma block, the same
18611 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
18612 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
18613 // row is unreachable there. It is also the witness arm:
18614 // a restored `/2 chroma height` lands on (8,4) and the
18615 // counter reads 0.
18616 (8, 8) => {
18617 hit!(CHROMA422_SQUARE_HITS);
18618 (TxbSet::Chroma8, default_scan(8))
18619 }
18620 // lane-av1-422o: with the `chroma422_pair16` arm above,
18621 // the (2,16) own-strip shape and the 4:4:4 shapes are the
18622 // only residents; anything else is a named-lane gap.
18623 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
18624 };
18625 let mut planes = Vec::with_capacity(2);
18626 for plane in 1..3 {
18627 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
18628 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
18629 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
18630 let (levels, tx_type) = read_chroma_coeffs_rect(
18631 dec,
18632 &mut coding,
18633 chroma_scan,
18634 cw,
18635 ch,
18636 skip_ctx,
18637 dc_sign_ctx(around[plane].2),
18638 default_tx,
18639 fctx,
18640 plane,
18641 )?;
18642 planes.push((levels, tx_type));
18643 }
18644 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
18645 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
18646 // CfL averages the luma of the WHOLE pair, the region this one
18647 // chroma transform covers.
18648 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18649 for (plane, _buf, levels, tx_type) in [
18650 (1usize, &mut *u, &u_levels, u_tx_type),
18651 (2, &mut *v, &v_levels, v_tx_type),
18652 ] {
18653 let residual = dequant_and_inverse_typed_wh(
18654 levels,
18655 cw,
18656 ch,
18657 crate::decode::bit_depth(fctx),
18658 block_q_idx(fctx),
18659 plane_q_delta(plane, fctx).0,
18660 plane_q_delta(plane, fctx).1,
18661 tx_type,
18662 block_iqmatrix(fctx, plane, cw, ch, tx_type),
18663 );
18664 if let Some((ub, vb)) = &palette_uv_bufs {
18665 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18666 }
18667 push_intra_rect(
18668 plane,
18669 cpx,
18670 cpy,
18671 cw,
18672 ch,
18673 uv_predict_mode,
18674 angle_delta_uv,
18675 pair_reach,
18676 &residual,
18677 alpha
18678 .zip(ac)
18679 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18680 None,
18681 smooth_neighbor_uv,
18682 fctx,
18683 );
18684 }
18685 (u_levels, v_levels)
18686 };
18687 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
18688 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
18689 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
18690 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
18691 // the arm above (libaom's coefficient contexts are per
18692 // 4x4-cell); a pair-wide state would erase the unit boundary the
18693 // next block reads.
18694 if !lossless_pair && !chroma422_pair16 {
18695 // The chroma planes' coefficient context, over the PAIR's mi span
18696 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
18697 // the luma one rounded up to its 4x4 unit).
18698 let u_state = neighbour_state(&u_levels);
18699 let v_state = neighbour_state(&v_levels);
18700 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18701 let bound_h = round_up_even(neighbours.mi_rows);
18702 let bound_w = round_up_even(neighbours.mi_cols);
18703 for cell in 0..(ph / MI) {
18704 if pair_mi.0 + cell < bound_h
18705 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18706 {
18707 slot[1] = u_state;
18708 slot[2] = v_state;
18709 }
18710 }
18711 for cell in 0..(pw / MI) {
18712 if pair_mi.1 + cell < bound_w
18713 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18714 {
18715 slot[1] = u_state;
18716 slot[2] = v_state;
18717 }
18718 }
18719 }
18720 last_uv_mode = Some(uv_predict_mode);
18721 }
18722 if horz {
18723 hit!(RECT4_16_HORZ_HITS);
18724 } else {
18725 hit!(RECT4_16_VERT_HITS);
18726 }
18727 let (pal_y_size, pal_y_colors) = palette_y
18728 .as_ref()
18729 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18730 let (pal_uv_size, pal_uv_colors) = palette_uv
18731 .as_ref()
18732 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18733 record_strip_palette(
18734 neighbours,
18735 lmi,
18736 bw,
18737 bh,
18738 pal_y_size,
18739 pal_y_colors,
18740 pal_uv_size,
18741 pal_uv_colors,
18742 );
18743 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
18744 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
18745 // frame): the above row records `tx_size_wide` over the block's width and
18746 // the left column `tx_size_high` over its height. This 1:4 strip reader is
18747 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
18748 // and it published neither band -- so the block after a 64x16 strip read
18749 // the row's init value 64 as its left transform height and took
18750 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
18751 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
18752 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
18753 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18754 Ok((mode, last_uv_mode, (tx_w, tx_h)))
18755}
18756
18757/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
18758/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
18759/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
18760/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
18761/// cap, so LUMA needs the same corner truncation [`decode_block`] already
18762/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
18763/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
18764/// this function's own charter/report), so both strips read a real 32x32
18765/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
18766/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
18767/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
18768/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
18769/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
18770/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
18771/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
18772/// that function, only the single-transform-unit (`tx_depth == 0`) case is
18773/// supported: a split transform refuses by name rather than guess-decode.
18774#[allow(clippy::too_many_arguments)]
18775fn decode_block_rect64(
18776 dec: &mut SymbolDecoder,
18777 cdfs: &mut Cdfs,
18778 neighbours: &mut Neighbours,
18779 at: (usize, usize),
18780 bw: usize,
18781 bh: usize,
18782 y: &mut PlaneBuf<'static>,
18783 u: &mut PlaneBuf<'static>,
18784 v: &mut PlaneBuf<'static>,
18785 enable_filter_intra: bool,
18786 allow_screen_content_tools: bool,
18787 base_q_idx: u8,
18788 tx_select: bool,
18789 reduced_tx_set: bool,
18790 fctx: &crate::decode::FrameCtx,
18791) -> Result<()> {
18792 let (r, c) = at;
18793 let (px, py) = (c * SUB, r * SUB);
18794 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
18795 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
18796 let palette_uv_cache = neighbours.palette_uv_cache(at);
18797 let (
18798 skip,
18799 mode,
18800 angle_delta_y,
18801 uv_mode,
18802 angle_delta_uv,
18803 alpha,
18804 filter_intra,
18805 palette_y,
18806 palette_uv,
18807 intrabc,
18808 ) = read_intra_mode_rect(
18809 dec,
18810 cdfs,
18811 nb_above_mode,
18812 nb_left_mode,
18813 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
18814 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
18815 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
18816 // correct), CFL must never be offered here -- passing `true`
18817 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
18818 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
18819 // from this block's very first symbol (lane-sbpart r3 bisect).
18820 false,
18821 true,
18822 bw,
18823 bh,
18824 enable_filter_intra,
18825 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
18826 allow_screen_content_tools,
18827 Some((palette_ctx, &palette_cache)),
18828 &palette_uv_cache,
18829 r * (SUB / MI),
18830 c * (SUB / MI),
18831 fctx,
18832 )?;
18833 if let Some((dv_row, dv_col)) = intrabc {
18834 return decode_intrabc_owned_rect(
18835 dec,
18836 cdfs,
18837 neighbours,
18838 (r * (SUB / MI), c * (SUB / MI)),
18839 (bw, bh),
18840 skip,
18841 (dv_row, dv_col),
18842 y,
18843 u,
18844 v,
18845 base_q_idx,
18846 tx_select,
18847 reduced_tx_set,
18848 fctx,
18849 );
18850 }
18851 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
18852 // lane-t900 r34: a non-skip palette block on a superblock-level strip
18853 // -- counted so its gate cannot go vacuous (this was a refusal until
18854 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
18855 // decodes_pixel_exact`).
18856 hit!(PALETTE_SB_STRIP_HITS);
18857 }
18858 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
18859 if smooth_neighbor {
18860 hit!(SMOOTH_LUMA_HITS);
18861 }
18862 let smooth_neighbor_uv =
18863 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
18864 if filter_intra.is_some() {
18865 // `filter_intra_size_class_rect` already returns `None` for both
18866 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
18867 // 32 on both axes), so this symbol is never read at this level --
18868 // kept only as the same defensive refusal [`decode_block_rect`] has.
18869 return Err(unsupported(
18870 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
18871 av1_filter_intra_allowed_bsize caps at 32x32)",
18872 ));
18873 }
18874 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18875 DC_PRED
18876 } else {
18877 uv_mode
18878 };
18879 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
18880 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
18881 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
18882 // no depth symbol here either (class sweep of the sub8 leaf's fix).
18883 let depth = if tx_select && !lossless(fctx) {
18884 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
18885 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
18886 // intra-only frame publishes them from every block too
18887 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
18888 // 1920x792 128-superblock stream,
18889 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
18890 // `tx_size_cat2` row 1 where libaom reads row 2.
18891 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
18892 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
18893 // counts `sub_tx_size_map` steps from the block's own max rect
18894 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
18895 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
18896 // steps, so this level's category is 3 (the same one a 64x64 square
18897 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
18898 // here was a wrong-table read of a real symbol.
18899 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
18900 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18901 eprintln!(
18902 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
18903 dec.debug_state().0
18904 );
18905 }
18906 d
18907 } else {
18908 0
18909 };
18910 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
18911 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
18912 publish_txfm_bands_if_in_inter(
18913 neighbours,
18914 (mi_r, mi_c),
18915 depth_to_tx_wh(bw, bh, depth, fctx),
18916 (bw, bh),
18917 fctx,
18918 );
18919 if depth != 0 || lossless(fctx) {
18920 hit!(TX_DEPTH_HITS);
18921 // lane-rectsplit r1/r4: the superblock-level strip splits its
18922 // transform through the very same per-unit path as its 32x32-level
18923 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
18924 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
18925 // measured the old square formula mis-tiling exactly that strip).
18926 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18927 if bw.max(bh) / bw.min(bh) == 4 {
18928 let which = if depth == 1 {
18929 &RECT4_SPLIT_DEPTH1_HITS
18930 } else {
18931 &RECT4_SPLIT_DEPTH2_HITS
18932 };
18933 hit_do! { which.with(|c| c.set(c.get() + 1)); }
18934 }
18935 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
18936 eprintln!(
18937 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
18938 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
18939 angle_y={angle_delta_y}"
18940 );
18941 }
18942 let modes = RectStripModes {
18943 skip,
18944 mode,
18945 angle_delta_y,
18946 uv_predict_mode,
18947 angle_delta_uv,
18948 alpha,
18949 filter_intra,
18950 smooth_neighbor,
18951 smooth_neighbor_uv,
18952 palette_y: palette_y
18953 .as_ref()
18954 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
18955 palette_uv: palette_uv.as_ref().map(|p| {
18956 (
18957 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18958 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18959 )
18960 }),
18961 };
18962 if palette_y.is_some() || palette_uv.is_some() {
18963 hit!(PALETTE_SPLIT_TX_HITS);
18964 }
18965 decode_rect_split(
18966 dec,
18967 cdfs,
18968 neighbours,
18969 (mi_r, mi_c),
18970 bw,
18971 bh,
18972 tx_w,
18973 tx_h,
18974 &modes,
18975 y,
18976 u,
18977 v,
18978 base_q_idx,
18979 reduced_tx_set,
18980 fctx,
18981 )?;
18982 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
18983 // (lane-palette2 r10): this return skips the fn's own tail, so a
18984 // split-tx superblock strip would otherwise leave the above/left
18985 // palette arrays holding a dead block's colours.
18986 let (py_size, py_colors) = palette_y
18987 .as_ref()
18988 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18989 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
18990 let (puv_size, puv_colors) = palette_uv
18991 .as_ref()
18992 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18993 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
18994 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
18995 // return skips the fn's own tail, so a SPLIT superblock-level strip
18996 // published no TXFM_CONTEXT band and the next block read the row's init
18997 // value 64 as its left transform height. Measured on the 10-bit
18998 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
18999 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
19000 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
19001 // bands carry the SPLIT unit's size, not the block's.
19002 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19003 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
19004 hit!(RECT_PARTITION_HITS);
19005 return Ok(());
19006 }
19007 let (tx_w, tx_h) = (bw, bh);
19008 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
19009 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
19010 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19011 if let Some(ref pyv) = palette_y {
19012 let buf: Vec<u16> = pyv
19013 .map
19014 .iter()
19015 .map(|&idx| pyv.colors[idx as usize])
19016 .collect();
19017 set_palette_pred(buf, fctx);
19018 }
19019 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
19020 (
19021 puv.map
19022 .iter()
19023 .map(|&idx| puv.u_colors[idx as usize])
19024 .collect(),
19025 puv.map
19026 .iter()
19027 .map(|&idx| puv.v_colors[idx as usize])
19028 .collect(),
19029 )
19030 });
19031 if skip {
19032 push_intra_rect(
19033 0,
19034 px,
19035 py,
19036 bw,
19037 bh,
19038 mode,
19039 angle_delta_y,
19040 reach,
19041 &ZERO_RESIDUAL[..bw * bh],
19042 None,
19043 filter_intra,
19044 smooth_neighbor,
19045 fctx,
19046 );
19047 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19048 if let Some((ub, _)) = &palette_uv_bufs {
19049 set_palette_pred(ub.clone(), fctx);
19050 }
19051 push_intra_rect(
19052 1,
19053 cpx,
19054 cpy,
19055 chroma_w,
19056 chroma_h,
19057 uv_predict_mode,
19058 angle_delta_uv,
19059 reach,
19060 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19061 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
19062 None,
19063 smooth_neighbor_uv,
19064 fctx,
19065 );
19066 if let Some((_, vb)) = &palette_uv_bufs {
19067 set_palette_pred(vb.clone(), fctx);
19068 }
19069 push_intra_rect(
19070 2,
19071 cpx,
19072 cpy,
19073 chroma_w,
19074 chroma_h,
19075 uv_predict_mode,
19076 angle_delta_uv,
19077 reach,
19078 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19079 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
19080 None,
19081 smooth_neighbor_uv,
19082 fctx,
19083 );
19084 neighbours.record_rect(
19085 at,
19086 bw,
19087 bh,
19088 mode,
19089 uv_predict_mode,
19090 &[
19091 &ZERO_RESIDUAL[..bw * bh],
19092 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19093 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19094 ],
19095 );
19096 } else {
19097 let around = neighbours.around_rect(at, bw, bh);
19098 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
19099 // (see this function's own doc comment). A 64-length axis codes only
19100 // its low 32 coefficients, so the corner is `min(bw, 32)` x
19101 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
19102 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
19103 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
19104 let scan32 = default_scan(TX32);
19105 if coeff_trace_on() {
19106 let (rng, _) = dec.debug_state();
19107 eprintln!(
19108 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
19109 );
19110 }
19111 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
19112 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
19113 read_coeffs(
19114 dec,
19115 &mut luma_coding,
19116 &scan32,
19117 0,
19118 dc_sign_ctx(around[0].2),
19119 TxType::DctDct,
19120 Some((bw, bh)),
19121 )?
19122 } else {
19123 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
19124 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
19125 // (`scan.c`) gives both the very same `default_scan_32x16` /
19126 // `default_scan_16x32` the 2:1 sizes use ("Half of the
19127 // coefficients of tx64 at higher frequencies are set to zeros. So
19128 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
19129 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
19130 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
19131 // 512-position eob group) -- BOTH identical to TX_32X16, so the
19132 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
19133 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
19134 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
19135 // what `base_ctx_rect` computes at (32, 16).
19136 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
19137 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
19138 read_coeffs_rect(
19139 dec,
19140 &mut luma_coding,
19141 luma_scan,
19142 luma_cw,
19143 luma_ch,
19144 0,
19145 dc_sign_ctx(around[0].2),
19146 TxType::DctDct,
19147 0,
19148 )?
19149 };
19150 if coeff_trace_on() {
19151 let (rng, _) = dec.debug_state();
19152 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
19153 }
19154 let mut luma_levels = vec![0i32; bw * bh];
19155 for row in 0..luma_ch {
19156 luma_levels[row * bw..][..luma_cw]
19157 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
19158 }
19159 {
19160 let cur = block_q_idx(fctx);
19161 if cur != i32::from(base_q_idx) {
19162 hit!(RECT64_QIDX_DRIFT_HITS);
19163 }
19164 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19165 eprintln!(
19166 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
19167 );
19168 }
19169 }
19170 let luma_residual = dequant_and_inverse_typed_wh(
19171 &luma_levels,
19172 bw,
19173 bh,
19174 crate::decode::bit_depth(fctx),
19175 block_q_idx(fctx),
19176 plane_q_delta(0, fctx).0,
19177 plane_q_delta(0, fctx).1,
19178 luma_tx_type,
19179 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
19180 );
19181 push_intra_rect(
19182 0,
19183 px,
19184 py,
19185 bw,
19186 bh,
19187 mode,
19188 angle_delta_y,
19189 reach,
19190 &luma_residual,
19191 None,
19192 filter_intra,
19193 smooth_neighbor,
19194 fctx,
19195 );
19196 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19197 let leftcol: Vec<u16> = if px > 0 {
19198 (py..py + bh)
19199 .map(|row| y.data[row * y.width + px - 1])
19200 .collect()
19201 } else {
19202 vec![]
19203 };
19204 eprintln!(
19205 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
19206 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
19207 luma_corner.iter().any(|&v| v != 0),
19208 &y.data[py * y.width + px..][..bw],
19209 leftcol,
19210 );
19211 }
19212 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
19213 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
19214 // is larger than that, so it is tiled into 32-capped units.
19215 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19216 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
19217 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
19218 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
19219 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
19220 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
19221 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
19222 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
19223 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
19224 _ => {
19225 return Err(unsupported(
19226 "a 64-axis strip whose chroma unit has no coefficient table",
19227 ));
19228 }
19229 };
19230 let bigger = nw * nh > 1;
19231 let mut u_levels = vec![0i32; chroma_w * chroma_h];
19232 let mut v_levels = vec![0i32; chroma_w * chroma_h];
19233 // The tiled units below stamp their own coefficient context
19234 // immediately, then the whole-strip `record_rect` rewrite paints
19235 // every chroma cell with ONE whole-strip state and the per-unit DC
19236 // signs and levels are lost (class `override-slot-on-one-arm`, same
19237 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
19238 // here and replayed after that record, the c8 `mu_chroma_units` way.
19239 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
19240 for plane_idx in 1..=2 {
19241 for cu_row in 0..nh {
19242 for cu_col in 0..nw {
19243 let cu_around = if nw == 1 && nh == 1 {
19244 around
19245 } else {
19246 let lsx = uw << ss_x(fctx);
19247 let lsy = uh << ss_y(fctx);
19248 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
19249 neighbours.around_mi_rect(cu_mi, lsx, lsy)
19250 };
19251 let lsx = uw << ss_x(fctx);
19252 let lsy = uh << ss_y(fctx);
19253 let cfl = alpha.map(|(au, av)| {
19254 let a = if plane_idx == 1 { au } else { av };
19255 (
19256 a,
19257 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
19258 )
19259 });
19260 let levels = if uw == uh {
19261 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
19262 if let Some((ub, vb)) = &palette_uv_bufs {
19263 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19264 }
19265 read_plane(
19266 dec,
19267 cdfs,
19268 chroma_set,
19269 chroma_scan,
19270 plane_idx,
19271 cu_around[plane_idx],
19272 mode,
19273 uv_predict_mode,
19274 angle_delta_uv,
19275 reach,
19276 plane,
19277 cpx + cu_col * uw,
19278 cpy + cu_row * uh,
19279 uw,
19280 uw,
19281 base_q_idx,
19282 cfl,
19283 None,
19284 bigger.then_some(3),
19285 smooth_neighbor_uv,
19286 fctx,
19287 )?
19288 } else {
19289 let skip_ctx = usize::from(cu_around[plane_idx].0)
19290 + usize::from(cu_around[plane_idx].1)
19291 + usize::from(bigger) * 3;
19292 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19293 let (levels, tx_type) = read_chroma_coeffs_rect(
19294 dec,
19295 &mut coding,
19296 chroma_scan,
19297 uw,
19298 uh,
19299 skip_ctx,
19300 dc_sign_ctx(cu_around[plane_idx].2),
19301 TxType::DctDct,
19302 fctx,
19303 plane_idx,
19304 )?;
19305 let residual = dequant_and_inverse_typed_wh(
19306 &levels,
19307 uw,
19308 uh,
19309 crate::decode::bit_depth(fctx),
19310 block_q_idx(fctx),
19311 plane_q_delta(plane_idx, fctx).0,
19312 plane_q_delta(plane_idx, fctx).1,
19313 tx_type,
19314 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
19315 );
19316 if let Some((ub, vb)) = &palette_uv_bufs {
19317 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19318 }
19319 push_intra_rect(
19320 plane_idx,
19321 cpx + cu_col * uw,
19322 cpy + cu_row * uh,
19323 uw,
19324 uh,
19325 uv_predict_mode,
19326 angle_delta_uv,
19327 reach,
19328 &residual,
19329 cfl,
19330 None,
19331 smooth_neighbor_uv,
19332 fctx,
19333 );
19334 levels
19335 };
19336 let dst = if plane_idx == 1 {
19337 &mut u_levels
19338 } else {
19339 &mut v_levels
19340 };
19341 for row in 0..uh {
19342 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
19343 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
19344 }
19345 if bigger {
19346 neighbours.record_mi_chroma(
19347 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19348 lsx,
19349 lsy,
19350 plane_idx,
19351 &levels,
19352 );
19353 tiled_chroma_units.push((
19354 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19355 plane_idx,
19356 levels.clone(),
19357 lsx,
19358 lsy,
19359 ));
19360 }
19361 }
19362 }
19363 }
19364 neighbours.record_rect(
19365 at,
19366 bw,
19367 bh,
19368 mode,
19369 uv_predict_mode,
19370 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
19371 );
19372 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
19373 // chroma cells from the assembled grids' one whole-strip state,
19374 // overwriting exactly the stamps the tiled loop just made.
19375 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
19376 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
19377 }
19378 hit!(RECT_COEFF_HITS);
19379 }
19380 let (py_size, py_colors) = palette_y
19381 .as_ref()
19382 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19383 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19384 let (puv_size, puv_colors) = palette_uv
19385 .as_ref()
19386 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19387 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19388 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
19389 neighbours.fill_lf_grid_rect(
19390 (mi_r, mi_c),
19391 bw / MI,
19392 bh / MI,
19393 tx_w as u8,
19394 tx_h as u8,
19395 0,
19396 fctx,
19397 );
19398 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19399 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19400 // frame): the above row records `tx_size_wide` over the block's width and
19401 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19402 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19403 // and it published neither band -- so the block after a 64x16 strip read
19404 // the row's init value 64 as its left transform height and took
19405 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19406 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19407 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19408 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19409 hit!(SB_RECT_HITS);
19410 match (bw, bh) {
19411 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
19412 (16, 64) => hit!(SB_RECT4_VERT_HITS),
19413 _ => {}
19414 }
19415 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19416 let (rng, _) = dec.debug_state();
19417 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
19418 }
19419 Ok(())
19420}
19421
19422/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
19423/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
19424/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
19425/// it lands away from zero, for gate tests to prove a real stream fired one.
19426fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
19427 let symbol = dec.symbol(cdf);
19428 if symbol != ANGLE_DELTA_ZERO {
19429 hit!(ANGLE_DELTA_HITS);
19430 }
19431 symbol as i32 - ANGLE_DELTA_ZERO as i32
19432}
19433
19434#[allow(clippy::too_many_arguments)]
19435fn read_intra_mode(
19436 dec: &mut SymbolDecoder,
19437 cdfs: &mut Cdfs,
19438 above_mode: usize,
19439 left_mode: usize,
19440 cfl: bool,
19441 side: usize,
19442 enable_filter_intra: bool,
19443 skip_ctx: usize,
19444 allow_screen_content_tools: bool,
19445 allow_intrabc: bool,
19446 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
19447 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
19448 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
19449 // `None` at the excluded call sites (the 8x8-leaf path), which still read
19450 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
19451 // decoder reads either way -- but refuse by name the moment it fires,
19452 // exactly the old behaviour.
19453 palette: Option<(usize, &[u16])>,
19454 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
19455 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
19456 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
19457 // `use_palette_y`, not a neighbour lookup).
19458 palette_uv_cache: &[u16],
19459 mi_r: usize,
19460 mi_c: usize,
19461 fctx: &crate::decode::FrameCtx,
19462) -> Result<(
19463 bool,
19464 usize,
19465 i32,
19466 usize,
19467 i32,
19468 Option<(i32, i32)>,
19469 Option<usize>,
19470 Option<PaletteY>,
19471 Option<PaletteUv>,
19472)> {
19473 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
19474 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
19475 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
19476 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
19477 // line against the instrumented aomdec, not just `tell()`.
19478 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
19479 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
19480 if ec_istep {
19481 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
19482 // (decodemv.c:818), printed at the same point: before the first
19483 // mode-info symbol of the block, so a cross-decoder range ladder can
19484 // be keyed on the BLOCK, not just on the symbol sequence.
19485 eprintln!(
19486 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
19487 dec.debug_state().0
19488 );
19489 }
19490 macro_rules! istep {
19491 ($name:literal, $val:expr) => {
19492 if ec_istep {
19493 let (rng, _) = dec.debug_state();
19494 eprintln!(
19495 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
19496 $name, $val
19497 );
19498 }
19499 };
19500 }
19501 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
19502 // point every square caller routes through (see `read_intra_mode_rect`).
19503 let cfl = if cfl && side > 32 {
19504 hit!(NOCFL_UV_MODE_HITS);
19505 false
19506 } else {
19507 cfl
19508 };
19509 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
19510 // `skip` when `SegIdPreSkip`, and after it otherwise.
19511 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
19512 if seg_id_pre_skip(fctx) {
19513 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
19514 }
19515 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
19516 if trace {
19517 eprintln!(
19518 "TRACE skip value={} rng={}",
19519 skip as i32,
19520 dec.debug_state().0
19521 );
19522 }
19523 istep!("skip", skip as i32);
19524 if !seg_id_pre_skip(fctx) {
19525 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
19526 }
19527 // spec order (see the comment below on `read_intrabc_info`): `skip`,
19528 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
19529 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
19530 istep!("cdef", 0);
19531 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
19532 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
19533 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
19534 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
19535 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19536 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19537 istep!("dq", 0);
19538 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
19539 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
19540 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
19541 // intra frame whose header set `allow_intrabc`. Actual intra block copy
19542 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
19543 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
19544 // draws the line at consuming this one flag symbol and refusing by name
19545 // when it fires, so the arithmetic decoder still resyncs for a stream
19546 // that merely allows (but never uses) intrabc.
19547 if allow_intrabc {
19548 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
19549 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19550 eprintln!(
19551 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
19552 u8::from(use_intrabc),
19553 dec.debug_state().0
19554 );
19555 }
19556 if trace {
19557 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
19558 }
19559 if use_intrabc {
19560 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
19561 if trace {
19562 eprintln!("TRACE intrabc dv={dv:?}");
19563 }
19564 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
19565 hit!(INTRABC_HITS);
19566 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
19567 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
19568 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
19569 // `DC_PRED` (which is also what the neighbour mode contexts and
19570 // the loop filter then see).
19571 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
19572 }
19573 }
19574 let above_ctx = INTRA_MODE_CTX[above_mode];
19575 let left_ctx = INTRA_MODE_CTX[left_mode];
19576 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
19577 if trace {
19578 eprintln!(
19579 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
19580 dec.debug_state().0
19581 );
19582 }
19583 istep!("mode", mode as i32);
19584 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
19585 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
19586 if trace {
19587 eprintln!(
19588 "TRACE angle_delta value={}",
19589 delta + ANGLE_DELTA_ZERO as i32
19590 );
19591 }
19592 delta
19593 } else {
19594 0
19595 };
19596 istep!("angle_y", angle_delta_y);
19597 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
19598 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
19599 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
19600 // gates its chroma symbols on.
19601 let has_chroma = !mono(fctx);
19602 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
19603 let uv_mode = if !has_chroma {
19604 DC_PRED
19605 } else if cfl {
19606 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19607 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
19608 } else {
19609 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19610 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
19611 };
19612 if trace {
19613 eprintln!(
19614 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
19615 dec.debug_state().0
19616 );
19617 }
19618 istep!("uv_mode", uv_mode as i32);
19619 let alpha = if cfl && uv_mode == UV_CFL_PRED {
19620 Some(read_cfl_alphas(dec, cdfs))
19621 } else {
19622 None
19623 };
19624 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
19625 // from this lane's directional chroma: a corner block with neither
19626 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
19627 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
19628 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
19629 // bug in that fallback this lane's own scope does not cover. Keep it
19630 // refused here rather than ship a silently-wrong decode.
19631 if (9..=12).contains(&uv_mode) {
19632 hit!(SMOOTH_UV_HITS);
19633 }
19634 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
19635 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
19636 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
19637 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
19638 // the `else` branch below and never reads one either way.
19639 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
19640 hit!(DIRECTIONAL_UV_HITS);
19641 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
19642 } else {
19643 0
19644 };
19645 istep!("angle_uv", angle_delta_uv);
19646 if angle_delta_uv != 0 {
19647 hit!(UV_ANGLE_DELTA_HITS);
19648 }
19649 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
19650 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
19651 // gated by `av1_allow_palette` (blockd.h -- size bound only,
19652 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
19653 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
19654 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
19655 // read the same CDF row whenever every neighbour really is non-palette).
19656 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
19657 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
19658 // neighbour lookup at all), so it is exact even at the excluded call
19659 // sites once Y decodes real syntax there too.
19660 //
19661 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
19662 // inline from `read_palette_mode_info` -- it runs later, from
19663 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
19664 // after the WHOLE mode-info read for the block, including UV palette
19665 // mode_info (`read_palette_mode_info`'s own second half, right below)
19666 // and `read_filter_intra_mode_info`. So this branch now only reads
19667 // mode/size/colours for both planes (deferring the two colour-index-map
19668 // decodes to after `filter_intra`, below) -- r6's range trace pinned
19669 // this exact ordering bug (`compare-range-not-tell`: ranges matched
19670 // bit-for-bit through the Y colours, diverged only at the old inline
19671 // `decode_color_index_map` call).
19672 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
19673 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
19674 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
19675 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
19676 if mode == DC_PRED {
19677 if trace {
19678 let (rng, _) = dec.debug_state();
19679 eprintln!(
19680 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
19681 );
19682 }
19683 }
19684 let use_palette_y =
19685 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
19686 if mode == DC_PRED && trace {
19687 let (rng, _) = dec.debug_state();
19688 eprintln!(
19689 "TRACE palette_y_mode value={} rng={rng}",
19690 use_palette_y as i32
19691 );
19692 }
19693 if use_palette_y {
19694 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
19695 if trace {
19696 let (rng, _) = dec.debug_state();
19697 eprintln!("TRACE palette_y_size n={n} rng={rng}");
19698 }
19699 let colors = read_palette_colors_y(dec, n, cache, fctx);
19700 if trace {
19701 let (rng, _) = dec.debug_state();
19702 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
19703 }
19704 palette_y_pending = Some((n, colors));
19705 }
19706 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
19707 // unconditionally at this bit position whenever `uv_mode ==
19708 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
19709 // scope always reconstructs chroma alongside luma (`decode_block`
19710 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
19711 // is always true here and does not need threading in.
19712 //
19713 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
19714 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
19715 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
19716 // symbol even at this chroma-owning square block.
19717 let palette_uv_mode_ctx = usize::from(use_palette_y);
19718 if has_chroma
19719 && uv_mode == DC_PRED
19720 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
19721 {
19722 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
19723 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
19724 palette_uv_pending = Some((n, u_colors, v_colors));
19725 }
19726 }
19727 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
19728 // `use_filter_intra` symbol this decoder never read at all until
19729 // lane-av1real r10 -- silently skipping it left every bit past a
19730 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
19731 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
19732 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
19733 // symbol's bits were never consumed).
19734 let mut filter_intra = None;
19735 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
19736 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
19737 // `use_filter_intra` symbol for a Y-palette block, and reading one here
19738 // desynced every screen-content stream from the first palette block on
19739 // (it surfaced as a bogus "partition below 8x8" refusal further down the
19740 // tile).
19741 if mode == DC_PRED
19742 && enable_filter_intra
19743 && palette_y_pending.is_none()
19744 && let Some(class) = filter_intra_size_class(side)
19745 {
19746 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
19747 if trace {
19748 eprintln!(
19749 "TRACE use_filter_intra side={side} rng={} value={}",
19750 dec.debug_state().0,
19751 use_filter_intra as i32
19752 );
19753 }
19754 istep!("use_filter_intra", use_filter_intra as i32);
19755 if use_filter_intra {
19756 hit!(FILTER_INTRA_HITS);
19757 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
19758 if trace {
19759 eprintln!("TRACE filter_intra_mode value={fi_mode}");
19760 }
19761 istep!("filter_intra_mode", fi_mode as i32);
19762 filter_intra = Some(fi_mode);
19763 }
19764 }
19765 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
19766 // shared U/V map) -- the same order libaom's own loop visits them in.
19767 let palette_y = palette_y_pending.map(|(n, colors)| {
19768 let map = decode_color_index_map(
19769 dec,
19770 cdfs,
19771 n,
19772 side,
19773 palette_onscreen(mi_r, mi_c, side, side, fctx),
19774 false,
19775 );
19776 hit!(PALETTE_HITS);
19777 if trace {
19778 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
19779 }
19780 PaletteY {
19781 size: n,
19782 colors,
19783 map,
19784 }
19785 });
19786 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
19787 let on = palette_onscreen_uv(
19788 (side, side),
19789 palette_onscreen(mi_r, mi_c, side, side, fctx),
19790 (side >> ss_x(fctx), side >> ss_y(fctx)),
19791 (ss_x(fctx), ss_y(fctx)),
19792 );
19793 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
19794 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
19795 // square call's `(side >> ss_x)`-squared (4x4), which left a
19796 // 16-entry map for a 32-sample unit and panicked the reconstruct.
19797 let map = decode_color_index_map_wh(
19798 dec,
19799 cdfs,
19800 n,
19801 side >> ss_x(fctx),
19802 side >> ss_y(fctx),
19803 on,
19804 true,
19805 );
19806 hit!(PALETTE_UV_HITS);
19807 if trace {
19808 eprintln!(
19809 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
19810 &u_colors[..n],
19811 &v_colors[..n]
19812 );
19813 }
19814 PaletteUv {
19815 size: n,
19816 u_colors,
19817 v_colors,
19818 map,
19819 }
19820 });
19821 Ok((
19822 skip,
19823 mode,
19824 angle_delta_y,
19825 uv_mode,
19826 angle_delta_uv,
19827 alpha,
19828 filter_intra,
19829 palette_y,
19830 palette_uv,
19831 ))
19832}
19833
19834/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
19835/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
19836/// intra modes.
19837const UV_CFL_PRED: usize = 13;
19838
19839/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
19840/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
19841/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
19842/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
19843/// joint sign the same way. Returns each plane's final signed `alpha_q3`
19844/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
19845fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
19846 hit!(CFL_BLOCK_HITS);
19847 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
19848 let sign_u = ((joint_sign + 1) * 11) >> 5;
19849 let sign_v = (joint_sign + 1) - 3 * sign_u;
19850 let alpha_u = if sign_u == 0 {
19851 0
19852 } else {
19853 let ctx_u = (joint_sign + 1 - 3) as usize;
19854 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
19855 if sign_u == 2 { mag } else { -mag }
19856 };
19857 let alpha_v = if sign_v == 0 {
19858 0
19859 } else {
19860 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
19861 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
19862 if sign_v == 2 { mag } else { -mag }
19863 };
19864 (alpha_u, alpha_v)
19865}
19866
19867/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
19868/// the reconstructed luma samples under a `side`-square block, subsampled
19869/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
19870/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
19871/// to give the AC values [`cfl_scaled`] scales by alpha.
19872fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
19873 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
19874 i32::from(y.data[ly * y.width + lx])
19875 })
19876}
19877
19878/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
19879/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
19880/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
19881/// reconstruction through THIS function rather than a second transcription of
19882/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
19883/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
19884/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
19885fn cfl_ac_ss(
19886 y: &PlaneBuf<'_>,
19887 px: usize,
19888 py: usize,
19889 bw: usize,
19890 bh: usize,
19891 ss_x: usize,
19892 ss_y: usize,
19893) -> Vec<i32> {
19894 if ss_x == 0 && ss_y == 0 {
19895 let mut ac = vec![0i32; bw * bh];
19896 let mut sum = 0i32;
19897 for row in 0..bh {
19898 for col in 0..bw {
19899 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
19900 ac[row * bw + col] = q3;
19901 sum += q3;
19902 }
19903 }
19904 let num_pel = (bw * bh) as i32;
19905 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19906 ac.iter_mut().for_each(|v| *v -= avg);
19907 ac
19908 } else if ss_x == 1 && ss_y == 0 {
19909 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
19910 // averages the HORIZONTAL luma pair above it, at full chroma height
19911 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
19912 // is square here, and the 4:2:0 rect/square helpers below would halve
19913 // the height it must keep.
19914 let (cw, ch) = (bw >> 1, bh);
19915 let mut ac = vec![0i32; cw * ch];
19916 let mut sum = 0i32;
19917 for row in 0..ch {
19918 for col in 0..cw {
19919 let (lx, ly) = (px + col * 2, py + row);
19920 let q3 = (i32::from(y.data[ly * y.width + lx])
19921 + i32::from(y.data[ly * y.width + lx + 1]))
19922 << 2;
19923 ac[row * cw + col] = q3;
19924 sum += q3;
19925 }
19926 }
19927 let num_pel = (cw * ch) as i32;
19928 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19929 ac.iter_mut().for_each(|v| *v -= avg);
19930 ac
19931 } else if bw == bh {
19932 cfl_ac_q3(y, px, py, bw)
19933 } else {
19934 cfl_ac_q3_rect(y, px, py, bw, bh)
19935 }
19936}
19937
19938pub(crate) fn cfl_ac_q3_at(
19939 px: usize,
19940 py: usize,
19941 bw: usize,
19942 bh: usize,
19943 sample: impl Fn(usize, usize) -> i32,
19944) -> Vec<i32> {
19945 let (cw, ch) = (bw / 2, bh / 2);
19946 let mut ac = vec![0i32; cw * ch];
19947 let mut sum = 0i32;
19948 for cy in 0..ch {
19949 for cx in 0..cw {
19950 let (lx, ly) = (px + cx * 2, py + cy * 2);
19951 let q3 =
19952 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
19953 << 1;
19954 ac[cy * cw + cx] = q3;
19955 sum += q3;
19956 }
19957 }
19958 let num_pel = (cw * ch) as i32;
19959 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19960 ac.iter_mut().for_each(|v| *v -= avg);
19961 ac
19962}
19963
19964/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
19965/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
19966/// ties away from zero on the shifted-out sign).
19967pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
19968 let v = alpha_q3 * ac_q3;
19969 if v >= 0 {
19970 (v + 32) >> 6
19971 } else {
19972 -((-v + 32) >> 6)
19973 }
19974}
19975
19976/// One plane's reconstruction buffer, `width * height` samples, and the
19977/// prediction/residual reads and writes into it — the decode-side twin of
19978/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
19979/// (own-edge and reach clamps both), passing what it gathers straight to
19980/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
19981/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
19982/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
19983/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
19984/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
19985/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
19986/// lane-mc64 r1: the decode-order index the stage dumps below key their file
19987/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
19988/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
19989/// without this every frame overwrote `.f0` and a per-frame bisection silently
19990/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
19991#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
19992fn stage_dump_idx() -> usize {
19993 PREFILT_PICTURE_IDX
19994 .load(std::sync::atomic::Ordering::SeqCst)
19995 .saturating_sub(1)
19996}
19997
19998fn dump_stage16(
19999 var: &str,
20000 y: &PlaneBuf<'_>,
20001 u: &PlaneBuf<'_>,
20002 v: &PlaneBuf<'_>,
20003 fw: usize,
20004 fh: usize,
20005) {
20006 use std::io::Write;
20007 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
20008 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
20009 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
20010 // not be read out at all.
20011 if let Ok(path) = crate::envflags::var(var)
20012 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20013 {
20014 for (p, w, h) in [
20015 (y, fw, fh),
20016 (u, fw.div_ceil(2), fh.div_ceil(2)),
20017 (v, fw.div_ceil(2), fh.div_ceil(2)),
20018 ] {
20019 for row in 0..h {
20020 let mut bytes = Vec::with_capacity(w * 2);
20021 for &s in &p.data[row * p.width..][..w] {
20022 bytes.extend_from_slice(&s.to_le_bytes());
20023 }
20024 let _ = f.write_all(&bytes);
20025 }
20026 }
20027 }
20028}
20029
20030/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
20031/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
20032/// every frame overwrote the previous one and only the LAST frame survived,
20033/// which silently defeats any per-frame filter-stage bisection.
20034fn dump_stage_idx(var: &str) -> usize {
20035 use std::collections::HashMap;
20036 use std::sync::{Mutex, OnceLock};
20037 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
20038 let mut m = IDX
20039 .get_or_init(|| Mutex::new(HashMap::new()))
20040 .lock()
20041 .unwrap();
20042 let e = m.entry(var.to_string()).or_insert(0);
20043 let i = *e;
20044 *e += 1;
20045 i
20046}
20047
20048fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20049 use std::io::Write;
20050 if let Ok(path) = crate::envflags::var(var)
20051 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20052 {
20053 for p in [y, u, v] {
20054 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
20055 let _ = f.write_all(&narrow);
20056 }
20057 }
20058}
20059
20060/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
20061/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
20062/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
20063/// `uv_width`/`uv_height`), so the two can be diffed directly.
20064///
20065/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
20066/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
20067/// measurement traps, and the second one is why the first went unnoticed:
20068/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
20069/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
20070/// inter frame had no pre-filter rung to compare against and got attributed to
20071/// reconstruction when the oracle could not see it. The `static` also restarted
20072/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
20073/// per-frame bisection silently compared the LAST decoded frame. The counter
20074/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
20075/// the inter path (skipped when the filter pipeline is active, which has
20076/// already deblocked by the time the tile tail runs -- same condition
20077/// `capture_filter_replay` guards itself with).
20078fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20079 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
20080 return;
20081 };
20082 use std::io::Write;
20083 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
20084 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
20085 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
20086 for row in 0..plane.true_height {
20087 out.extend(
20088 plane.data[row * plane.width..][..plane.true_width]
20089 .iter()
20090 .map(|&s| s as u8),
20091 );
20092 }
20093 out
20094 };
20095 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
20096 let _ = f.write_all(&crop(y));
20097 let _ = f.write_all(&crop(u));
20098 let _ = f.write_all(&crop(v));
20099 }
20100}
20101
20102/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
20103/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
20104/// at most 4095), so a decode that hashes identically under the flag proves
20105/// the output does not depend on the plane buffer's initial content.
20106const PLANE_SENTINEL: u16 = 0xDEAD;
20107
20108/// A frame plane's own backing store, `n` samples, UNINITIALISED.
20109///
20110/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
20111/// by the tile walk's reconstruction before anything reads it, so the
20112/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
20113/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
20114/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
20115/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
20116/// ways (see the lane report) and the two agree, which is the proof that no
20117/// unwritten sample reaches the output.
20118fn fresh_plane(n: usize) -> Vec<u16> {
20119 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
20120 return vec![PLANE_SENTINEL; n];
20121 }
20122 let mut v: Vec<u16> = Vec::with_capacity(n);
20123 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
20124 // capacity was just reserved, so the vector owns `n` initialised-or-not
20125 // `u16` slots. Every one is written by reconstruction before it is read
20126 // (proven by the sentinel gate above).
20127 #[allow(unsafe_code)]
20128 unsafe {
20129 v.set_len(n);
20130 }
20131 v
20132}
20133
20134#[derive(Clone)]
20135struct PlaneBuf<'a> {
20136 data: std::borrow::Cow<'a, [u16]>,
20137 width: usize,
20138 height: usize,
20139 /// The frame's true, decodable extent in this plane's own units — past
20140 /// this, samples are the padded coding surface's invented tail, never a
20141 /// real decoder's edge or reach reads.
20142 true_width: usize,
20143 true_height: usize,
20144 /// This plane's own tile's top-left pixel origin (spec: intra prediction
20145 /// never reaches across a tile boundary even though an earlier-decoded
20146 /// tile's real pixels sit right there in the shared buffer) — set via
20147 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
20148 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
20149 /// is threaded (the two-tile column-split stage 1 fixture's tile always
20150 /// ends at the frame's own right/bottom edge); a non-last tile's own
20151 /// right/bottom reach bound is still open, tracked in the report.
20152 tile_x0: usize,
20153 tile_y0: usize,
20154 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
20155 /// (exclusive) -- a non-last tile column/row's own reach must stop at
20156 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
20157 /// full padded extent) for the single-tile/last-tile case, matching the
20158 /// old unclipped behaviour exactly.
20159 tile_x1: usize,
20160 tile_y1: usize,
20161}
20162
20163/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
20164/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
20165/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
20166/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
20167/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
20168/// `ALTREF2`/`ALTREF`).
20169
20170impl PlaneBuf<'_> {
20171 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
20172 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
20173 /// are already in this plane's own units (luma pixels for `y`, chroma
20174 /// pixels — halved — for `u`/`v`).
20175 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
20176 self.tile_x0 = x0;
20177 self.tile_y0 = y0;
20178 self.tile_x1 = x1;
20179 self.tile_y1 = y1;
20180 }
20181
20182 fn edges(
20183 &self,
20184 x: usize,
20185 y: usize,
20186 side: usize,
20187 reach: Reach,
20188 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20189 let own_across = x + side.min(self.true_width.saturating_sub(x));
20190 let across = if reach.above_right {
20191 own_across + side.min(self.true_width.saturating_sub(own_across))
20192 } else {
20193 own_across
20194 }
20195 .min(self.width)
20196 .min(self.tile_x1);
20197 let own_down = y + side.min(self.true_height.saturating_sub(y));
20198 let down = if reach.below_left {
20199 own_down + side.min(self.true_height.saturating_sub(own_down))
20200 } else {
20201 own_down
20202 }
20203 .min(self.height)
20204 .min(self.tile_y1);
20205 let above = (y > self.tile_y0 && across > x)
20206 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20207 let left = (x > self.tile_x0 && down > y).then(|| {
20208 (y..down)
20209 .map(|row| self.data[row * self.width + x - 1])
20210 .collect::<Vec<_>>()
20211 });
20212 let corner =
20213 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20214 (above, left, corner)
20215 }
20216
20217 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
20218 /// the above/left reach each extend by their OWN axis (`bw` across,
20219 /// `bh` down), not one shared `side`.
20220 fn edges_rect(
20221 &self,
20222 x: usize,
20223 y: usize,
20224 bw: usize,
20225 bh: usize,
20226 reach: Reach,
20227 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20228 let own_across = x + bw.min(self.true_width.saturating_sub(x));
20229 let across = if reach.above_right {
20230 own_across + bw.min(self.true_width.saturating_sub(own_across))
20231 } else {
20232 own_across
20233 }
20234 .min(self.width)
20235 .min(self.tile_x1);
20236 let own_down = y + bh.min(self.true_height.saturating_sub(y));
20237 let down = if reach.below_left {
20238 own_down + bh.min(self.true_height.saturating_sub(own_down))
20239 } else {
20240 own_down
20241 }
20242 .min(self.height)
20243 .min(self.tile_y1);
20244 let above = (y > self.tile_y0 && across > x)
20245 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20246 let left = (x > self.tile_x0 && down > y).then(|| {
20247 (y..down)
20248 .map(|row| self.data[row * self.width + x - 1])
20249 .collect::<Vec<_>>()
20250 });
20251 let corner =
20252 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20253 if matches!((bw, bh), (16, 8) | (8, 16)) {
20254 hit!(RECT_STRIP_PRED_HITS);
20255 if across > own_across || down > own_down {
20256 hit!(RECT_STRIP_REACH_HITS);
20257 }
20258 }
20259 (above, left, corner)
20260 }
20261
20262 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
20263 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
20264 /// already-rect-capable `(bw, bh)` pair.
20265 #[allow(clippy::too_many_arguments)]
20266 #[track_caller]
20267 fn reconstruct_rect(
20268 &mut self,
20269 x: usize,
20270 y: usize,
20271 bw: usize,
20272 bh: usize,
20273 mode: usize,
20274 angle_delta: i32,
20275 reach: Reach,
20276 residual: &[i32],
20277 cfl: Option<(i32, &[i32])>,
20278 filter_intra: Option<usize>,
20279 smooth_neighbor: bool,
20280 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20281 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20282 // than by this replay.
20283 pred: Option<Vec<u16>>,
20284 fctx: &crate::decode::FrameCtx,
20285 ) {
20286 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
20287 // (lane-palette2 r4): a palette block's prediction is the
20288 // reconstructed colour-index map, needing no edge pixels at all.
20289 let prediction = if let Some(buf) = pred {
20290 buf
20291 } else {
20292 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
20293 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20294 eprintln!(
20295 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
20296 above.as_ref().map(|a| (a.len(), a[0])),
20297 left.as_ref().map(|l| l.len()),
20298 left.as_ref().map(|l| l[0]),
20299 self.tile_x0,
20300 self.tile_y0,
20301 self.true_width,
20302 self.true_height
20303 );
20304 }
20305 let mut prediction = vec![0u16; bw * bh];
20306 if let Some(fi_mode) = filter_intra {
20307 crate::intra::predict_filter_intra(
20308 fi_mode,
20309 above.as_deref(),
20310 left.as_deref(),
20311 corner,
20312 bw,
20313 bh,
20314 &mut prediction,
20315 fctx,
20316 );
20317 } else {
20318 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20319 predict(
20320 mode as u8,
20321 angle_delta,
20322 above.as_deref(),
20323 left.as_deref(),
20324 corner,
20325 bw,
20326 bh,
20327 enable_edge_filter,
20328 smooth_neighbor,
20329 &mut prediction,
20330 fctx,
20331 );
20332 }
20333 prediction
20334 };
20335 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20336 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20337 if crate::envflags::env_flag!("EC_PRED") {
20338 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20339 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20340 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
20341 eprintln!(
20342 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20343 std::panic::Location::caller(),
20344 recon_plane(),
20345 i32::from(smooth_neighbor)
20346 );
20347 }
20348 let residual = dense_residual(residual, bw * bh);
20349 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20350 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
20351 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20352 eprintln!(
20353 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
20354 );
20355 }
20356 for row in 0..bh {
20357 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
20358 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
20359 // whose padded width is not superblock aligned hangs past it.
20360 if y + row >= self.height {
20361 break;
20362 }
20363 for col in 0..bw {
20364 if x + col >= self.width {
20365 break;
20366 }
20367 let idx = row * bw + col;
20368 let mut base = i32::from(prediction[idx]);
20369 if let Some((alpha_q3, ac_q3)) = cfl {
20370 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20371 }
20372 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20373 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20374 }
20375 }
20376 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
20377 // -- a block whose prediction matches the oracle's but whose written
20378 // samples do not is either a residual defect or a later overwrite, and
20379 // only this print separates the two.
20380 if crate::envflags::env_flag!("EC_PRED") {
20381 let row0: Vec<u16> = (0..bw.min(8))
20382 .map(|c| self.data[y * self.width + x + c])
20383 .collect();
20384 let col0: Vec<u16> = (0..bh.min(8))
20385 .map(|r| self.data[(y + r) * self.width + x])
20386 .collect();
20387 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
20388 }
20389 }
20390
20391 /// Predicts under `mode` then adds `residual` (side*side, raster),
20392 /// writing the clamped reconstruction back into the plane at `(x, y)`.
20393 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
20394 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
20395 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
20396 /// order (cfl.c).
20397 #[track_caller]
20398 fn reconstruct(
20399 &mut self,
20400 x: usize,
20401 y: usize,
20402 side: usize,
20403 mode: usize,
20404 angle_delta: i32,
20405 reach: Reach,
20406 residual: &[i32],
20407 cfl: Option<(i32, &[i32])>,
20408 filter_intra: Option<usize>,
20409 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
20410 // libaom `get_filt_type`): true when the block's above OR left
20411 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
20412 // Callers pass their own plane's neighbour-mode check
20413 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
20414 // callers until a smooth/paeth `uv_mode` can reach this call at all
20415 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
20416 // keeps `false` exact for chroma without this fn needing to know why.
20417 smooth_neighbor: bool,
20418 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20419 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20420 // than by this replay.
20421 pred: Option<Vec<u16>>,
20422 fctx: &crate::decode::FrameCtx,
20423 ) {
20424 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
20425 // takes priority over `predict()`/`predict_filter_intra` entirely --
20426 // palette prediction needs no edge pixels at all.
20427 let prediction = if let Some(buf) = pred {
20428 buf
20429 } else {
20430 let (above, left, corner) = self.edges(x, y, side, reach);
20431 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20432 eprintln!(
20433 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
20434 above.as_deref(),
20435 left.as_deref(),
20436 );
20437 }
20438 let mut prediction = vec![0u16; side * side];
20439 if let Some(fi_mode) = filter_intra {
20440 crate::intra::predict_filter_intra(
20441 fi_mode,
20442 above.as_deref(),
20443 left.as_deref(),
20444 corner,
20445 side,
20446 side,
20447 &mut prediction,
20448 fctx,
20449 );
20450 } else {
20451 // `enable_intra_edge_filter` is the sequence header's own flag
20452 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
20453 // call, never per-block) -- threading it through every
20454 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
20455 // dozen sites for a value that never changes mid-decode, so it
20456 // rides a thread-local instead (this decoder is single-threaded
20457 // per stream).
20458 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20459 predict(
20460 mode as u8,
20461 angle_delta,
20462 above.as_deref(),
20463 left.as_deref(),
20464 corner,
20465 side,
20466 side,
20467 enable_edge_filter,
20468 smooth_neighbor,
20469 &mut prediction,
20470 fctx,
20471 );
20472 }
20473 prediction
20474 };
20475 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20476 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20477 if crate::envflags::env_flag!("EC_PRED") {
20478 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20479 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
20480 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
20481 eprintln!(
20482 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20483 std::panic::Location::caller(),
20484 recon_plane(),
20485 i32::from(smooth_neighbor)
20486 );
20487 }
20488 let residual = dense_residual(residual, side * side);
20489 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20490 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
20491 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
20492 eprintln!(
20493 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
20494 cfl.is_some()
20495 );
20496 }
20497 for row in 0..side {
20498 // lane-sb128c r8: libaom's frame buffer is superblock
20499 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
20500 // transform unit of a 128x64 block at the BOTTOM frame edge
20501 // can hang past the last padded row (1920x792: a unit at
20502 // y=768 wants 832 rows of an 800-row buffer, which panicked
20503 // the film's key frames). Those samples are outside the
20504 // frame: never output, and no block below ever references
20505 // them.
20506 if y + row >= self.height {
20507 break;
20508 }
20509 for col in 0..side {
20510 if x + col >= self.width {
20511 break;
20512 }
20513 let idx = row * side + col;
20514 let mut base = i32::from(prediction[idx]);
20515 if let Some((alpha_q3, ac_q3)) = cfl {
20516 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20517 }
20518 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20519 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20520 }
20521 }
20522 }
20523}
20524
20525/// Reads one plane's transform block, reconstructs it into `plane` at
20526/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
20527#[allow(clippy::too_many_arguments)]
20528
20529fn read_plane(
20530 dec: &mut SymbolDecoder,
20531 cdfs: &mut Cdfs,
20532 set: TxbSet,
20533 scan: &[u16],
20534 plane_idx: usize,
20535 around: (bool, bool, i32),
20536 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
20537 // it for every plane's `txb` lookup (it is what an intra transform type's
20538 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
20539 tx_mode: usize,
20540 predict_mode: usize,
20541 angle_delta: i32,
20542 reach: Reach,
20543 // lane-wave1 step (i): unread -- this reader records its write
20544 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
20545 // stays in the signature so every call site still proves the plane is
20546 // exclusively held while its coefficients are parsed.
20547 _plane: &mut PlaneBuf<'static>,
20548 x: usize,
20549 y: usize,
20550 side: usize,
20551 tx_side: usize,
20552 base_q_idx: u8,
20553 cfl: Option<(i32, CflSrc)>,
20554 filter_intra: Option<usize>,
20555 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
20556 // smaller than its own block (spec `get_txb_ctx_general`'s
20557 // `plane_bsize != tx_size` branch), carrying the already-looked-up
20558 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
20559 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
20560 // formula below.
20561 luma_skip_ctx: Option<usize>,
20562 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
20563 smooth_neighbor: bool,
20564 fctx: &crate::decode::FrameCtx,
20565) -> Result<Grid> {
20566 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
20567 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
20568 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
20569 // no chroma write is recorded. Return the all-zero grid the caller's
20570 // neighbour bookkeeping reads, without consuming a bit.
20571 if plane_idx > 0 && mono(fctx) {
20572 return Ok(Grid::Zero(side * side));
20573 }
20574 // lane-av1readcensus: the units read from here on are this plane's.
20575 set_census_plane(plane_idx);
20576 let skip_ctx = if plane_idx == 0 {
20577 luma_skip_ctx.unwrap_or(0)
20578 } else {
20579 // libaom `get_txb_ctx`: a chroma unit's context is
20580 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
20581 // plane block is bigger than the transform. Our chroma tables hold the
20582 // offset-7 rows first, so the caller adds 3 for the bigger-block case
20583 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
20584 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
20585 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
20586 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
20587 };
20588 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
20589 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
20590 // not by the block's ordinary `mode` (which is always DC_PRED whenever
20591 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
20592 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
20593 // filter-intra in AV1).
20594 let tx_mode = if plane_idx == 0 {
20595 fi_tx_row(tx_mode, filter_intra)
20596 } else {
20597 tx_mode
20598 };
20599 let mut coding = cdfs.txb(set, tx_mode);
20600 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
20601 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
20602 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
20603 // plane of a lossless block (the residual then goes through the WHT, so
20604 // the type only picks the scan, which is the default one).
20605 if lossless(fctx) {
20606 coding.tx_type = None;
20607 }
20608 // Luma's `default_tx_type` is only a fallback for the sizes whose
20609 // `TxbSet` carries no symbol at all (32-point and up), which the spec
20610 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
20611 // *never* its own coded symbol (`coding.tx_type` is always `None` for
20612 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
20613 // the plane's own predicted mode (`default_intra_tx_type`) -- except
20614 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
20615 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
20616 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
20617 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
20618 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
20619 // narrows there — only `Chroma32` and up do).
20620 let default_tx_type = if plane_idx == 0 || side >= 32 {
20621 TxType::DctDct
20622 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
20623 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
20624 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
20625 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
20626 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
20627 // [`read_inter_plane`]'s own `side < 32` guard).
20628 inherited
20629 } else {
20630 default_intra_tx_type(predict_mode as u8)
20631 };
20632 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
20633 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
20634 let default_tx_type = if lossless(fctx) {
20635 TxType::DctDct
20636 } else {
20637 default_tx_type
20638 };
20639 let (grid, tx_type) = read_coeffs(
20640 dec,
20641 &mut coding,
20642 scan,
20643 skip_ctx,
20644 dc_sign_ctx(around.2),
20645 default_tx_type,
20646 None,
20647 )?;
20648 note_chroma_class1(plane_idx, tx_type);
20649 if plane_idx == 0 {
20650 fctx.luma_tx_type.with(|c| c.set(tx_type));
20651 }
20652 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
20653 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
20654 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
20655 // guard also assumes.
20656 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
20657 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
20658 // keyed by that true size, not the coded corner's -- so the corner
20659 // goes into the top-left of a `side`-sized grid, not the reverse.
20660 let levels = extend_corner(grid, tx_side, tx_side, side, side);
20661 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
20662 let tx = TxParams {
20663 w: side,
20664 h: side,
20665 bit_depth: bit_depth(fctx),
20666 q_idx: block_q_idx(fctx),
20667 dc_delta,
20668 ac_delta,
20669 tx_type,
20670 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
20671 stride: 0,
20672 lossless: lossless(fctx),
20673 };
20674 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20675 let residual = tx.run(&levels);
20676 eprintln!(
20677 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
20678 &*levels,
20679 );
20680 }
20681 push_intra_tx(
20682 plane_idx,
20683 x,
20684 y,
20685 side,
20686 side,
20687 false,
20688 predict_mode,
20689 angle_delta,
20690 reach,
20691 tx,
20692 &levels,
20693 cfl,
20694 filter_intra,
20695 smooth_neighbor,
20696 fctx,
20697 );
20698 // `record`'s neighbour state only reads whether *the coded grid* (not the
20699 // residual) has nonzero entries, so the levels this function already
20700 // built are what it wants back -- both arms of the old `tx_side == side`
20701 // branch returned exactly that, one of them through a full `to_vec` copy
20702 // of the grid per intra transform unit (lane-coefbuf).
20703 Ok(levels)
20704}
20705
20706/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
20707/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
20708/// block's own rect shape, and the `rect` flag selects
20709/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
20710#[allow(clippy::too_many_arguments)]
20711fn push_intra_unit(
20712 plane: usize,
20713 x: usize,
20714 y: usize,
20715 w: usize,
20716 h: usize,
20717 mode: usize,
20718 angle_delta: i32,
20719 reach: Reach,
20720 residual: &[i32],
20721 cfl: Option<(i32, CflSrc)>,
20722 filter_intra: Option<usize>,
20723 smooth_neighbor: bool,
20724 fctx: &crate::decode::FrameCtx,
20725) {
20726 if w == h {
20727 push_intra(
20728 plane,
20729 x,
20730 y,
20731 w,
20732 mode,
20733 angle_delta,
20734 reach,
20735 residual,
20736 cfl,
20737 filter_intra,
20738 smooth_neighbor,
20739 fctx,
20740 );
20741 } else {
20742 push_intra_rect(
20743 plane,
20744 x,
20745 y,
20746 w,
20747 h,
20748 mode,
20749 angle_delta,
20750 reach,
20751 residual,
20752 cfl,
20753 filter_intra,
20754 smooth_neighbor,
20755 fctx,
20756 );
20757 }
20758}
20759
20760/// ONE RECT chroma transform unit of a square block's uv plane
20761/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
20762/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
20763/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
20764/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
20765/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
20766/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
20767/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
20768/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
20769/// predicted mode supplies the mode-derived default `tx_type` unless an armed
20770/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
20771/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
20772/// ([`read_plane`]'s `side >= 32` clamp).
20773#[allow(clippy::too_many_arguments)]
20774fn read_rect_chroma_unit(
20775 dec: &mut SymbolDecoder,
20776 cdfs: &mut Cdfs,
20777 set: TxbSet,
20778 scan: &[u16],
20779 w: usize,
20780 h: usize,
20781 plane_idx: usize,
20782 around: (bool, bool, i32),
20783 uv_predict_mode: usize,
20784 angle_delta_uv: i32,
20785 reach: Reach,
20786 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
20787 // the plane exclusively while the unit's coefficients are parsed.
20788 _plane: &mut PlaneBuf<'static>,
20789 x: usize,
20790 y: usize,
20791 // Signature parity with [`read_plane`]; the dequant reads its q index
20792 // off `block_q_idx(fctx)` like every other reader here.
20793 _base_q_idx: u8,
20794 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
20795 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
20796 // where `ctx_offset` is 10 when the plane block is bigger than the
20797 // transform and 7 otherwise. The port stores the offset-7 rows at
20798 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
20799 // (lane-av1-422b), so a unit SMALLER than its plane block passes
20800 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
20801 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
20802 // rect unit except in the chunk arms.
20803 chroma_skip_offset: Option<usize>,
20804 cfl: Option<(i32, CflSrc)>,
20805 smooth_neighbor_uv: bool,
20806 fctx: &crate::decode::FrameCtx,
20807) -> Result<Grid> {
20808 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
20809 hit!(CHROMA422_RECT_HITS);
20810 }
20811 let default_tx = if w.max(h) >= 32 {
20812 TxType::DctDct
20813 } else {
20814 fctx.intrabc_chroma_tx
20815 .with(std::cell::Cell::get)
20816 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8))
20817 };
20818 let mut coding = cdfs.txb(set, uv_predict_mode);
20819 let (levels, tx_type) = read_coeffs_rect(
20820 dec,
20821 &mut coding,
20822 scan,
20823 w,
20824 h,
20825 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
20826 dc_sign_ctx(around.2),
20827 default_tx,
20828 plane_idx,
20829 )?;
20830 let residual = dequant_and_inverse_typed_wh(
20831 &levels,
20832 w,
20833 h,
20834 crate::decode::bit_depth(fctx),
20835 block_q_idx(fctx),
20836 plane_q_delta(plane_idx, fctx).0,
20837 plane_q_delta(plane_idx, fctx).1,
20838 tx_type,
20839 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
20840 );
20841 push_intra_rect(
20842 plane_idx,
20843 x,
20844 y,
20845 w,
20846 h,
20847 uv_predict_mode,
20848 angle_delta_uv,
20849 reach,
20850 &residual,
20851 cfl,
20852 None,
20853 smooth_neighbor_uv,
20854 fctx,
20855 );
20856 Ok(levels)
20857}
20858
20859/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
20860/// three planes, reconstructing them into `y`/`u`/`v` and updating
20861/// `neighbours`.
20862#[allow(clippy::too_many_arguments)]
20863fn decode_block(
20864 dec: &mut SymbolDecoder,
20865 cdfs: &mut Cdfs,
20866 neighbours: &mut Neighbours,
20867 at: (usize, usize),
20868 side: usize,
20869 luma_set: TxbSet,
20870 chroma_set: TxbSet,
20871 luma_tx: usize,
20872 chroma_tx: usize,
20873 scans: (&[u16], &[u16]),
20874 cfl: bool,
20875 y: &mut PlaneBuf<'static>,
20876 u: &mut PlaneBuf<'static>,
20877 v: &mut PlaneBuf<'static>,
20878 base_q_idx: u8,
20879 enable_filter_intra: bool,
20880 allow_screen_content_tools: bool,
20881 allow_intrabc: bool,
20882 scan32: &[u16],
20883 scan16: &[u16],
20884 scan8: &[u16],
20885 scan4: &[u16],
20886 tx_select: bool,
20887 reduced_tx_set: bool,
20888 fctx: &crate::decode::FrameCtx,
20889) -> Result<()> {
20890 let (r, c) = at;
20891 let (px, py) = (c * SUB, r * SUB);
20892 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
20893 let palette_uv_cache = neighbours.palette_uv_cache(at);
20894 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
20895 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
20896 let (
20897 skip,
20898 mode,
20899 angle_delta_y,
20900 uv_mode,
20901 angle_delta_uv,
20902 alpha,
20903 filter_intra,
20904 palette_y,
20905 palette_uv,
20906 ) = read_intra_mode(
20907 dec,
20908 cdfs,
20909 nb_above_mode,
20910 nb_left_mode,
20911 cfl,
20912 side,
20913 enable_filter_intra,
20914 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
20915 allow_screen_content_tools,
20916 allow_intrabc,
20917 Some((palette_ctx, &palette_cache)),
20918 &palette_uv_cache,
20919 r * (SUB / MI),
20920 c * (SUB / MI),
20921 fctx,
20922 )?;
20923 if at_tile_left && palette_y.is_some() {
20924 hit!(PALETTE_TILE_LEFT_HITS);
20925 }
20926 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
20927 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
20928 // tables/scans are replaced by the 4x4 ones and the block always takes the
20929 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
20930 // sit at the TOP of the function -- before `read_intra_mode`, which is
20931 // where the block's own `segment_id` is read -- so a mixed frame resolved
20932 // every block's geometry against the PREVIOUS block's segment (a lossless
20933 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
20934 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
20935 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
20936 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
20937 // rewrite (which sat above `read_intra_mode`) rides along here -- same
20938 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
20939 // segment like the lossless arm above it.
20940 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
20941 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
20942 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
20943 let tx = if side >= 64 { 32 } else { side };
20944 let (set, scan): (TxbSet, &[u16]) = match tx {
20945 32 => (TxbSet::Chroma32, scan32),
20946 16 => (TxbSet::Chroma16, scan16),
20947 8 => (TxbSet::Chroma8, scan8),
20948 _ => (TxbSet::Chroma4, scan4),
20949 };
20950 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
20951 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20952 // lane-av1-422f: the uv plane block is the (side/2, side) rect
20953 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
20954 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
20955 // the RECT that fills the plane block, NOT the square transform of
20956 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
20957 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
20958 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
20959 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
20960 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
20961 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
20962 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
20963 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
20964 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
20965 let (tx_w, tx_h) = match side {
20966 4 => (4, 4),
20967 8 => (4, 8),
20968 16 => (8, 16),
20969 32 => (16, 32),
20970 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
20971 _ => (32, 32),
20972 };
20973 let (set, scan): (TxbSet, &[u16]) = match side {
20974 4 => (TxbSet::Chroma4, scan4),
20975 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
20976 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
20977 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
20978 _ => (TxbSet::Chroma32, scan32),
20979 };
20980 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
20981 } else {
20982 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
20983 };
20984 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
20985 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
20986 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
20987 // actual chroma-from-luma correlation, same as this decoder always did.
20988 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
20989 DC_PRED
20990 } else {
20991 uv_mode
20992 };
20993 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
20994 if smooth_neighbor {
20995 hit!(SMOOTH_LUMA_HITS);
20996 }
20997 let smooth_neighbor_uv =
20998 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
20999 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21000 eprintln!(
21001 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
21002 angle_delta_uv={angle_delta_uv}"
21003 );
21004 }
21005 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
21006 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
21007 // block, skipped or not. `logical_tx` is what the loop filter's edge
21008 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
21009 // transform size -- 64 even for the 64x64 corner-scanned case, spec
21010 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
21011 // which only differs from it at that one corner case.
21012 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
21013 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
21014 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
21015 // intrabc block reads NO tx-size symbol at all -- it takes
21016 // `maxRectTxSize` -- while every ordinary skipped intra block does read
21017 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
21018 // the tile from that block on (class `equal-range-means-unread`).
21019 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
21020 // tree instead (`read_var_tx_size`), the same syntax the inter block path
21021 // has always read -- libaom's `parse_decode_block` dispatches on
21022 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
21023 // intrabc block as inter.
21024 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
21025 // libaom `parse_decode_block`'s var-tx tree condition carries
21026 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
21027 // block inside a LOSSLESS segment of a mixed frame reads NO
21028 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
21029 // hands back TX_4X4. Invisible while every lossless frame was also
21030 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
21031 // is why the mixed frame is the first stream to reach it.
21032 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
21033 let intrabc_leaves = if intrabc_vartx {
21034 let max_tx = side.min(64);
21035 // `max_block_wide`/`max_block_high`: the frame's own mi grid
21036 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
21037 // right/bottom edge reads no split symbol for the units outside it.
21038 let mi_cols = 2 * y.true_width.div_ceil(8);
21039 let mi_rows = 2 * y.true_height.div_ceil(8);
21040 let side_mi = side / MI;
21041 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
21042 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
21043 let mut leaves = Vec::new();
21044 for row in (0..side_mi).step_by(max_tx / MI) {
21045 for col in (0..side_mi).step_by(max_tx / MI) {
21046 read_var_tx_size(
21047 dec,
21048 cdfs,
21049 neighbours,
21050 (mi_r, mi_c),
21051 side,
21052 (max_w_mi, max_h_mi),
21053 (max_tx, max_tx),
21054 0,
21055 row,
21056 col,
21057 &mut leaves,
21058 );
21059 }
21060 }
21061 hit!(INTRABC_VARTX_HITS);
21062 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
21063 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
21064 // longer refused -- the luma reconstruct below walks the tree's own
21065 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
21066 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
21067 // transform unit), so mixed sizes reconstruct at their own stride.
21068 // The counter marks the shape so a gate can prove a witness actually
21069 // carries a mixed tree and not merely another uniform one.
21070 let uniform = leaves.first().is_some_and(|f| {
21071 leaves
21072 .iter()
21073 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
21074 });
21075 if !uniform {
21076 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
21077 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
21078 eprintln!(
21079 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
21080 dv={intrabc_dv:?} leaves={leaves:?}"
21081 );
21082 }
21083 }
21084 Some(leaves)
21085 } else {
21086 None
21087 };
21088 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
21089 (tx, if tx == 64 { 32 } else { tx })
21090 } else if tx_select && !intrabc_skip_tx {
21091 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
21092 (resolved, if resolved == 64 { 32 } else { resolved })
21093 } else {
21094 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
21095 // TX_64X64, so a 128x128 block is always FOUR luma transform units
21096 // even with `tx_select` off -- the TU loop below, never the
21097 // single-unit path.
21098 (lossless_tx(side.min(64), fctx), luma_tx)
21099 };
21100 if tx_select && logical_tx < side && uv_mode != DC_PRED {
21101 hit!(SQ_CHROMA_TX_HITS);
21102 }
21103 let luma_set = if tx_select {
21104 txbset_for(logical_tx, reduced_tx_set)
21105 } else {
21106 luma_set
21107 };
21108 let luma_set = if intrabc_dv.is_some() {
21109 inter_txbset_for(logical_tx, reduced_tx_set)
21110 } else {
21111 luma_set
21112 };
21113 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
21114 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
21115 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
21116 let chroma_side = side >> ss_x(fctx);
21117 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
21118 // `side / 2` at 4:2:0.
21119 let chroma_height = side >> ss_y(fctx);
21120 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
21121 // frame's own pre-loop-filter reconstruction (all loop filters are off
21122 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
21123 // block vector, with the BILINEAR kernel libaom forces for intrabc --
21124 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
21125 // odd, which is exactly what the bilinear taps then interpolate.
21126 flush_recon(fctx, y, u, v);
21127 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
21128 let mut yb = vec![0u16; side * side];
21129 mc::predict_with_filter(
21130 &y.data,
21131 y.width,
21132 y.true_width,
21133 y.true_height,
21134 mv_to_q4(px, dv_col, 0),
21135 mv_to_q4(py, dv_row, 0),
21136 side,
21137 side,
21138 mc::InterpFilterKind::Bilinear,
21139 &mut yb,
21140 fctx,
21141 );
21142 let mut ub = vec![0u16; chroma_side * chroma_height];
21143 mc::predict_with_filter(
21144 &u.data,
21145 u.width,
21146 u.true_width,
21147 u.true_height,
21148 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21149 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21150 chroma_side,
21151 chroma_height,
21152 mc::InterpFilterKind::Bilinear,
21153 &mut ub,
21154 fctx,
21155 );
21156 let mut vb = vec![0u16; chroma_side * chroma_height];
21157 mc::predict_with_filter(
21158 &v.data,
21159 v.width,
21160 v.true_width,
21161 v.true_height,
21162 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21163 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21164 chroma_side,
21165 chroma_height,
21166 mc::InterpFilterKind::Bilinear,
21167 &mut vb,
21168 fctx,
21169 );
21170 (yb, ub, vb)
21171 });
21172 // A palette-Y block's own prediction is the reconstructed colour-index
21173 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
21174 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
21175 // parameter through this function's dozen `y.reconstruct`/`read_plane`
21176 // sites. A split luma transform (`tx_select && logical_tx != side`)
21177 // would need the map sliced per-TU -- untested against a real
21178 // `--enable-palette=1` stream this round, so refuse by name rather than
21179 // guess at the slicing (charter's own named-acceptable fallback).
21180 let palette_y_buf: Option<Vec<u16>> = palette_y
21181 .as_ref()
21182 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
21183 // lane-t900 r32: the intrabc luma prediction rides the very same
21184 // whole-block override slot, so the multi-TU loop below windows it per
21185 // transform unit exactly like a palette map -- setting it once up front
21186 // handed the whole `side`x`side` buffer to the FIRST unit and left every
21187 // later one predicting off block edges (the var-tx tree above is what
21188 // first makes `logical_tx < side` reachable for an intrabc block).
21189 let palette_y_buf = match &intrabc_bufs {
21190 Some((yb, _, _)) => Some(yb.clone()),
21191 None => palette_y_buf,
21192 };
21193 // With one luma transform unit the whole `side`x`side` map is the
21194 // prediction; with several (`logical_tx != side`) each unit takes its own
21195 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
21196 // below (lane-palette2 r7) -- setting the full-block buffer here would be
21197 // taken by the FIRST unit and indexed at the wrong stride.
21198 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
21199 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
21200 // `split_tx_skip` walk), so its map must be armed here even when the
21201 // transform is split. Gating the arm on `logical_tx == side` alone left a
21202 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
21203 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
21204 // key frame; class override-slot-on-one-arm). Neither prediction is
21205 // edge-derived, so the whole-block buffer at the block's own stride is
21206 // exactly what that single call wants.
21207 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
21208 // that reaches this block apart from one that never does (class
21209 // gate-blind-to-feature).
21210 if palette_y_buf.is_some() && skip && logical_tx < side {
21211 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
21212 }
21213 if let Some(buf) = &palette_y_buf
21214 && (logical_tx == side || skip)
21215 {
21216 set_palette_pred(buf.clone(), fctx);
21217 }
21218 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
21219 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
21220 // plane's own `reconstruct`/`read_plane` call below (never both planes at
21221 // once), since Y's own set-then-take already emptied the slot by the time
21222 // either of these run.
21223 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
21224 (
21225 puv.map
21226 .iter()
21227 .map(|&idx| puv.u_colors[idx as usize])
21228 .collect(),
21229 puv.map
21230 .iter()
21231 .map(|&idx| puv.v_colors[idx as usize])
21232 .collect(),
21233 )
21234 });
21235 // The chroma half of the intrabc prediction rides the same per-plane
21236 // override slot the UV-palette buffers do (set fresh before each plane's
21237 // own `reconstruct`/`read_plane` call below).
21238 let palette_uv_bufs = match &intrabc_bufs {
21239 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
21240 None => palette_uv_bufs,
21241 };
21242 if skip {
21243 // A skipped block codes no residual syntax at all (spec 5.11.34):
21244 // straight prediction, on every plane.
21245 //
21246 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
21247 // is skipped (only an INTER skip forces the largest transform), and
21248 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
21249 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
21250 // already written left/above of it inside this same block. Predicting
21251 // the whole `side`x`side` at once gives a different (uniformly off by
21252 // ~1) answer, which is exactly the residue this lane was chasing.
21253 // The palette/intrabc override path keeps the single-call shape (its
21254 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
21255 // untested for skip and unreachable in these streams).
21256 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
21257 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
21258 // per-unit prediction is keyed on the transform being smaller than
21259 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
21260 // narrower meaning (a READ split tx depth).
21261 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
21262 if split_tx_skip {
21263 if tx_select {
21264 hit!(SKIP_SPLIT_TX_HITS);
21265 }
21266 let n_axis = side / logical_tx;
21267 for tu_row in 0..n_axis {
21268 for tu_col in 0..n_axis {
21269 let tu_px = px + tu_col * logical_tx;
21270 let tu_py = py + tu_row * logical_tx;
21271 if tu_px >= y.true_width || tu_py >= y.true_height {
21272 continue;
21273 }
21274 let tu_reach = tu_reach(
21275 side,
21276 side,
21277 tu_col * logical_tx,
21278 tu_row * logical_tx,
21279 logical_tx,
21280 reach,
21281 px,
21282 py,
21283 y.width,
21284 y.height,
21285 fctx,
21286 );
21287 push_intra(
21288 0,
21289 tu_px,
21290 tu_py,
21291 logical_tx,
21292 mode,
21293 angle_delta_y,
21294 tu_reach,
21295 &ZERO_RESIDUAL[..logical_tx * logical_tx],
21296 None,
21297 filter_intra,
21298 smooth_neighbor,
21299 fctx,
21300 );
21301 }
21302 }
21303 } else {
21304 push_intra(
21305 0,
21306 px,
21307 py,
21308 side,
21309 mode,
21310 angle_delta_y,
21311 reach,
21312 &ZERO_RESIDUAL[..side * side],
21313 None,
21314 filter_intra,
21315 smooth_neighbor,
21316 fctx,
21317 );
21318 }
21319 let ac = alpha.map(|_| cfl_src(px, py, side));
21320 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
21321 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
21322 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
21323 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
21324 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
21325 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
21326 // reads ONE unit per plane, the whole plane block).
21327 let cn_cols = (chroma_side / chroma_tx).max(1);
21328 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21329 let luma_span_x = chroma_tx << ss_x(fctx);
21330 let luma_span_y = chroma_tx_h << ss_y(fctx);
21331 for cu_row in 0..cn_rows {
21332 for cu_col in 0..cn_cols {
21333 let cu_r = if cn_rows == 1 && cn_cols == 1 {
21334 reach
21335 } else {
21336 tu_reach_rect(
21337 side,
21338 side,
21339 cu_col * luma_span_x,
21340 cu_row * luma_span_y,
21341 luma_span_x,
21342 luma_span_y,
21343 reach,
21344 px,
21345 py,
21346 y.width,
21347 y.height,
21348 fctx,
21349 )
21350 };
21351 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21352 if let Some((ub, _)) = &palette_uv_bufs {
21353 set_palette_pred(ub.clone(), fctx);
21354 }
21355 push_intra_unit(
21356 1,
21357 cu_x,
21358 cu_y,
21359 chroma_tx,
21360 chroma_tx_h,
21361 uv_predict_mode,
21362 angle_delta_uv,
21363 cu_r,
21364 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21365 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21366 None,
21367 smooth_neighbor_uv,
21368 fctx,
21369 );
21370 if let Some((_, vb)) = &palette_uv_bufs {
21371 set_palette_pred(vb.clone(), fctx);
21372 }
21373 push_intra_unit(
21374 2,
21375 cu_x,
21376 cu_y,
21377 chroma_tx,
21378 chroma_tx_h,
21379 uv_predict_mode,
21380 angle_delta_uv,
21381 cu_r,
21382 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21383 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21384 None,
21385 smooth_neighbor_uv,
21386 fctx,
21387 );
21388 }
21389 }
21390 let luma_grid = vec![0i32; side * side];
21391 let u_grid = vec![0i32; chroma_side * chroma_side];
21392 let v_grid = vec![0i32; chroma_side * chroma_side];
21393 neighbours.record(
21394 at,
21395 side,
21396 mode,
21397 uv_predict_mode,
21398 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21399 );
21400 } else if logical_tx == side {
21401 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
21402 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
21403 // that arm was redundant -- and wrong at 128, where
21404 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
21405 // block is four units whether or not `tx_select` is on.
21406 // A single luma transform unit -- the old path, unchanged (including
21407 // the 64x64 corner case, `logical_tx == side == 64` with
21408 // `coeff_tx_side == 32`).
21409 let around = neighbours.around(at, side);
21410 let luma_grid = read_plane(
21411 dec,
21412 cdfs,
21413 luma_set,
21414 luma_scan,
21415 0,
21416 around[0],
21417 mode,
21418 mode,
21419 angle_delta_y,
21420 reach,
21421 y,
21422 px,
21423 py,
21424 side,
21425 coeff_tx_side,
21426 base_q_idx,
21427 None,
21428 filter_intra,
21429 None,
21430 smooth_neighbor,
21431 fctx,
21432 )?;
21433 let ac = alpha.map(|_| cfl_src(px, py, side));
21434 // Armed for exactly this block's two chroma reads (see
21435 // [`INTRABC_CHROMA_TX`]); the luma call above just set
21436 // [`LUMA_TX_TYPE`] to the type it coded.
21437 if intrabc_dv.is_some() {
21438 fctx.intrabc_chroma_tx
21439 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
21440 }
21441 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
21442 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
21443 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
21444 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
21445 // (every U, then every V) — the same loop the multi-TU arm runs.
21446 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
21447 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
21448 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
21449 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
21450 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
21451 // unit is the plane block's own rect.
21452 let cn_cols = (chroma_side / chroma_tx).max(1);
21453 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21454 let luma_span_x = chroma_tx << ss_x(fctx);
21455 let luma_span_y = chroma_tx_h << ss_y(fctx);
21456 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
21457 if chroma_tx == chroma_tx_h {
21458 if let Some((ub, _)) = &palette_uv_bufs {
21459 set_palette_pred(ub.clone(), fctx);
21460 }
21461 let u_grid = read_plane(
21462 dec,
21463 cdfs,
21464 chroma_set,
21465 scans.1,
21466 1,
21467 around[1],
21468 mode,
21469 uv_predict_mode,
21470 angle_delta_uv,
21471 reach,
21472 u,
21473 cpx,
21474 cpy,
21475 chroma_side,
21476 chroma_tx,
21477 base_q_idx,
21478 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21479 None,
21480 None,
21481 smooth_neighbor_uv,
21482 fctx,
21483 )?;
21484 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21485 eprintln!(
21486 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
21487 &u.data[cpy * u.width + cpx..][..chroma_side]
21488 );
21489 }
21490 if let Some((_, vb)) = &palette_uv_bufs {
21491 set_palette_pred(vb.clone(), fctx);
21492 }
21493 let v_grid = read_plane(
21494 dec,
21495 cdfs,
21496 chroma_set,
21497 scans.1,
21498 2,
21499 around[2],
21500 mode,
21501 uv_predict_mode,
21502 angle_delta_uv,
21503 reach,
21504 v,
21505 cpx,
21506 cpy,
21507 chroma_side,
21508 chroma_tx,
21509 base_q_idx,
21510 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21511 None,
21512 None,
21513 smooth_neighbor_uv,
21514 fctx,
21515 )?;
21516 (u_grid, v_grid, Vec::new())
21517 } else {
21518 // lane-av1-422f: the one unit is a RECT filling the plane
21519 // block -- the square-shaped [`read_plane`] cannot express
21520 // it, so both planes go through [`read_rect_chroma_unit`]
21521 // (U, then V, the same order the square arm reads). The
21522 // chroma context reads per chroma 4-px cell (see
21523 // [`Neighbours::around_mi_422_chroma`]).
21524 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
21525 if let Some((ub, _)) = &palette_uv_bufs {
21526 set_palette_pred(ub.clone(), fctx);
21527 }
21528 let u_grid = read_rect_chroma_unit(
21529 dec,
21530 cdfs,
21531 chroma_set,
21532 scans.1,
21533 chroma_tx,
21534 chroma_tx_h,
21535 1,
21536 chroma_around[1],
21537 uv_predict_mode,
21538 angle_delta_uv,
21539 reach,
21540 u,
21541 cpx,
21542 cpy,
21543 base_q_idx,
21544 None,
21545 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21546 smooth_neighbor_uv,
21547 fctx,
21548 )?;
21549 if let Some((_, vb)) = &palette_uv_bufs {
21550 set_palette_pred(vb.clone(), fctx);
21551 }
21552 let v_grid = read_rect_chroma_unit(
21553 dec,
21554 cdfs,
21555 chroma_set,
21556 scans.1,
21557 chroma_tx,
21558 chroma_tx_h,
21559 2,
21560 chroma_around[2],
21561 uv_predict_mode,
21562 angle_delta_uv,
21563 reach,
21564 v,
21565 cpx,
21566 cpy,
21567 base_q_idx,
21568 None,
21569 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21570 smooth_neighbor_uv,
21571 fctx,
21572 )?;
21573 (u_grid, v_grid, Vec::new())
21574 }
21575 } else {
21576 let chroma_ctx_offset = Some(3);
21577 let mut u_pass: Vec<Grid> = Vec::new();
21578 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21579 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21580 for plane_pass in 1..=2usize {
21581 let mut pass_idx = 0usize;
21582 for cu_row in 0..cn_rows {
21583 for cu_col in 0..cn_cols {
21584 let cu_mi = (
21585 mi_r + cu_row * (luma_span_y / MI),
21586 mi_c + cu_col * (luma_span_x / MI),
21587 );
21588 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21589 // lane-av1-422f: chroma-only loop; per-chroma-cell
21590 // above votes (see [`Neighbours::around_mi_422_chroma`]).
21591 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21592 } else {
21593 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21594 };
21595 let cu_reach = tu_reach_rect(
21596 side,
21597 side,
21598 cu_col * luma_span_x,
21599 cu_row * luma_span_y,
21600 luma_span_x,
21601 luma_span_y,
21602 reach,
21603 px,
21604 py,
21605 y.width,
21606 y.height,
21607 fctx,
21608 );
21609 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21610 if let Some((ub, vb)) = &palette_uv_bufs {
21611 let pbuf = if plane_pass == 1 { ub } else { vb };
21612 set_palette_pred(
21613 palette_window(
21614 pbuf,
21615 chroma_side,
21616 cu_col * chroma_tx,
21617 cu_row * chroma_tx_h,
21618 chroma_tx,
21619 chroma_tx_h,
21620 ),
21621 fctx,
21622 );
21623 }
21624 let buf: &mut PlaneBuf<'static> =
21625 if plane_pass == 1 { &mut *u } else { &mut *v };
21626 let cu_grid = read_plane(
21627 dec,
21628 cdfs,
21629 chroma_set,
21630 scans.1,
21631 plane_pass,
21632 cu_around[plane_pass],
21633 mode,
21634 uv_predict_mode,
21635 angle_delta_uv,
21636 cu_reach,
21637 buf,
21638 cu_x,
21639 cu_y,
21640 chroma_tx,
21641 chroma_tx,
21642 base_q_idx,
21643 alpha
21644 .zip(ac)
21645 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
21646 None,
21647 chroma_ctx_offset,
21648 smooth_neighbor_uv,
21649 fctx,
21650 )?;
21651 hit!(CHROMA_SPLIT_TX_HITS);
21652 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21653 hit!(CHROMA422_SQUARE_HITS);
21654 }
21655 // Immediately, so the next unit of this block reads this
21656 // one's coefficient context. `record` below stamps one
21657 // chroma state across the whole block; the replay after
21658 // it puts the per-unit state back.
21659 neighbours.record_mi_chroma(
21660 cu_mi,
21661 luma_span_x,
21662 luma_span_y,
21663 plane_pass,
21664 &cu_grid,
21665 );
21666 if plane_pass == 1 {
21667 u_pass.push(cu_grid);
21668 } else {
21669 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
21670 units.push((
21671 cu_mi,
21672 luma_span_x,
21673 luma_span_y,
21674 u_grid.clone(),
21675 cu_grid.clone(),
21676 ));
21677 last_grids = [u_grid, cu_grid];
21678 }
21679 pass_idx += 1;
21680 }
21681 }
21682 }
21683 (last_grids[0].clone(), last_grids[1].clone(), units)
21684 };
21685 fctx.intrabc_chroma_tx.with(|c| c.set(None));
21686 neighbours.record(
21687 at,
21688 side,
21689 mode,
21690 uv_predict_mode,
21691 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21692 );
21693 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
21694 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
21695 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
21696 }
21697 } else {
21698 // Several luma transform units, raster order (spec
21699 // `transform_block`'s loop): the block's resolved transform is
21700 // genuinely smaller than its own side, so each tile of it predicts
21701 // and codes independently, its own context read fresh off whatever
21702 // the earlier tiles in this same block already wrote -- the same
21703 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
21704 let n_axis = side / logical_tx;
21705 // lane-av1-422f: unit width/height per axis, like walk 2 above --
21706 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
21707 // chunk, the whole plane block.
21708 let cn_cols = (chroma_side / chroma_tx).max(1);
21709 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21710 let luma_span_x = chroma_tx << ss_x(fctx);
21711 let luma_span_y = chroma_tx_h << ss_y(fctx);
21712 // libaom's transform-block loop is over 64x64 luma "mu" chunks
21713 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
21714 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
21715 // before moving to the next one. Below 128 a block is a single chunk,
21716 // so this is byte-for-byte the all-luma-then-all-chroma order that has
21717 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
21718 // and reading all four luma units first desyncs the tile at the second
21719 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
21720 let nchunk = (side / 64).max(1);
21721 // `cn > 1` means the uv plane block is larger than the uv transform,
21722 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
21723 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
21724 let tpc = (n_axis / nchunk).max(1);
21725 let cpc_rows = (cn_rows / nchunk).max(1);
21726 let cpc_cols = (cn_cols / nchunk).max(1);
21727 // The block's luma transform units, raster order inside each mu
21728 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
21729 // tree's own leaf list -- mixed sizes included, exactly what libaom's
21730 // `decode_token_recon_block` token loop reconstructs (one
21731 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
21732 // while every other block's list is the uniform `logical_tx` grid
21733 // this loop has always walked, generated here in the same order.
21734 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
21735 if let Some(leaves) = &intrabc_leaves {
21736 for &(lr, lc, tw, _th) in leaves {
21737 let (off_y, off_x) = (lr * MI, lc * MI);
21738 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
21739 }
21740 } else {
21741 for tu_row in 0..n_axis {
21742 for tu_col in 0..n_axis {
21743 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
21744 tu_row * logical_tx,
21745 tu_col * logical_tx,
21746 logical_tx,
21747 ));
21748 }
21749 }
21750 }
21751 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21752 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21753 for ch_row in 0..nchunk {
21754 for ch_col in 0..nchunk {
21755 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
21756 // type of the co-located luma position (`av1_get_tx_type`,
21757 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
21758 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
21759 // luma unit covering it). Inside a mu chunk that is the chunk's
21760 // FIRST luma unit in raster order (the chunk origin is always the
21761 // first leaf's own origin). Captured right after that unit's read;
21762 // the single-TU arm below does the same for a whole-block unit.
21763 let mut first_leaf_tx: Option<TxType> = None;
21764 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
21765 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
21766 let tu_px = px + tu_off_x;
21767 let tu_py = py + tu_off_y;
21768 // Same libaom clip as `decode_rect_split`'s loop above; a
21769 // square block only hangs off the frame when the frame's mi
21770 // dimensions are odd at the block's own level.
21771 if tu_px >= y.true_width || tu_py >= y.true_height {
21772 continue;
21773 }
21774 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
21775 // A transform unit inside a block is NOT a block at that
21776 // position (lane-palette2 r12): `Reach::of` granted the
21777 // top-right 8x8 unit of a 16x16 D203 block bottom-left
21778 // pixels libaom refuses outright (`col_off > 0`), which is
21779 // the diagonal wedge seed 46 reconstructed wrong.
21780 let tu_reach = tu_reach(
21781 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
21782 fctx,
21783 );
21784 // This transform unit's own bsize (`tu_tx`) is smaller
21785 // than the block it sits in (`side`), so `txb_skip_ctx` is
21786 // the neighbour-magnitude table, not the lone-TU 0 (spec
21787 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
21788 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
21789 // An intrabc unit's CDF set and scan follow the unit's OWN
21790 // resolved size (`get_txsize_entropy_ctx` /
21791 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
21792 // uniform grid's precomputed pair already matches because
21793 // `tu_tx == logical_tx` there.
21794 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
21795 (
21796 inter_txbset_for(tu_tx, reduced_tx_set),
21797 scan_for(
21798 if tu_tx == 64 { 32 } else { tu_tx },
21799 scan32,
21800 scan16,
21801 scan8,
21802 scan4,
21803 ),
21804 )
21805 } else {
21806 (luma_set, luma_scan)
21807 };
21808 if let Some(buf) = &palette_y_buf {
21809 hit!(PALETTE_SPLIT_TX_HITS);
21810 let mut window = vec![0u16; tu_tx * tu_tx];
21811 for row in 0..tu_tx {
21812 let src = (tu_off_y + row) * side + tu_off_x;
21813 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
21814 }
21815 set_palette_pred(window, fctx);
21816 }
21817 let tu_grid = read_plane(
21818 dec,
21819 cdfs,
21820 tu_set,
21821 tu_scan,
21822 0,
21823 tu_around,
21824 mode,
21825 mode,
21826 angle_delta_y,
21827 tu_reach,
21828 y,
21829 tu_px,
21830 tu_py,
21831 tu_tx,
21832 // The unit's own COEFFICIENT grid, half its side at
21833 // TX_64X64 (a 64-point transform codes nothing past 32);
21834 // identical to `tu_tx` at every smaller size
21835 // (lane-sb128b r1).
21836 if tu_tx == 64 { 32 } else { tu_tx },
21837 base_q_idx,
21838 None,
21839 filter_intra,
21840 Some(tu_skip_ctx),
21841 smooth_neighbor,
21842 fctx,
21843 )?;
21844 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21845 eprintln!(
21846 "TRACE tu_bitpos mi=({},{}) tell={}",
21847 tu_mi.0,
21848 tu_mi.1,
21849 dec.debug_bitpos()
21850 );
21851 }
21852 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
21853 if first_leaf_tx.is_none() {
21854 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
21855 }
21856 }
21857 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
21858 // this still runs after every luma unit of the block.
21859 let ac = alpha.map(|_| cfl_src(px, py, side));
21860 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
21861 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
21862 // branch sets before its own chroma reads.
21863 if intrabc_dv.is_some() {
21864 if let Some(t) = first_leaf_tx {
21865 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
21866 }
21867 }
21868 // The block's uv plane block is `chroma_side` across but its uv
21869 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
21870 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
21871 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
21872 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
21873 // FOUR units (lane-sb128b r2) -- one per mu chunk.
21874 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
21875 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
21876 // the chunk, then every V unit. At one unit per plane per chunk --
21877 // every non-lossless case this decoder reaches -- that is the same
21878 // symbol order as the interleaved pair this loop used to read; a
21879 // lossless frame's 4x4 chroma units are the case where it differs
21880 // (lane-lossless2).
21881 let mut u_pass: Vec<Grid> = Vec::new();
21882 for plane_pass in 1..=2usize {
21883 let mut pass_idx = 0usize;
21884 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
21885 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
21886 // libaom `decode_reconstruct_tx`'s frame-edge clip
21887 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
21888 // >= max_blocks_wide` returns before ANY symbol is read): a
21889 // transform unit whose 4x4 origin sits outside the frame's mi
21890 // grid is not coded at all. The luma loop above carries the
21891 // same clip; its absence here read `txb_skip` (+coeffs) for
21892 // chroma units libaom never wrote -- the lossless 64x64 block
21893 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
21894 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
21895 // eight (lane-av1-loss64; 48 chroma units per plane in
21896 // aomdec's EC_COEFF census vs the 64 this loop read).
21897 // `max_block_wide/high` (av1_common_int.h:1565): the plane
21898 // block's pixel span (4:2:0 halves the luma span, clamped to
21899 // 4 by `set_plane_n4`) plus the negative overhang
21900 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
21901 // units.
21902 let span_mi = side / MI;
21903 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
21904 - mi_c as i32
21905 - span_mi as i32;
21906 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
21907 - mi_r as i32
21908 - span_mi as i32;
21909 // `max_block_wide/high` in chroma pixels: the plane block's
21910 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
21911 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
21912 // block's coded units and desynced the tile) plus the
21913 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
21914 // chroma-px scale is `MI >> ss` per mi.
21915 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
21916 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
21917 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
21918 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
21919 // lane-av1-422f: the shared halved formula in the `else` counts
21920 // the plane span in 4-px units through the 2-px-per-mi
21921 // subsampled height, which a 4:2:2 plane does not have (ss_y
21922 // 0) -- its span is the full luma mi count, so a keyed
21923 // formula clips the same units libaom's `max_block_high`
21924 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
21925 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
21926 // pre-ss form spelled).
21927 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21928 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
21929 } else {
21930 ((plane_px + over_h_px) >> 2).max(0) as usize
21931 };
21932 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
21933 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
21934 hit!(CHROMA_EDGE_TU_CLIP_HITS);
21935 continue;
21936 }
21937 // The chroma context arrays are indexed in LUMA mi, so this
21938 // unit's anchor is its own luma quadrant (lane-av1-422b: the
21939 // quadrant spans `chroma_tx << ss_x` luma px wide by
21940 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
21941 // one unit's quadrant is the whole block).
21942 let cu_mi = (
21943 mi_r + cu_row * (luma_span_y / MI),
21944 mi_c + cu_col * (luma_span_x / MI),
21945 );
21946 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21947 // lane-av1-422f: chroma-only loop; per-chroma-cell above
21948 // votes (see [`Neighbours::around_mi_422_chroma`]).
21949 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21950 } else {
21951 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21952 };
21953 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
21954 reach
21955 } else {
21956 tu_reach_rect(
21957 side,
21958 side,
21959 cu_col * luma_span_x,
21960 cu_row * luma_span_y,
21961 luma_span_x,
21962 luma_span_y,
21963 reach,
21964 px,
21965 py,
21966 y.width,
21967 y.height,
21968 fctx,
21969 )
21970 };
21971 let (cu_x, cu_y) =
21972 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21973 if let Some((ub, vb)) = &palette_uv_bufs {
21974 let pbuf = if plane_pass == 1 { ub } else { vb };
21975 set_palette_pred(
21976 palette_window(
21977 pbuf,
21978 chroma_side,
21979 cu_col * chroma_tx,
21980 cu_row * chroma_tx_h,
21981 chroma_tx,
21982 chroma_tx_h,
21983 ),
21984 fctx,
21985 );
21986 }
21987 let buf: &mut PlaneBuf<'static> =
21988 if plane_pass == 1 { &mut *u } else { &mut *v };
21989 let cu_grid = if chroma_tx == chroma_tx_h {
21990 read_plane(
21991 dec,
21992 cdfs,
21993 chroma_set,
21994 scans.1,
21995 plane_pass,
21996 cu_around[plane_pass],
21997 mode,
21998 uv_predict_mode,
21999 angle_delta_uv,
22000 cu_reach,
22001 buf,
22002 cu_x,
22003 cu_y,
22004 chroma_tx,
22005 chroma_tx,
22006 base_q_idx,
22007 alpha.zip(ac).map(|((au, av), ac)| {
22008 (if plane_pass == 1 { au } else { av }, ac)
22009 }),
22010 None,
22011 chroma_ctx_offset,
22012 smooth_neighbor_uv,
22013 fctx,
22014 )?
22015 } else {
22016 // lane-av1-422f: the whole plane block as one rect unit;
22017 // `chroma_ctx_offset` is `None` there (the unit covers
22018 // the plane block, so the offset-7 skip rows are right).
22019 read_rect_chroma_unit(
22020 dec,
22021 cdfs,
22022 chroma_set,
22023 scans.1,
22024 chroma_tx,
22025 chroma_tx_h,
22026 plane_pass,
22027 cu_around[plane_pass],
22028 uv_predict_mode,
22029 angle_delta_uv,
22030 cu_reach,
22031 buf,
22032 cu_x,
22033 cu_y,
22034 base_q_idx,
22035 None,
22036 alpha.zip(ac).map(|((au, av), ac)| {
22037 (if plane_pass == 1 { au } else { av }, ac)
22038 }),
22039 smooth_neighbor_uv,
22040 fctx,
22041 )?
22042 };
22043 if cn_rows * cn_cols > 1 {
22044 hit!(CHROMA_SPLIT_TX_HITS);
22045 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22046 hit!(CHROMA422_SQUARE_HITS);
22047 }
22048 // Immediately, so the NEXT unit of this same block reads
22049 // this one's coefficient context (libaom's chroma
22050 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
22051 // 1 from this left neighbour -- measured against aomdec).
22052 // The same writes are replayed after `record_split_luma`
22053 // below, which would otherwise clobber them whole-block.
22054 neighbours.record_mi_chroma(
22055 cu_mi,
22056 luma_span_x,
22057 luma_span_y,
22058 plane_pass,
22059 &cu_grid,
22060 );
22061 }
22062 if plane_pass == 1 {
22063 u_pass.push(cu_grid);
22064 } else {
22065 let u_grid =
22066 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22067 if cn_rows * cn_cols > 1 {
22068 units.push((
22069 cu_mi,
22070 luma_span_x,
22071 luma_span_y,
22072 u_grid.clone(),
22073 cu_grid.clone(),
22074 ));
22075 }
22076 last_grids = [u_grid, cu_grid];
22077 }
22078 pass_idx += 1;
22079 }
22080 }
22081 }
22082 }
22083 if intrabc_dv.is_some() {
22084 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22085 }
22086 }
22087 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
22088 // context write; at `cn > 1` the per-unit writes above are what the
22089 // next block reads, so they run after this (last writer wins).
22090 neighbours.record_split_luma(
22091 at,
22092 side,
22093 mode,
22094 uv_predict_mode,
22095 [&last_grids[0], &last_grids[1]],
22096 );
22097 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
22098 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
22099 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
22100 }
22101 }
22102 // Unconditional, `size == 0` for a non-palette block: clears any stale
22103 // neighbour palette state the same way [`Neighbours::record`] always
22104 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
22105 // (the split-luma-TU branch above always refuses before reaching here
22106 // when `palette_y` is `Some`, so it is never live for that branch).
22107 let (py_size, py_colors) = palette_y
22108 .as_ref()
22109 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22110 neighbours.record_palette_y(at, side, py_size, py_colors);
22111 let (puv_size, puv_colors) = palette_uv
22112 .as_ref()
22113 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22114 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
22115 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
22116 neighbours.fill_lf_grid(
22117 (r * (SUB / MI), c * (SUB / MI)),
22118 side / MI,
22119 logical_tx as u8,
22120 0,
22121 fctx,
22122 );
22123 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
22124 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
22125 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
22126 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
22127 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
22128 // intrabc block publish its BLOCK size instead, intrabc being the only
22129 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
22130 // stays the authority wherever one can appear; with `allow_intrabc` unset
22131 // it writes exactly what the grid already did.
22132 if allow_intrabc {
22133 set_txfm_ctxs(
22134 neighbours,
22135 (mi_r, mi_c),
22136 logical_tx,
22137 side / MI,
22138 side / MI,
22139 skip && intrabc_dv.is_some(),
22140 );
22141 }
22142 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
22143 Ok(())
22144}
22145
22146thread_local! {
22147 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
22148 /// root's HORZ arm, and 64x128 ones at its VERT arm.
22149 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22150 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22151 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
22152 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
22153 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
22154 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
22155 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
22156 /// inter frame) -- (128x64, 64x128).
22157 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
22158 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
22159 /// handed back var-tx leaves, so the per-transform-unit luma publication
22160 /// loop never ran and the block has to clear its own luma coefficient
22161 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
22162 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
22163 /// non-vacuous.
22164 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22165 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
22166 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
22167 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
22168 /// shape non-vacuous -- a stream that never codes one reads 0.
22169 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22170 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
22171 /// intra block re-stamped by the end-of-block replay
22172 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
22173 /// walk published, so every unit replays its own state after it). A
22174 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
22175 /// of them, so this reads 0 on any stream that never codes one -- the
22176 /// non-vacuity anchor for the replay's own gate.
22177 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22178 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
22179 /// height differs from the unit's own LUMA-MI height -- the signature of the
22180 /// width passed to both axes (`luma_span` where the in-loop stamp used
22181 /// `luma_span_h`). Zero on every stream this decoder admits: both
22182 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
22183 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
22184 /// at the sequence header (`stream::decode_frame`), so the arm is
22185 /// defensive until that format is ported. The counter turns a future
22186 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
22187 /// of silent mi-state corruption.
22188 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22189}
22190
22191/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
22192pub fn skip_vartx_luma_reset_hits() -> usize {
22193 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
22194}
22195
22196/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
22197pub(crate) fn intra128_lossless_hits() -> usize {
22198 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
22199}
22200
22201/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
22202pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
22203 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
22204}
22205
22206/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
22207/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
22208pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
22209 (
22210 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
22211 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
22212 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
22213 )
22214}
22215
22216/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
22217/// `decode_block_128rect`'s end-of-block replay) and
22218/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
22219/// not the unit's own), for a gate's own before/after delta.
22220pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
22221 (
22222 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
22223 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
22224 )
22225}
22226
22227/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
22228/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
22229/// `decode_inter_block`'s own rect path).
22230///
22231/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
22232/// transform unit, with the 128-specific geometry:
22233/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
22234/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
22235/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
22236/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
22237/// same CDF a 64x64 square block reads).
22238/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
22239/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
22240/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
22241/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
22242/// a chunk before moving to the next (the interleave lane-sb128b r3
22243/// measured at the 128x128 NONE root).
22244/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
22245/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
22246/// No CfL, no filter intra (both cap at 32x32) and no palette
22247/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
22248/// reader's own size gates already say so, and the guard below is defensive.
22249///
22250/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
22251/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
22252/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
22253/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
22254/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
22255/// units, plane-major inside each 64x64 mu chunk exactly as
22256/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
22257/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
22258/// this lane closed); the geometry and the unit walks below are normalized on
22259/// `lossless_frame`.
22260#[allow(clippy::too_many_arguments)]
22261fn decode_block_128rect(
22262 dec: &mut SymbolDecoder,
22263 cdfs: &mut Cdfs,
22264 neighbours: &mut Neighbours,
22265 at: (usize, usize),
22266 bw: usize,
22267 bh: usize,
22268 y: &mut PlaneBuf<'static>,
22269 u: &mut PlaneBuf<'static>,
22270 v: &mut PlaneBuf<'static>,
22271 base_q_idx: u8,
22272 enable_filter_intra: bool,
22273 allow_screen_content_tools: bool,
22274 tx_select: bool,
22275 reduced_tx_set: bool,
22276 fctx: &crate::decode::FrameCtx,
22277) -> Result<()> {
22278 let (r, c) = at;
22279 let (px, py) = (c * SUB, r * SUB);
22280 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
22281 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22282 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
22283 let palette_uv_cache = neighbours.palette_uv_cache(at);
22284 let (
22285 skip,
22286 mode,
22287 angle_delta_y,
22288 uv_mode,
22289 angle_delta_uv,
22290 alpha,
22291 filter_intra,
22292 palette_y,
22293 palette_uv,
22294 intrabc,
22295 ) = read_intra_mode_rect(
22296 dec,
22297 cdfs,
22298 nb_above_mode,
22299 nb_left_mode,
22300 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
22301 // 13-symbol no-CFL CDF here, never the 14-symbol one.
22302 false,
22303 true,
22304 bw,
22305 bh,
22306 enable_filter_intra,
22307 neighbours.skip_txfm_ctx(mi_r, mi_c),
22308 allow_screen_content_tools,
22309 Some((palette_ctx, &palette_cache)),
22310 &palette_uv_cache,
22311 mi_r,
22312 mi_c,
22313 fctx,
22314 )?;
22315 if let Some((dv_row, dv_col)) = intrabc {
22316 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
22317 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
22318 // from this frame's own reconstruction and runs the INTER residual
22319 // walk (`decode_token_recon_block`'s else arm) over it.
22320 return decode_intrabc_128rect(
22321 dec,
22322 cdfs,
22323 neighbours,
22324 (mi_r, mi_c),
22325 (bw, bh),
22326 skip,
22327 (dv_row, dv_col),
22328 y,
22329 u,
22330 v,
22331 base_q_idx,
22332 fctx,
22333 );
22334 }
22335 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
22336 return Err(unsupported(
22337 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
22338 their size gates caps at 64x64 or below, so none of these symbols exists there)",
22339 ));
22340 }
22341 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22342 DC_PRED
22343 } else {
22344 uv_mode
22345 };
22346 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22347 if smooth_neighbor {
22348 hit!(SMOOTH_LUMA_HITS);
22349 }
22350 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
22351 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
22352 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
22353 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
22354 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
22355 // before the symbol is even considered (`decodeframe.c:141`) and
22356 // `read_tx_size` returns `TX_4X4` before it looks at anything
22357 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
22358 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
22359 let lossless_frame = lossless(fctx);
22360 let in_inter = fctx
22361 .intra_in_inter_mode
22362 .with(std::cell::Cell::get)
22363 .is_some();
22364 let depth = if tx_select && !lossless_frame {
22365 // lane-inter128intra r1: `get_tx_size_context` compares the bands
22366 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
22367 // TX_64X64 for every 128-axis block, hence the `min(64)`.
22368 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
22369 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
22370 } else {
22371 0
22372 };
22373 if depth != 0 {
22374 hit!(TX_DEPTH_HITS);
22375 }
22376 hit_do! {
22377 INTRA_SB128_DEPTH_HITS.with(|c| {
22378 let mut h = c.get();
22379 h[depth.min(2)] += 1;
22380 c.set(h);
22381 });
22382 }
22383 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
22384 if lossless_frame {
22385 hit!(INTRA128_LOSSLESS_HITS);
22386 }
22387 // A 64-point transform codes nothing past its low 32 coefficients.
22388 let coeff_tx_side = logical_tx.min(32);
22389 let luma_set = if lossless_frame {
22390 TxbSet::Luma4
22391 } else {
22392 txbset_for(logical_tx, reduced_tx_set)
22393 };
22394 let luma_scan = default_scan(coeff_tx_side);
22395 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
22396 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
22397 let chroma_tx = if lossless_frame { 4 } else { 32 };
22398 let chroma_set = if lossless_frame {
22399 TxbSet::Chroma4
22400 } else {
22401 TxbSet::Chroma32
22402 };
22403 let chroma_scan = default_scan(chroma_tx);
22404 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22405 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
22406 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
22407 let (nch_x, nch_y) = (bw / 64, bh / 64);
22408 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
22409 // `decode_token_recon_block` clips each vector's walk to
22410 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
22411 // codes nothing.
22412 let mi_cols = 2 * y.true_width.div_ceil(8);
22413 let mi_rows = 2 * y.true_height.div_ceil(8);
22414 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
22415 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
22416 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
22417 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
22418 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
22419 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
22420 debug_assert!(
22421 lossless_frame
22422 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
22423 == (
22424 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
22425 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
22426 )
22427 );
22428 let tpc = 64 / logical_tx;
22429 let zero_tu = vec![0i32; logical_tx * logical_tx];
22430 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
22431 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22432 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
22433 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
22434 // every chunk shares this luma span (2 chroma pixels per luma unit).
22435 let luma_span = chroma_tx << ss_x(fctx);
22436 let luma_span_h = chroma_tx << ss_y(fctx);
22437 for ch_row in 0..nch_y {
22438 for ch_col in 0..nch_x {
22439 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
22440 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
22441 let tu_mi = (
22442 mi_r + tu_row * (logical_tx / MI),
22443 mi_c + tu_col * (logical_tx / MI),
22444 );
22445 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
22446 // libaom clips the transform loop to
22447 // `max_blocks_wide/high`: a unit whose top-left sample is
22448 // outside the frame is never coded.
22449 if tu_px >= y.true_width || tu_py >= y.true_height {
22450 continue;
22451 }
22452 // Edge availability of a unit INSIDE a block, with the
22453 // 128 geometry -- `has_top_right` is false for a block
22454 // whose largest side is > 64, which [`Reach::of_rect`]
22455 // already answered for the block and [`tu_reach`] carries
22456 // down to the units on its own top row.
22457 let tu_r = tu_reach(
22458 bw,
22459 bh,
22460 tu_col * logical_tx,
22461 tu_row * logical_tx,
22462 logical_tx,
22463 reach,
22464 px,
22465 py,
22466 y.width,
22467 y.height,
22468 fctx,
22469 );
22470 if skip {
22471 push_intra(
22472 0,
22473 tu_px,
22474 tu_py,
22475 logical_tx,
22476 mode,
22477 angle_delta_y,
22478 tu_r,
22479 &zero_tu,
22480 None,
22481 None,
22482 smooth_neighbor,
22483 fctx,
22484 );
22485 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
22486 continue;
22487 }
22488 // The unit is smaller than its block, so `txb_skip_ctx`
22489 // is the neighbour-magnitude table, never the lone-TU 0.
22490 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
22491 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
22492 let tu_grid = read_plane(
22493 dec,
22494 cdfs,
22495 luma_set,
22496 &luma_scan,
22497 0,
22498 tu_around,
22499 mode,
22500 mode,
22501 angle_delta_y,
22502 tu_r,
22503 y,
22504 tu_px,
22505 tu_py,
22506 logical_tx,
22507 coeff_tx_side,
22508 base_q_idx,
22509 None,
22510 None,
22511 Some(tu_skip_ctx),
22512 smooth_neighbor,
22513 fctx,
22514 )?;
22515 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
22516 }
22517 }
22518 // Transform units per axis inside this mu chunk's chroma span:
22519 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
22520 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
22521 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
22522 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
22523 // chroma plane block is 32x64 there, so the two axes' counts
22524 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
22525 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
22526 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
22527 // libaom's per-chunk `unit_width/height` (plane-mi units of the
22528 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
22529 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
22530 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
22531 let stepc = (chroma_tx / 4).max(1);
22532 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
22533 // unit of the chunk, then every V unit. At one unit per plane per
22534 // chunk (every non-lossless 128-axis block) that is the same
22535 // symbol order the interleaved pair used to read; a lossless
22536 // frame's 4x4 chroma units are where it becomes observable.
22537 for plane_pass in 1..=2usize {
22538 for ci_row in 0..cn_h {
22539 for ci_col in 0..cn {
22540 // The clamp strides are the CHUNK's chroma mi extent
22541 // per axis: 16 luma mi >> the axis's own ss.
22542 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
22543 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
22544 {
22545 continue;
22546 }
22547 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
22548 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
22549 let cu_mi = (
22550 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
22551 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
22552 );
22553 let cu_r = tu_reach_rect(
22554 bw,
22555 bh,
22556 ch_col * 64 + ci_col * luma_span,
22557 ch_row * 64 + ci_row * luma_span_h,
22558 luma_span,
22559 luma_span_h,
22560 reach,
22561 px,
22562 py,
22563 y.width,
22564 y.height,
22565 fctx,
22566 );
22567 if skip {
22568 push_intra(
22569 plane_pass,
22570 cu_x,
22571 cu_y,
22572 chroma_tx,
22573 uv_predict_mode,
22574 angle_delta_uv,
22575 cu_r,
22576 &zero_cu,
22577 None,
22578 None,
22579 smooth_neighbor_uv,
22580 fctx,
22581 );
22582 continue;
22583 }
22584 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
22585 let buf: &mut PlaneBuf<'static> =
22586 if plane_pass == 1 { &mut *u } else { &mut *v };
22587 let grid = read_plane(
22588 dec,
22589 cdfs,
22590 chroma_set,
22591 &chroma_scan,
22592 plane_pass,
22593 cu_around[plane_pass],
22594 mode,
22595 uv_predict_mode,
22596 angle_delta_uv,
22597 cu_r,
22598 buf,
22599 cu_x,
22600 cu_y,
22601 chroma_tx,
22602 chroma_tx,
22603 base_q_idx,
22604 None,
22605 None,
22606 Some(3),
22607 smooth_neighbor_uv,
22608 fctx,
22609 )?;
22610 last_grids[plane_pass - 1] = grid.clone();
22611 // Immediately, so the NEXT unit of this same block
22612 // reads this one's coefficient context; replayed after
22613 // `record_split_luma_rect` below, which would otherwise
22614 // clobber them whole-block.
22615 neighbours.record_mi_chroma(
22616 cu_mi,
22617 luma_span,
22618 luma_span_h,
22619 plane_pass,
22620 &grid,
22621 );
22622 units.push((plane_pass, cu_mi, grid));
22623 }
22624 }
22625 }
22626 if !skip {
22627 hit!(CHROMA_SPLIT_TX_HITS);
22628 }
22629 }
22630 }
22631 if skip {
22632 neighbours.record_rect(
22633 at,
22634 bw,
22635 bh,
22636 mode,
22637 uv_predict_mode,
22638 &[
22639 &ZERO_RESIDUAL[..bw * bh],
22640 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22641 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22642 ],
22643 );
22644 } else {
22645 neighbours.record_split_luma_rect(
22646 at,
22647 bw,
22648 bh,
22649 mode,
22650 uv_predict_mode,
22651 [&last_grids[0], &last_grids[1]],
22652 );
22653 // lane-av1-128rectspan: the replay must re-stamp each unit over the
22654 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
22655 // height drives `left[]` and its width `above[]`, and the walk used
22656 // the per-axis `luma_span_h`. Passing the width on both axes doubled
22657 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
22658 // rows below the block on the last unit of a 128x64/64x128 strip and
22659 // smearing a neighbour chunk's unit over its neighbour's rows.
22660 //
22661 // DEFENSIVE at the decoder's current capability set: both admitted
22662 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
22663 // (0,0)), so the two spans are equal and this line is a no-op on
22664 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
22665 // format where they differ -- is refused by name at the sequence
22666 // header, so the arm is unreachable there. It stays per-axis because
22667 // the walk it replays is per-axis, and a 4:2:2 port must not have to
22668 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
22669 // day that changes.
22670 if luma_span != luma_span_h {
22671 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
22672 }
22673 for (plane, cu_mi, grid) in &units {
22674 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
22675 hit!(SB128RECT_CHROMA_REPLAY_HITS);
22676 }
22677 }
22678 // No palette exists at this size; the unconditional stamp clears any
22679 // stale neighbour palette state, as every other block path does.
22680 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
22681 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
22682 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
22683 neighbours.fill_lf_grid_rect(
22684 (mi_r, mi_c),
22685 bw / MI,
22686 bh / MI,
22687 logical_tx as u8,
22688 logical_tx as u8,
22689 0,
22690 fctx,
22691 );
22692 if in_inter || allow_intrabc_frame(fctx) {
22693 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
22694 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
22695 // inter frame, intra ones included: an intra block stamps its
22696 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
22697 // A key frame reads those bands only when it allows intrabc
22698 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
22699 // stamps here too -- lane-av1-intrabc r3.
22700 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
22701 }
22702 if in_inter {
22703 hit_do! {
22704 INTRA128_IN_INTER_HITS.with(|c| {
22705 let mut h = c.get();
22706 h[usize::from(bw < bh)] += 1;
22707 c.set(h);
22708 });
22709 }
22710 } else if bw > bh {
22711 hit!(INTRA_SB128_HORZ_HITS);
22712 } else {
22713 hit!(INTRA_SB128_VERT_HITS);
22714 }
22715 Ok(())
22716}
22717
22718/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
22719/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
22720/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
22721/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
22722/// just-decoded mode, not the enclosing slot's stale one, is the true
22723/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
22724/// units, which is what its coefficient context (finer than [`SUB`]) is read
22725/// at. Returns the mode this leaf decoded, for the caller's own
22726/// `prev_leaf`/final mode-writeback bookkeeping.
22727#[allow(clippy::too_many_arguments)]
22728/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
22729/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
22730/// `above_mode[col]`, and its true above neighbour is the mi directly above
22731/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
22732/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
22733/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
22734/// (bottom-right) into both, as this path did, is right only when all four
22735/// leaves happen to share a mode. `done` may be short at the true frame edge
22736/// (the straddle caller filters positions off the frame), so each side falls
22737/// back to the last leaf actually decoded.
22738fn write_back_split_modes(
22739 neighbours: &mut Neighbours,
22740 done: &[((usize, usize), usize)],
22741 parent_mi: (usize, usize),
22742 slot: (usize, usize),
22743) {
22744 let (sr, sc) = slot;
22745 let Some(&(_, last)) = done.last() else {
22746 return;
22747 };
22748 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
22749 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
22750 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
22751}
22752
22753fn decode_leaf8(
22754 dec: &mut SymbolDecoder,
22755 cdfs: &mut Cdfs,
22756 neighbours: &mut Neighbours,
22757 outer_at: (usize, usize),
22758 leaf_mi: (usize, usize),
22759 scans: (&[u16], &[u16]),
22760 prev_leaf: Option<((usize, usize), usize)>,
22761 y: &mut PlaneBuf<'static>,
22762 u: &mut PlaneBuf<'static>,
22763 v: &mut PlaneBuf<'static>,
22764 base_q_idx: u8,
22765 enable_filter_intra: bool,
22766 allow_screen_content_tools: bool,
22767 allow_intrabc: bool,
22768 tx_select: bool,
22769 reduced_tx_set: bool,
22770 fctx: &crate::decode::FrameCtx,
22771) -> Result<usize> {
22772 let (r, c) = outer_at;
22773 // lane-modectx r1: the group's own availability-correct fallback pair, not
22774 // the raw coarse bands (which leak across a tile edge -- see
22775 // `modes_above_left`).
22776 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
22777 if let Some(((pr, pc), pmode)) = prev_leaf {
22778 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
22779 above_mode = pmode;
22780 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
22781 left_mode = pmode;
22782 }
22783 }
22784 // The mi-exact neighbour wins over both the coarse 16x16 slot and
22785 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
22786 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
22787 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
22788 // lane-rectsplitx r2 swept this arm into
22789 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
22790 // "no neighbour" at a tile edge, where the coarse cell holds the block
22791 // above/left of it inside the same 16x16.
22792 let (above_mode, left_mode) =
22793 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
22794 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
22795 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
22796 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
22797 // this leaf's `smooth_neighbor` is built from -- passing `false` here
22798 // filtered a directional chroma block's edge at the wrong strength
22799 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
22800 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
22801 // with the coarse [`SUB`] slot as the fallback when no block recorded
22802 // that exact mi cell.
22803 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
22804 if smooth_neighbor {
22805 hit!(SMOOTH_LUMA_HITS);
22806 }
22807 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
22808 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
22809 // `decode_block` caller at 16x16 and up.
22810 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
22811 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
22812 // `read_palette_mode_info`), at its REAL mi position -- passing
22813 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
22814 // moment a real 8x8 palette block fired, which is where every 8-bit
22815 // `--tune-content=screen --min-partition-size=8` stream stopped.
22816 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
22817 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
22818 let (
22819 skip,
22820 mode,
22821 angle_delta_y,
22822 uv_mode,
22823 angle_delta_uv,
22824 alpha,
22825 filter_intra,
22826 palette_y,
22827 palette_uv,
22828 ) = read_intra_mode(
22829 dec,
22830 cdfs,
22831 above_mode,
22832 left_mode,
22833 true,
22834 8,
22835 enable_filter_intra,
22836 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
22837 allow_screen_content_tools,
22838 allow_intrabc,
22839 Some((palette_ctx, &palette_cache)),
22840 &palette_uv_cache,
22841 leaf_mi.0,
22842 leaf_mi.1,
22843 fctx,
22844 )?;
22845 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
22846 // `read_intra_mode` and then decoded the block as if it were ordinary
22847 // intra. libaom's `is_inter_block` counts an intrabc block
22848 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
22849 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
22850 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
22851 // same value with a different interval, so the tile desynced at the very
22852 // next symbol (class `wrong-alphabet-same-value`). Everything below
22853 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
22854 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
22855 if intrabc_dv.is_some() {
22856 hit!(LEAF8_INTRABC_HITS);
22857 }
22858 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
22859 // index map, mapped through the base colours, IS the block's prediction --
22860 // carried to the next `reconstruct`/`read_plane` through the same
22861 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
22862 let palette_y_buf: Option<Vec<u16>> = palette_y
22863 .as_ref()
22864 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
22865 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
22866 (
22867 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
22868 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
22869 )
22870 });
22871 let (pal_y_size, pal_y_colors) = palette_y
22872 .as_ref()
22873 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22874 let (pal_uv_size, pal_uv_colors) = palette_uv
22875 .as_ref()
22876 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22877 if palette_y.is_some() || palette_uv.is_some() {
22878 hit!(PALETTE_LEAF8_HITS);
22879 }
22880 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22881 DC_PRED
22882 } else {
22883 uv_mode
22884 };
22885 neighbours.above_uv_mode[c] = uv_predict_mode;
22886 neighbours.left_uv_mode[r] = uv_predict_mode;
22887 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
22888 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
22889 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
22890 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
22891 // transform units, same raster-order per-TU pattern `decode_block`'s
22892 // multi-TU branch runs).
22893 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
22894 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
22895 // intrabc block, so a SKIPPED one takes the largest transform and an
22896 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
22897 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
22898 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
22899 // `parse_decode_block`'s tree condition carries
22900 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
22901 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
22902 // `read_tx_size`'s first line (lane-av1mixloss).
22903 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
22904 let mut leaves = Vec::new();
22905 let mi_cols = 2 * y.true_width.div_ceil(8);
22906 let mi_rows = 2 * y.true_height.div_ceil(8);
22907 read_var_tx_size(
22908 dec,
22909 cdfs,
22910 neighbours,
22911 leaf_mi,
22912 8,
22913 (
22914 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
22915 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
22916 ),
22917 (8, 8),
22918 0,
22919 0,
22920 0,
22921 &mut leaves,
22922 );
22923 hit!(INTRABC_VARTX_HITS);
22924 leaves.first().map_or(8, |l| l.2)
22925 } else if tx_select && intrabc_dv.is_none() {
22926 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
22927 } else {
22928 // lane-lossless: TX_4X4 on a lossless frame, no symbol
22929 // (libaom `read_tx_size`).
22930 lossless_tx(8, fctx)
22931 };
22932 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
22933 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
22934 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22935 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
22936 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
22937 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
22938 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
22939 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
22940 // TX_4X8): one txb_skip + one scan per plane in the
22941 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
22942 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
22943 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
22944 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
22945 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
22946 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
22947 let (csz, cset, cscan) = if chroma_444 {
22948 (8usize, TxbSet::Chroma8, scans.0)
22949 } else {
22950 (4usize, TxbSet::Chroma4, scans.1)
22951 };
22952 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
22953 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
22954 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
22955 // the full-pel block vector, with the BILINEAR kernel libaom forces.
22956 flush_recon(fctx, y, u, v);
22957 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
22958 let mut yb = vec![0u16; 8 * 8];
22959 mc::predict_with_filter(
22960 &y.data,
22961 y.width,
22962 y.true_width,
22963 y.true_height,
22964 mv_to_q4(px, dv_col, 0),
22965 mv_to_q4(py, dv_row, 0),
22966 8,
22967 8,
22968 mc::InterpFilterKind::Bilinear,
22969 &mut yb,
22970 fctx,
22971 );
22972 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
22973 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
22974 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
22975 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
22976 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
22977 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
22978 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
22979 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
22980 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
22981 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
22982 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
22983 // so all three heal with this one sizing.
22984 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
22985 let mut ub = vec![0u16; cw * ch];
22986 mc::predict_with_filter(
22987 &u.data,
22988 u.width,
22989 u.true_width,
22990 u.true_height,
22991 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22992 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22993 cw,
22994 ch,
22995 mc::InterpFilterKind::Bilinear,
22996 &mut ub,
22997 fctx,
22998 );
22999 let mut vb = vec![0u16; cw * ch];
23000 mc::predict_with_filter(
23001 &v.data,
23002 v.width,
23003 v.true_width,
23004 v.true_height,
23005 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23006 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23007 cw,
23008 ch,
23009 mc::InterpFilterKind::Bilinear,
23010 &mut vb,
23011 fctx,
23012 );
23013 (yb, ub, vb)
23014 });
23015 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
23016 // `decode_block` uses: set fresh right before each plane's own
23017 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
23018 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
23019 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
23020 // first shape that reaches that loop with an override set).
23021 let palette_y_buf = match &intrabc_bufs {
23022 Some((yb, _, _)) => Some(yb.clone()),
23023 None => palette_y_buf,
23024 };
23025 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
23026 // `decode_block` does the same for its own `palette_uv_bufs`
23027 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
23028 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
23029 // chroma reads with the override unset: the unit predicted INTRA from
23030 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
23031 // R5 first differing pixel U(184,4), block mi (2,92).
23032 let palette_uv_bufs = match &intrabc_bufs {
23033 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
23034 None => palette_uv_bufs,
23035 };
23036 let (luma_grid, u_grid, v_grid);
23037 if skip {
23038 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
23039 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
23040 // transform units, each off the units already written left/above of
23041 // it inside this same leaf -- an intra block's transform size is read
23042 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
23043 // A palette block's prediction is the whole-block index map, never
23044 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
23045 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
23046 // even when `tx_depth` resolved to TX_4X4.
23047 if resolved == 4 && palette_y_buf.is_none() {
23048 hit!(SKIP_SPLIT_TX_HITS);
23049 for tu_row in 0..2 {
23050 for tu_col in 0..2 {
23051 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
23052 if tu_px >= y.true_width || tu_py >= y.true_height {
23053 continue;
23054 }
23055 let tu_reach = tu_reach(
23056 8,
23057 8,
23058 tu_col * 4,
23059 tu_row * 4,
23060 4,
23061 reach,
23062 px,
23063 py,
23064 y.width,
23065 y.height,
23066 fctx,
23067 );
23068 push_intra(
23069 0,
23070 tu_px,
23071 tu_py,
23072 4,
23073 mode,
23074 angle_delta_y,
23075 tu_reach,
23076 &ZERO_RESIDUAL[..16],
23077 None,
23078 filter_intra,
23079 smooth_neighbor,
23080 fctx,
23081 );
23082 }
23083 }
23084 } else {
23085 if let Some(buf) = &palette_y_buf {
23086 set_palette_pred(buf.clone(), fctx);
23087 }
23088 push_intra(
23089 0,
23090 px,
23091 py,
23092 8,
23093 mode,
23094 angle_delta_y,
23095 reach,
23096 &ZERO_RESIDUAL[..64],
23097 None,
23098 filter_intra,
23099 smooth_neighbor,
23100 fctx,
23101 );
23102 }
23103 let ac = alpha.map(|_| cfl_src(px, py, 8));
23104 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
23105 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
23106 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
23107 // skip-arm rule); no coefficient symbol exists, so the entropy
23108 // context never enters the rect read.
23109 if chroma_422 {
23110 u_grid = leaf8_chroma422_unit(
23111 dec,
23112 cdfs,
23113 (false, false, 0),
23114 uv_predict_mode,
23115 angle_delta_uv,
23116 reach,
23117 1,
23118 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23119 true,
23120 intrabc_bufs
23121 .as_ref()
23122 .map(|(_, ub, _)| ub.clone())
23123 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23124 u,
23125 cpx,
23126 cpy,
23127 smooth_neighbor_uv,
23128 fctx,
23129 )?;
23130 v_grid = leaf8_chroma422_unit(
23131 dec,
23132 cdfs,
23133 (false, false, 0),
23134 uv_predict_mode,
23135 angle_delta_uv,
23136 reach,
23137 2,
23138 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23139 true,
23140 intrabc_bufs
23141 .as_ref()
23142 .map(|(_, _, vb)| vb.clone())
23143 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23144 v,
23145 cpx,
23146 cpy,
23147 smooth_neighbor_uv,
23148 fctx,
23149 )?;
23150 luma_grid = Grid::Zero(64);
23151 } else {
23152 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
23153 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
23154 // plane), so a skipped leaf predicts per unit -- each from its own
23155 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
23156 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
23157 // chroma plane block is 8x8), and intrabc/palette keep the
23158 // whole-plane-block prediction they already run. The guard also
23159 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
23160 let chroma_units_444 =
23161 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
23162 if let Some((_, ub, _)) = &intrabc_bufs {
23163 set_palette_pred(ub.clone(), fctx);
23164 } else if let Some((ub, _)) = &palette_uv_bufs {
23165 set_palette_pred(ub.clone(), fctx);
23166 }
23167 if chroma_units_444 {
23168 for cu_row in 0..2 {
23169 for cu_col in 0..2 {
23170 let cu_reach = tu_reach(
23171 8,
23172 8,
23173 cu_col * 4,
23174 cu_row * 4,
23175 4,
23176 reach,
23177 px,
23178 py,
23179 y.width,
23180 y.height,
23181 fctx,
23182 );
23183 push_intra(
23184 1,
23185 cpx + cu_col * 4,
23186 cpy + cu_row * 4,
23187 4,
23188 uv_predict_mode,
23189 angle_delta_uv,
23190 cu_reach,
23191 &ZERO_RESIDUAL[..16],
23192 None,
23193 None,
23194 smooth_neighbor_uv,
23195 fctx,
23196 );
23197 }
23198 }
23199 } else {
23200 push_intra(
23201 1,
23202 cpx,
23203 cpy,
23204 csz,
23205 uv_predict_mode,
23206 angle_delta_uv,
23207 reach,
23208 &ZERO_RESIDUAL[..csz * csz],
23209 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23210 None,
23211 smooth_neighbor_uv,
23212 fctx,
23213 );
23214 }
23215 if let Some((_, _, vb)) = &intrabc_bufs {
23216 set_palette_pred(vb.clone(), fctx);
23217 } else if let Some((_, vb)) = &palette_uv_bufs {
23218 set_palette_pred(vb.clone(), fctx);
23219 }
23220 if chroma_units_444 {
23221 for cu_row in 0..2 {
23222 for cu_col in 0..2 {
23223 let cu_reach = tu_reach(
23224 8,
23225 8,
23226 cu_col * 4,
23227 cu_row * 4,
23228 4,
23229 reach,
23230 px,
23231 py,
23232 y.width,
23233 y.height,
23234 fctx,
23235 );
23236 push_intra(
23237 2,
23238 cpx + cu_col * 4,
23239 cpy + cu_row * 4,
23240 4,
23241 uv_predict_mode,
23242 angle_delta_uv,
23243 cu_reach,
23244 &ZERO_RESIDUAL[..16],
23245 None,
23246 None,
23247 smooth_neighbor_uv,
23248 fctx,
23249 );
23250 }
23251 }
23252 } else {
23253 push_intra(
23254 2,
23255 cpx,
23256 cpy,
23257 csz,
23258 uv_predict_mode,
23259 angle_delta_uv,
23260 reach,
23261 &ZERO_RESIDUAL[..csz * csz],
23262 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23263 None,
23264 smooth_neighbor_uv,
23265 fctx,
23266 );
23267 }
23268 luma_grid = Grid::Zero(64);
23269 u_grid = Grid::Zero(csz * csz);
23270 v_grid = Grid::Zero(csz * csz);
23271 }
23272 } else if resolved != 4 {
23273 let around = neighbours.around_mi(leaf_mi, 8);
23274 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
23275 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
23276 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
23277 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
23278 // the doubled sum crosses zero (the same class
23279 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
23280 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
23281 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
23282 let chroma_around = if chroma_422 {
23283 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23284 } else {
23285 around
23286 };
23287 if let Some(buf) = &palette_y_buf {
23288 set_palette_pred(buf.clone(), fctx);
23289 }
23290 luma_grid = read_plane(
23291 dec,
23292 cdfs,
23293 if intrabc_dv.is_some() {
23294 inter_txbset_for(8, reduced_tx_set)
23295 } else if reduced_tx_set {
23296 TxbSet::Luma8
23297 } else {
23298 TxbSet::Luma8Set1
23299 },
23300 scans.0,
23301 0,
23302 around[0],
23303 mode,
23304 mode,
23305 angle_delta_y,
23306 reach,
23307 y,
23308 px,
23309 py,
23310 8,
23311 TX8,
23312 base_q_idx,
23313 None,
23314 filter_intra,
23315 None,
23316 smooth_neighbor,
23317 fctx,
23318 )?;
23319 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
23320 // an intrabc block's chroma tx_type is the colocated LUMA transform's
23321 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
23322 if intrabc_dv.is_some() {
23323 fctx.intrabc_chroma_tx
23324 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
23325 }
23326 let ac = alpha.map(|_| cfl_src(px, py, 8));
23327 if chroma_422 {
23328 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
23329 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
23330 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
23331 u_grid = leaf8_chroma422_unit(
23332 dec,
23333 cdfs,
23334 chroma_around[1],
23335 uv_predict_mode,
23336 angle_delta_uv,
23337 reach,
23338 1,
23339 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23340 false,
23341 intrabc_bufs
23342 .as_ref()
23343 .map(|(_, ub, _)| ub.clone())
23344 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23345 u,
23346 cpx,
23347 cpy,
23348 smooth_neighbor_uv,
23349 fctx,
23350 )?;
23351 v_grid = leaf8_chroma422_unit(
23352 dec,
23353 cdfs,
23354 chroma_around[2],
23355 uv_predict_mode,
23356 angle_delta_uv,
23357 reach,
23358 2,
23359 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23360 false,
23361 intrabc_bufs
23362 .as_ref()
23363 .map(|(_, _, vb)| vb.clone())
23364 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23365 v,
23366 cpx,
23367 cpy,
23368 smooth_neighbor_uv,
23369 fctx,
23370 )?;
23371 } else {
23372 if let Some((_, ub, _)) = &intrabc_bufs {
23373 set_palette_pred(ub.clone(), fctx);
23374 } else if let Some((ub, _)) = &palette_uv_bufs {
23375 set_palette_pred(ub.clone(), fctx);
23376 }
23377 u_grid = read_plane(
23378 dec,
23379 cdfs,
23380 cset,
23381 cscan,
23382 1,
23383 around[1],
23384 mode,
23385 uv_predict_mode,
23386 angle_delta_uv,
23387 reach,
23388 u,
23389 cpx,
23390 cpy,
23391 csz,
23392 csz,
23393 base_q_idx,
23394 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23395 None,
23396 None,
23397 smooth_neighbor_uv,
23398 fctx,
23399 )?;
23400 if let Some((_, _, vb)) = &intrabc_bufs {
23401 set_palette_pred(vb.clone(), fctx);
23402 } else if let Some((_, vb)) = &palette_uv_bufs {
23403 set_palette_pred(vb.clone(), fctx);
23404 }
23405 v_grid = read_plane(
23406 dec,
23407 cdfs,
23408 cset,
23409 cscan,
23410 2,
23411 around[2],
23412 mode,
23413 uv_predict_mode,
23414 angle_delta_uv,
23415 reach,
23416 v,
23417 cpx,
23418 cpy,
23419 csz,
23420 csz,
23421 base_q_idx,
23422 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23423 None,
23424 None,
23425 smooth_neighbor_uv,
23426 fctx,
23427 )?;
23428 }
23429 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
23430 // two chroma reads (`decode_block`'s own tail does the same) -- left
23431 // set, every later chroma block would inherit this luma tx_type,
23432 // which picks the scan and the inverse transform.
23433 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23434 } else {
23435 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
23436 // grid of 4x4 transform units, each predicted from the leaf's own
23437 // 8x8 `mode` and reading its own fresh context off the earlier
23438 // units in this same leaf (the same per-TU pattern `decode_block`'s
23439 // multi-TU branch runs at bigger blocks).
23440 let mut first_leaf_tx: Option<TxType> = None;
23441 for tu_row in 0..2 {
23442 for tu_col in 0..2 {
23443 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
23444 let tu_px = px + tu_col * 4;
23445 let tu_py = py + tu_row * 4;
23446 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
23447 if crate::encode::Reach::in_vert_ab() {
23448 hit!(VERT_AB_TX4_HITS);
23449 }
23450 let tu_reach = tu_reach(
23451 8,
23452 8,
23453 tu_col * 4,
23454 tu_row * 4,
23455 4,
23456 reach,
23457 px,
23458 py,
23459 y.width,
23460 y.height,
23461 fctx,
23462 );
23463 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
23464 // Each 4x4 unit predicts from its own window of the block's
23465 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
23466 // 16x16 and up) -- the whole-block buffer would be taken by
23467 // the FIRST unit and indexed at the wrong stride.
23468 if let Some(buf) = &palette_y_buf {
23469 hit!(PALETTE_SPLIT_TX_HITS);
23470 let mut window = vec![0u16; 16];
23471 for row in 0..4 {
23472 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
23473 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
23474 }
23475 set_palette_pred(window, fctx);
23476 }
23477 let tu_grid = read_plane(
23478 dec,
23479 cdfs,
23480 if intrabc_dv.is_some() {
23481 inter_txbset_for(4, reduced_tx_set)
23482 } else if reduced_tx_set {
23483 TxbSet::Luma4
23484 } else {
23485 TxbSet::Luma4Set1
23486 },
23487 scans.1,
23488 0,
23489 tu_around,
23490 mode,
23491 mode,
23492 angle_delta_y,
23493 tu_reach,
23494 y,
23495 tu_px,
23496 tu_py,
23497 4,
23498 4,
23499 base_q_idx,
23500 None,
23501 filter_intra,
23502 Some(tu_skip_ctx),
23503 smooth_neighbor,
23504 fctx,
23505 )?;
23506 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23507 eprintln!(
23508 "TRACE tu_bitpos mi=({},{}) tell={}",
23509 tu_mi.0,
23510 tu_mi.1,
23511 dec.debug_bitpos()
23512 );
23513 }
23514 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
23515 // The FIRST (top-left, co-located with this group's chroma)
23516 // TU's coded tx_type is what the group's chroma inherits --
23517 // the same capture [`decode_block`]'s multi-TU branch makes
23518 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
23519 // an inter-classified block's `PLANE_TYPE_UV` reads
23520 // `tx_type_map`, and intrabc is inter-classified).
23521 if first_leaf_tx.is_none() {
23522 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
23523 }
23524 }
23525 }
23526 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
23527 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
23528 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
23529 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
23530 // the inherited luma type's (R5's first fork: mi (36,66), luma
23531 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
23532 // decoded its `eob` from the wrong CDF row). Same arm the
23533 // `resolved != 4` branch above runs for its whole-leaf unit.
23534 if intrabc_dv.is_some() {
23535 if let Some(t) = first_leaf_tx {
23536 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
23537 }
23538 }
23539 let ac = alpha.map(|_| cfl_src(px, py, 8));
23540 // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm
23541 // above -- the doubled above sum crosses zero at mi(2,24) plane 2.
23542 let chroma_around = if chroma_422 {
23543 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23544 } else {
23545 neighbours.around_mi(leaf_mi, 8)
23546 };
23547 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
23548 // by this arm's chroma reads means the frame-copy + inherited-type
23549 // route ran; zero at gate time means the fixture stopped reaching it.
23550 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
23551 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
23552 }
23553 if chroma_422 {
23554 // lane-av1-422d: the chroma unit does NOT follow the luma var-tx
23555 // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block,
23556 // still the one 4x8 rect unit per plane at ss (1,0).
23557 u_grid = leaf8_chroma422_unit(
23558 dec,
23559 cdfs,
23560 chroma_around[1],
23561 uv_predict_mode,
23562 angle_delta_uv,
23563 reach,
23564 1,
23565 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23566 false,
23567 intrabc_bufs
23568 .as_ref()
23569 .map(|(_, ub, _)| ub.clone())
23570 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23571 u,
23572 cpx,
23573 cpy,
23574 smooth_neighbor_uv,
23575 fctx,
23576 )?;
23577 v_grid = leaf8_chroma422_unit(
23578 dec,
23579 cdfs,
23580 chroma_around[2],
23581 uv_predict_mode,
23582 angle_delta_uv,
23583 reach,
23584 2,
23585 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23586 false,
23587 intrabc_bufs
23588 .as_ref()
23589 .map(|(_, _, vb)| vb.clone())
23590 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23591 v,
23592 cpx,
23593 cpy,
23594 smooth_neighbor_uv,
23595 fctx,
23596 )?;
23597 } else if chroma_444 && lossless(fctx) {
23598 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
23599 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
23600 // lossless forces TX_4X4 on EVERY plane) -- the same walk
23601 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
23602 // TX_8X8 unit here panicked before: the lossless inverse is the
23603 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
23604 // invariant), and the unit count desyncs the tile either way.
23605 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
23606 // inside, which is why the tail's whole-leaf chroma stamp below
23607 // is skipped for this shape.
23608 let (mut uo, mut vo) = (Vec::new(), Vec::new());
23609 read_intra_chroma_lossless(
23610 dec,
23611 cdfs,
23612 neighbours,
23613 u,
23614 v,
23615 leaf_mi,
23616 (px, py),
23617 (cpx, cpy),
23618 8,
23619 (8, 8),
23620 (0, 0),
23621 (8, 8),
23622 8,
23623 reach,
23624 (y.width, y.height),
23625 mode,
23626 uv_predict_mode,
23627 angle_delta_uv,
23628 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
23629 smooth_neighbor_uv,
23630 base_q_idx,
23631 &mut uo,
23632 &mut vo,
23633 fctx,
23634 )?;
23635 u_grid = if uo.is_empty() {
23636 Grid::Zero(64)
23637 } else {
23638 Grid::Own(uo)
23639 };
23640 v_grid = if vo.is_empty() {
23641 Grid::Zero(64)
23642 } else {
23643 Grid::Own(vo)
23644 };
23645 } else {
23646 if let Some((ub, _)) = &palette_uv_bufs {
23647 set_palette_pred(ub.clone(), fctx);
23648 }
23649 u_grid = read_plane(
23650 dec,
23651 cdfs,
23652 cset,
23653 cscan,
23654 1,
23655 chroma_around[1],
23656 mode,
23657 uv_predict_mode,
23658 angle_delta_uv,
23659 reach,
23660 u,
23661 cpx,
23662 cpy,
23663 csz,
23664 csz,
23665 base_q_idx,
23666 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23667 None,
23668 None,
23669 smooth_neighbor_uv,
23670 fctx,
23671 )?;
23672 if let Some((_, vb)) = &palette_uv_bufs {
23673 set_palette_pred(vb.clone(), fctx);
23674 }
23675 v_grid = read_plane(
23676 dec,
23677 cdfs,
23678 cset,
23679 cscan,
23680 2,
23681 chroma_around[2],
23682 mode,
23683 uv_predict_mode,
23684 angle_delta_uv,
23685 reach,
23686 v,
23687 cpx,
23688 cpy,
23689 csz,
23690 csz,
23691 base_q_idx,
23692 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23693 None,
23694 None,
23695 smooth_neighbor_uv,
23696 fctx,
23697 )?;
23698 }
23699 // The two chroma reads above are the only consulters of this leaf's
23700 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
23701 // leaf's chroma inherit this leaf's luma type instead of its own
23702 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
23703 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
23704 // luma's `V_ADST` for its chroma eob row).
23705 if intrabc_dv.is_some() {
23706 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23707 }
23708 // `record_split_luma` expects a `record`-style `(r, c)` position in
23709 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
23710 // already in mi units, so calling it here double-scaled the
23711 // position. Plane 0 is already correct per-TU from the
23712 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
23713 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
23714 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
23715 // leaf's own 8x8 side over `MI`).
23716 let side_mi = 2;
23717 for cell in 0..side_mi {
23718 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
23719 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
23720 }
23721 let round_up_even = |n: usize| n.div_ceil(2) * 2;
23722 let bound_h = round_up_even(neighbours.mi_rows);
23723 let bound_w = round_up_even(neighbours.mi_cols);
23724 let u_state = neighbour_state(&u_grid);
23725 let v_state = neighbour_state(&v_grid);
23726 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
23727 // (its raster-order last writer per cell is exactly libaom's
23728 // per-entry last update); this whole-leaf aggregate would clobber
23729 // four distinct unit states with one, so it runs only for the shapes
23730 // whose chroma really is one unit.
23731 if !(chroma_444 && lossless(fctx)) {
23732 for cell in 0..side_mi {
23733 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
23734 neighbours.left[leaf_mi.0 + cell][1] = u_state;
23735 neighbours.left[leaf_mi.0 + cell][2] = v_state;
23736 }
23737 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
23738 neighbours.above[leaf_mi.1 + cell][1] = u_state;
23739 neighbours.above[leaf_mi.1 + cell][2] = v_state;
23740 }
23741 }
23742 }
23743 // This leaf's own palette state into the mi-granular above/left bands
23744 // (sizes 0 when it used none, which is what clears a previous block's
23745 // palette out of the next block's ctx and colour cache).
23746 {
23747 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
23748 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
23749 }
23750 neighbours.fill_skip_grid(leaf_mi, 2, skip);
23751 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
23752 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
23753 // own copy; only an intrabc var-tx read consumes these bands on the intra
23754 // path, so the write is armed by `allow_intrabc`.
23755 if allow_intrabc {
23756 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
23757 }
23758 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
23759 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
23760 return Ok(mode);
23761 }
23762 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
23763 // This leaf's own palette state into the mi-granular above/left bands
23764 // (sizes 0 when it used none, which is what clears a previous block's
23765 // palette out of the next block's ctx and colour cache).
23766 {
23767 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
23768 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
23769 }
23770 hit!(INTER8_SKIP_BAND_HITS);
23771 neighbours.fill_skip_grid(leaf_mi, 2, skip);
23772 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
23773 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
23774 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
23775 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
23776 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
23777 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
23778 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
23779 // wrong CDF row, so the msac range diverged mid-frame with no refusal
23780 // (class `wrong-alphabet-same-value`; the ReelB key frame at
23781 // -ss 900, first bad luma sample row 186 col 1803).
23782 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
23783 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
23784 // `decode_block`'s own copy for why this stays beside
23785 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
23786 // BLOCK-size term).
23787 if allow_intrabc {
23788 set_txfm_ctxs(
23789 neighbours,
23790 leaf_mi,
23791 resolved,
23792 2,
23793 2,
23794 skip && intrabc_dv.is_some(),
23795 );
23796 }
23797 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
23798 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
23799 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
23800 // publish its own cells exactly like `decode_block` does.
23801 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
23802 Ok(mode)
23803}
23804
23805/// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf
23806/// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and
23807/// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to
23808/// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is
23809/// a single rect unit -- one txb_skip + one scan per plane in the
23810/// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
23811/// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved
23812/// position: the entropy context is the leaf's own 8x8 luma-span
23813/// above/left state (the `chroma_tiled` arm's convention; no `+3`
23814/// plane-block-bigger term -- the unit covers the plane block exactly), the
23815/// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted
23816/// mode supplies the mode-derived default `tx_type` unless an armed
23817/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller
23818/// arms and disarms it, exactly as it does around its square reads).
23819#[allow(clippy::too_many_arguments)]
23820fn leaf8_chroma422_unit(
23821 dec: &mut SymbolDecoder,
23822 cdfs: &mut Cdfs,
23823 around: (bool, bool, i32),
23824 uv_predict_mode: usize,
23825 angle_delta_uv: i32,
23826 reach: Reach,
23827 plane_idx: usize,
23828 cfl: Option<(i32, CflSrc)>,
23829 skip: bool,
23830 // The prediction override the square arms feed through
23831 // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes
23832 // priority over a palette block's colour-index map.
23833 pred_override: Option<Vec<u16>>,
23834 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
23835 // the plane exclusively while the unit's coefficients are parsed.
23836 _plane: &mut PlaneBuf<'static>,
23837 cpx: usize,
23838 cpy: usize,
23839 smooth_neighbor_uv: bool,
23840 fctx: &crate::decode::FrameCtx,
23841) -> Result<Grid> {
23842 // The unit's prediction runs whether or not a residual follows it -- a
23843 // skipped leaf still predicts (the CfL contribution survives a skip),
23844 // and a skipped intrabc leaf still copies the frame at its DV.
23845 if let Some(buf) = pred_override {
23846 set_palette_pred(buf, fctx);
23847 }
23848 if skip {
23849 push_intra_rect(
23850 plane_idx,
23851 cpx,
23852 cpy,
23853 4,
23854 8,
23855 uv_predict_mode,
23856 angle_delta_uv,
23857 reach,
23858 &ZERO_RESIDUAL[..4 * 8],
23859 cfl,
23860 None,
23861 smooth_neighbor_uv,
23862 fctx,
23863 );
23864 return Ok(Grid::Zero(4 * 8));
23865 }
23866 let default_tx = fctx
23867 .intrabc_chroma_tx
23868 .with(std::cell::Cell::get)
23869 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8));
23870 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
23871 let (levels, tx_type) = read_coeffs_rect(
23872 dec,
23873 &mut coding,
23874 &SCAN_4X8,
23875 4,
23876 8,
23877 usize::from(around.0) + usize::from(around.1),
23878 dc_sign_ctx(around.2),
23879 default_tx,
23880 plane_idx,
23881 )?;
23882 let residual = dequant_and_inverse_typed_wh(
23883 &levels,
23884 4,
23885 8,
23886 crate::decode::bit_depth(fctx),
23887 block_q_idx(fctx),
23888 plane_q_delta(plane_idx, fctx).0,
23889 plane_q_delta(plane_idx, fctx).1,
23890 tx_type,
23891 block_iqmatrix(fctx, plane_idx, 4, 8, tx_type),
23892 );
23893 push_intra_rect(
23894 plane_idx,
23895 cpx,
23896 cpy,
23897 4,
23898 8,
23899 uv_predict_mode,
23900 angle_delta_uv,
23901 reach,
23902 &residual,
23903 cfl,
23904 None,
23905 smooth_neighbor_uv,
23906 fctx,
23907 );
23908 Ok(levels)
23909}
23910
23911/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
23912/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
23913/// bottom, where no partition symbol is read at all -- `decode_block` runs
23914/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
23915/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
23916/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
23917/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
23918/// of the 2x2 4x4 group carries chroma syntax at all.
23919#[allow(clippy::too_many_arguments)]
23920fn read_intra_mode_sub8(
23921 dec: &mut SymbolDecoder,
23922 cdfs: &mut Cdfs,
23923 above_mode: usize,
23924 left_mode: usize,
23925 has_chroma: bool,
23926 enable_filter_intra: bool,
23927 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
23928 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
23929 // from the wrong row is the same VALUE with a different interval, so it
23930 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
23931 fi_class: usize,
23932 skip_ctx: usize,
23933 allow_intrabc: bool,
23934 mi_r: usize,
23935 mi_c: usize,
23936 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
23937 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
23938 // left the second mi column at segment 0, which reads back as a
23939 // neighbour's `cdf_index`/prediction two blocks later.
23940 seg_w_mi: usize,
23941 seg_h_mi: usize,
23942 fctx: &crate::decode::FrameCtx,
23943) -> Result<(
23944 bool,
23945 usize,
23946 i32,
23947 Option<(usize, i32, Option<(i32, i32)>)>,
23948 Option<usize>,
23949 Option<(i32, i32)>,
23950)> {
23951 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
23952 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
23953 let has_chroma = has_chroma && !mono(fctx);
23954 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
23955 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
23956 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
23957 if ec_istep {
23958 eprintln!(
23959 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}",
23960 dec.debug_state().0
23961 );
23962 }
23963 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
23964 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
23965 macro_rules! istep {
23966 ($name:literal, $val:expr) => {
23967 if ec_istep {
23968 eprintln!(
23969 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}",
23970 $name,
23971 $val,
23972 dec.debug_state().0
23973 );
23974 }
23975 };
23976 }
23977 // lane-seg2: same `intra_segment_id` placement as the square and rect
23978 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
23979 // like any other block, over its own 1x1 mi footprint. Dropping it here
23980 // both ate a symbol (the tile desynced at the frame's first sub-8x8
23981 // split) and left `cur_segment_id` on the previous block, so the leaf
23982 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
23983 if seg_id_pre_skip(fctx) {
23984 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
23985 }
23986 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
23987 if trace {
23988 eprintln!(
23989 "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}",
23990 skip as i32,
23991 dec.debug_state().0
23992 );
23993 }
23994 istep!("skip", skip as i32);
23995 if !seg_id_pre_skip(fctx) {
23996 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
23997 }
23998 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
23999 istep!("cdef", 0);
24000 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
24001 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
24002 istep!("dq", 0);
24003 if allow_intrabc {
24004 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
24005 if ec_istep {
24006 eprintln!(
24007 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
24008 u8::from(use_intrabc),
24009 dec.debug_state().0
24010 );
24011 }
24012 if use_intrabc {
24013 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
24014 // vector right after the flag and RETURNS -- no y/uv mode, angle
24015 // delta, palette, CfL or filter-intra syntax follows, and the
24016 // block is reconstructed by the INTER path (libaom's
24017 // `is_inter_block` counts an intrabc block), so the caller takes
24018 // the frame-copy prediction + inter residual.
24019 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
24020 // lane-av1txr: the DV travels back in the RETURN value -- it is
24021 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
24022 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
24023 // then `take()` it in the same call), so a sub-8x8 leaf that
24024 // armed it left the vector standing for the NEXT >=8x8 block:
24025 // `warped.obu`'s (38,60) 8x8 intra block took it as its own
24026 // intrabc and read an inter var-tx `txfm_split` where libaom read
24027 // an intra `tx_depth` (class `stale-slot-handoff`).
24028 hit!(INTRABC_HITS);
24029 return Ok((skip, DC_PRED, 0, None, None, Some(dv)));
24030 }
24031 }
24032 let above_ctx = INTRA_MODE_CTX[above_mode];
24033 let left_ctx = INTRA_MODE_CTX[left_mode];
24034 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
24035 istep!("mode", mode);
24036 if trace {
24037 eprintln!(
24038 "TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
24039 dec.debug_state().0
24040 );
24041 }
24042 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
24043 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
24044 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
24045 // symbol. Reading one consumed a symbol the encoder never wrote and
24046 // desynced the tile at the very next element.
24047 let angle_delta_y = 0;
24048 let chroma = if has_chroma {
24049 // `is_cfl_allowed` (blockd.h): at lossless CfL needs the CHROMA plane
24050 // block to be a single TX_4X4 (`cfl_allowed_px`). True for this leaf
24051 // at 4:2:0 (the group's plane block is 4x4) and for a 4:4:4
24052 // `BLOCK_4X4` split leaf, but FALSE for a 4:4:4 `BLOCK_8X4`/`BLOCK_4X8`
24053 // rect leaf, whose plane block is the rect itself -- that shape reads
24054 // the 13-symbol `uv_mode_no_cfl` CDF, and reading the CFL alphabet
24055 // there desynced the tile at the rect leaf's own uv_mode symbol (measured:
24056 // ours consumed the 14-symbol interval where the oracle read 13, first
24057 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
24058 // `wrong-alphabet-same-value`, lane-av1-llsub8).
24059 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {
24060 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
24061 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
24062 } else {
24063 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
24064 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
24065 };
24066 if trace {
24067 eprintln!(
24068 "TRACE sub8 uv_mode value={uv_mode} rng={}",
24069 dec.debug_state().0
24070 );
24071 }
24072 if (9..=12).contains(&uv_mode) {
24073 hit!(SMOOTH_UV_HITS);
24074 }
24075 let alpha = if uv_mode == UV_CFL_PRED {
24076 Some(read_cfl_alphas(dec, cdfs))
24077 } else {
24078 None
24079 };
24080 if (V_PRED..=D67_PRED).contains(&uv_mode) {
24081 hit!(DIRECTIONAL_UV_HITS);
24082 }
24083 // See the luma comment above: no angle delta below 8x8.
24084 let angle_delta_uv = 0;
24085 Some((uv_mode, angle_delta_uv, alpha))
24086 } else {
24087 None
24088 };
24089 let mut filter_intra = None;
24090 if mode == DC_PRED && enable_filter_intra {
24091 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
24092 if trace {
24093 eprintln!(
24094 "TRACE sub8 use_filter_intra value={}",
24095 use_filter_intra as i32
24096 );
24097 }
24098 if use_filter_intra {
24099 hit!(FILTER_INTRA_HITS);
24100 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
24101 filter_intra = Some(fi_mode);
24102 }
24103 }
24104 Ok((skip, mode, angle_delta_y, chroma, filter_intra, None))
24105}
24106/// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0
24107/// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY
24108/// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right
24109/// after its own luma (`read_intra_mode_sub8` already read this leaf's own
24110/// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] /
24111/// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails
24112/// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an
24113/// intrabc leaf predicts a frame copy at its DV with the luma `tx_type`
24114/// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after
24115/// the luma read) -- and a SKIPPED intrabc leaf is still the DV copy, never
24116/// an intra prediction (lane-av1-ibcskip2: libaom's
24117/// `av1_build_inter_predictors_sb` runs for an intrabc block regardless of
24118/// `skip`). The chroma position, reach and entropy-context span are
24119/// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same
24120/// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape.
24121/// Records the leaf's own `uv_mode` map entry and chroma above/left state,
24122/// and returns the (u, v) grids for the caller's coarse slots.
24123#[allow(clippy::too_many_arguments)]
24124fn sub8_leaf_chroma444(
24125 dec: &mut SymbolDecoder,
24126 cdfs: &mut Cdfs,
24127 neighbours: &mut Neighbours,
24128 lmi: (usize, usize),
24129 bw: usize,
24130 bh: usize,
24131 uv_mode: usize,
24132 alpha: Option<(i32, i32)>,
24133 skip: bool,
24134 intrabc_dv: Option<(i32, i32)>,
24135 y: &PlaneBuf<'static>,
24136 u: &mut PlaneBuf<'static>,
24137 v: &mut PlaneBuf<'static>,
24138 scan4: &[u16],
24139 base_q_idx: u8,
24140 smooth_neighbor_uv: bool,
24141 fctx: &crate::decode::FrameCtx,
24142) -> Result<(Grid, Grid, usize, usize)> {
24143 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
24144 DC_PRED
24145 } else {
24146 uv_mode
24147 };
24148 let (w_mi, h_mi) = (bw / MI, bh / MI);
24149 neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode);
24150 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
24151 let square = (bw, bh) == (4, 4);
24152 // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8);
24153 // the square unit takes the leaf's own `Reach::of`, as its luma does.
24154 let reach = if square {
24155 Reach::of(4, px, py, y.width, y.height, fctx)
24156 } else {
24157 Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx)
24158 };
24159 let grids = if let Some(dv) = intrabc_dv.filter(|_| skip) {
24160 // lane-av1-ibcskip2: a SKIPPED intrabc leaf still predicts the frame
24161 // copy at its DV -- libaom's `av1_build_inter_predictors_sb` runs for
24162 // an intrabc block regardless of `skip` (only the residual read is
24163 // dropped), so the reconstruction is the bare DV copy. The intra push
24164 // in the next arm is the NON-intrabc route; predicting DC there
24165 // decoded flat cells where this fixture's oracle copies frame bytes
24166 // (class skipped-intrabc-predicts-intra,
24167 // lanes/av1ibcskip2.report.md). Same armed-palette-slot route the
24168 // leaf's own luma skip arm uses (`decode_leaf_split4` /
24169 // `decode_leaf_rect8`); the caller already flushed the recon queue
24170 // before its luma DV copy, so the source samples are current.
24171 let mut ub = vec![0u16; bw * bh];
24172 mc::predict_with_filter(
24173 &u.data,
24174 u.width,
24175 u.true_width,
24176 u.true_height,
24177 mv_to_q4(px, dv.1, 0),
24178 mv_to_q4(py, dv.0, 0),
24179 bw,
24180 bh,
24181 mc::InterpFilterKind::Bilinear,
24182 &mut ub,
24183 fctx,
24184 );
24185 let mut vb = vec![0u16; bw * bh];
24186 mc::predict_with_filter(
24187 &v.data,
24188 v.width,
24189 v.true_width,
24190 v.true_height,
24191 mv_to_q4(px, dv.1, 0),
24192 mv_to_q4(py, dv.0, 0),
24193 bw,
24194 bh,
24195 mc::InterpFilterKind::Bilinear,
24196 &mut vb,
24197 fctx,
24198 );
24199 hit!(SKIPPED_INTRABC_DV_COPY_HITS);
24200 let zeros = &ZERO_RESIDUAL[..bw * bh];
24201 if square {
24202 set_palette_pred(ub, fctx);
24203 push_intra(
24204 1,
24205 px,
24206 py,
24207 4,
24208 DC_PRED,
24209 0,
24210 reach,
24211 zeros,
24212 None,
24213 None,
24214 smooth_neighbor_uv,
24215 fctx,
24216 );
24217 set_palette_pred(vb, fctx);
24218 push_intra(
24219 2,
24220 px,
24221 py,
24222 4,
24223 DC_PRED,
24224 0,
24225 reach,
24226 zeros,
24227 None,
24228 None,
24229 smooth_neighbor_uv,
24230 fctx,
24231 );
24232 } else {
24233 set_palette_pred(ub, fctx);
24234 push_intra_rect(
24235 1,
24236 px,
24237 py,
24238 bw,
24239 bh,
24240 DC_PRED,
24241 0,
24242 reach,
24243 zeros,
24244 None,
24245 None,
24246 smooth_neighbor_uv,
24247 fctx,
24248 );
24249 set_palette_pred(vb, fctx);
24250 push_intra_rect(
24251 2,
24252 px,
24253 py,
24254 bw,
24255 bh,
24256 DC_PRED,
24257 0,
24258 reach,
24259 zeros,
24260 None,
24261 None,
24262 smooth_neighbor_uv,
24263 fctx,
24264 );
24265 }
24266 // The same arm-without-clear route the 4:2:0 tails count: a skipped
24267 // leaf reads no coefficient, so the inherited chroma `tx_type` is
24268 // dropped unconsumed.
24269 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
24270 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24271 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
24272 } else if skip {
24273 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
24274 if square {
24275 push_intra(
24276 1,
24277 px,
24278 py,
24279 4,
24280 uv_predict_mode,
24281 0,
24282 reach,
24283 &ZERO_RESIDUAL[..16],
24284 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24285 None,
24286 smooth_neighbor_uv,
24287 fctx,
24288 );
24289 push_intra(
24290 2,
24291 px,
24292 py,
24293 4,
24294 uv_predict_mode,
24295 0,
24296 reach,
24297 &ZERO_RESIDUAL[..16],
24298 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24299 None,
24300 smooth_neighbor_uv,
24301 fctx,
24302 );
24303 } else {
24304 push_intra_rect(
24305 1,
24306 px,
24307 py,
24308 bw,
24309 bh,
24310 uv_predict_mode,
24311 0,
24312 reach,
24313 &ZERO_RESIDUAL[..bw * bh],
24314 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24315 None,
24316 smooth_neighbor_uv,
24317 fctx,
24318 );
24319 push_intra_rect(
24320 2,
24321 px,
24322 py,
24323 bw,
24324 bh,
24325 uv_predict_mode,
24326 0,
24327 reach,
24328 &ZERO_RESIDUAL[..bw * bh],
24329 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24330 None,
24331 smooth_neighbor_uv,
24332 fctx,
24333 );
24334 }
24335 // The same arm-without-clear route the 4:2:0 tails count: a skipped
24336 // leaf reads no coefficient, so an armed intrabc slot is dropped.
24337 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
24338 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
24339 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24340 }
24341 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
24342 } else if let Some(dv) = intrabc_dv {
24343 // Frame copy at the DV; the residual still reads the ordinary chroma
24344 // tables with the inherited luma `tx_type` (see the 4:2:0 tails).
24345 let mut ub = vec![0u16; bw * bh];
24346 mc::predict_with_filter(
24347 &u.data,
24348 u.width,
24349 u.true_width,
24350 u.true_height,
24351 mv_to_q4(px, dv.1, 0),
24352 mv_to_q4(py, dv.0, 0),
24353 bw,
24354 bh,
24355 mc::InterpFilterKind::Bilinear,
24356 &mut ub,
24357 fctx,
24358 );
24359 let mut vb = vec![0u16; bw * bh];
24360 mc::predict_with_filter(
24361 &v.data,
24362 v.width,
24363 v.true_width,
24364 v.true_height,
24365 mv_to_q4(px, dv.1, 0),
24366 mv_to_q4(py, dv.0, 0),
24367 bw,
24368 bh,
24369 mc::InterpFilterKind::Bilinear,
24370 &mut vb,
24371 fctx,
24372 );
24373 let around = neighbours.around_mi_rect(lmi, bw, bh);
24374 let pair = if square {
24375 set_palette_pred(ub, fctx);
24376 let ug = read_plane(
24377 dec,
24378 cdfs,
24379 TxbSet::Chroma4,
24380 scan4,
24381 1,
24382 around[1],
24383 DC_PRED,
24384 DC_PRED,
24385 0,
24386 reach,
24387 u,
24388 px,
24389 py,
24390 4,
24391 TX4,
24392 base_q_idx,
24393 None,
24394 None,
24395 None,
24396 smooth_neighbor_uv,
24397 fctx,
24398 )?;
24399 set_palette_pred(vb, fctx);
24400 let vg = read_plane(
24401 dec,
24402 cdfs,
24403 TxbSet::Chroma4,
24404 scan4,
24405 2,
24406 around[2],
24407 DC_PRED,
24408 DC_PRED,
24409 0,
24410 reach,
24411 v,
24412 px,
24413 py,
24414 4,
24415 TX4,
24416 base_q_idx,
24417 None,
24418 None,
24419 None,
24420 smooth_neighbor_uv,
24421 fctx,
24422 )?;
24423 (ug, vg, 4, 4)
24424 } else {
24425 // lane-av1-ibc444rect: the unskipped lossless chroma walk this
24426 // lane fixes (one rect unit -> per-4x4 Chroma4 units).
24427 if lossless(fctx) {
24428 hit!(INTRABC_RECT8_LOSSLESS_CHROMA_HITS);
24429 }
24430 if lossless(fctx) {
24431 // lane-av1-ibc444rect: at lossless `read_tx_size` forces
24432 // TX_4X4 on EVERY plane (`av1_get_tx_size`'s lossless
24433 // first line), so this rect leaf's chroma is (bw/4)*(bh/4)
24434 // TX_4X4 units at their own 4x4 origins -- not the single
24435 // `ChromaRect8x4` rect unit the non-loss

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